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,
61 const PPCSubtarget &STI)
62 : TargetLowering(TM), Subtarget(STI) {
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 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
101 if (Subtarget.useCRBits()) {
102 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
104 if (isPPC64 || Subtarget.hasFPCVT()) {
105 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
106 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
107 isPPC64 ? MVT::i64 : MVT::i32);
108 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
109 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
110 isPPC64 ? MVT::i64 : MVT::i32);
112 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
113 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
116 // PowerPC does not support direct load / store of condition registers
117 setOperationAction(ISD::LOAD, MVT::i1, Custom);
118 setOperationAction(ISD::STORE, MVT::i1, Custom);
120 // FIXME: Remove this once the ANDI glue bug is fixed:
122 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
124 for (MVT VT : MVT::integer_valuetypes()) {
125 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
126 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
127 setTruncStoreAction(VT, MVT::i1, Expand);
130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
133 // This is used in the ppcf128->int sequence. Note it has different semantics
134 // from FP_ROUND: that rounds to nearest, this rounds to zero.
135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137 // We do not currently implement these libm ops for PowerPC.
138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145 // PowerPC has no SREM/UREM instructions
146 setOperationAction(ISD::SREM, MVT::i32, Expand);
147 setOperationAction(ISD::UREM, MVT::i32, Expand);
148 setOperationAction(ISD::SREM, MVT::i64, Expand);
149 setOperationAction(ISD::UREM, MVT::i64, Expand);
151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161 // We don't support sin/cos/sqrt/fmod/pow
162 setOperationAction(ISD::FSIN , MVT::f64, Expand);
163 setOperationAction(ISD::FCOS , MVT::f64, Expand);
164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165 setOperationAction(ISD::FREM , MVT::f64, Expand);
166 setOperationAction(ISD::FPOW , MVT::f64, Expand);
167 setOperationAction(ISD::FMA , MVT::f64, Legal);
168 setOperationAction(ISD::FSIN , MVT::f32, Expand);
169 setOperationAction(ISD::FCOS , MVT::f32, Expand);
170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171 setOperationAction(ISD::FREM , MVT::f32, Expand);
172 setOperationAction(ISD::FPOW , MVT::f32, Expand);
173 setOperationAction(ISD::FMA , MVT::f32, Legal);
175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177 // If we're enabling GP optimizations, use hardware square root
178 if (!Subtarget.hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
181 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183 if (!Subtarget.hasFSQRT() &&
184 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
185 Subtarget.hasFRES()))
186 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188 if (Subtarget.hasFCPSGN()) {
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
196 if (Subtarget.hasFPRND()) {
197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200 setOperationAction(ISD::FROUND, MVT::f64, Legal);
202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205 setOperationAction(ISD::FROUND, MVT::f32, Legal);
208 // PowerPC does not have BSWAP, CTPOP or CTTZ
209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218 if (Subtarget.hasPOPCNTD()) {
219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
226 // PowerPC does not have ROTR
227 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
228 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
230 if (!Subtarget.useCRBits()) {
231 // PowerPC does not have Select
232 setOperationAction(ISD::SELECT, MVT::i32, Expand);
233 setOperationAction(ISD::SELECT, MVT::i64, Expand);
234 setOperationAction(ISD::SELECT, MVT::f32, Expand);
235 setOperationAction(ISD::SELECT, MVT::f64, Expand);
238 // PowerPC wants to turn select_cc of FP into fsel when possible.
239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 // PowerPC wants to optimize integer setcc a bit
243 if (!Subtarget.useCRBits())
244 setOperationAction(ISD::SETCC, MVT::i32, Custom);
246 // PowerPC does not have BRCOND which requires SetCC
247 if (!Subtarget.useCRBits())
248 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 // PowerPC does not have [U|S]INT_TO_FP
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264 // We cannot sextinreg(i1). Expand to shifts.
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269 // support continuation, user-level threading, and etc.. As a result, no
270 // other SjLj exception interfaces are implemented and please don't build
271 // your own exception handling based on them.
272 // LLVM/Clang supports zero-cost DWARF exception handling.
273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276 // We want to legalize GlobalAddress and ConstantPool nodes into the
277 // appropriate instructions to materialize the address.
278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
287 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
292 // TRAMPOLINE is custom lowered.
293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 if (Subtarget.isSVR4ABI()) {
301 // VAARG always uses double-word chunks, so promote anything smaller.
302 setOperationAction(ISD::VAARG, MVT::i1, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i8, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i16, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i32, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::Other, Expand);
312 // VAARG is custom lowered with the 32-bit SVR4 ABI.
313 setOperationAction(ISD::VAARG, MVT::Other, Custom);
314 setOperationAction(ISD::VAARG, MVT::i64, Custom);
317 setOperationAction(ISD::VAARG, MVT::Other, Expand);
319 if (Subtarget.isSVR4ABI() && !isPPC64)
320 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
323 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
325 // Use the default implementation.
326 setOperationAction(ISD::VAEND , MVT::Other, Expand);
327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
332 // We want to custom lower some of our intrinsics.
333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335 // To handle counter-based loop conditions.
336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338 // Comparisons that require checking two conditions.
339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352 if (Subtarget.has64BitSupport()) {
353 // They also have instructions for converting between i64 and fp.
354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358 // This is just the low 32 bits of a (signed) fp->i64 conversion.
359 // We cannot do this with Promote because i64 is not a legal type.
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
369 // With the instructions enabled under FPCVT, we can do everything.
370 if (Subtarget.hasFPCVT()) {
371 if (Subtarget.has64BitSupport()) {
372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
384 if (Subtarget.use64BitRegs()) {
385 // 64-bit PowerPC implementations can support i64 types directly
386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389 // 64-bit PowerPC wants to expand i128 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394 // 32-bit PowerPC wants to expand i64 shifts itself.
395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
400 if (Subtarget.hasAltivec()) {
401 // First set operation action for all vector types to expand. Then we
402 // will selectively turn on ones that can be effectively codegen'd.
403 for (MVT VT : MVT::vector_valuetypes()) {
404 // add/sub are legal for all supported vector VT's.
405 setOperationAction(ISD::ADD , VT, Legal);
406 setOperationAction(ISD::SUB , VT, Legal);
408 // Vector instructions introduced in P8
409 if (Subtarget.hasP8Altivec()) {
410 setOperationAction(ISD::CTPOP, VT, Legal);
411 setOperationAction(ISD::CTLZ, VT, Legal);
414 setOperationAction(ISD::CTPOP, VT, Expand);
415 setOperationAction(ISD::CTLZ, VT, Expand);
418 // We promote all shuffles to v16i8.
419 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
420 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
422 // We promote all non-typed operations to v4i32.
423 setOperationAction(ISD::AND , VT, Promote);
424 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
425 setOperationAction(ISD::OR , VT, Promote);
426 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
427 setOperationAction(ISD::XOR , VT, Promote);
428 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
429 setOperationAction(ISD::LOAD , VT, Promote);
430 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
431 setOperationAction(ISD::SELECT, VT, Promote);
432 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
433 setOperationAction(ISD::STORE, VT, Promote);
434 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
436 // No other operations are legal.
437 setOperationAction(ISD::MUL , VT, Expand);
438 setOperationAction(ISD::SDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UDIV, VT, Expand);
441 setOperationAction(ISD::UREM, VT, Expand);
442 setOperationAction(ISD::FDIV, VT, Expand);
443 setOperationAction(ISD::FREM, VT, Expand);
444 setOperationAction(ISD::FNEG, VT, Expand);
445 setOperationAction(ISD::FSQRT, VT, Expand);
446 setOperationAction(ISD::FLOG, VT, Expand);
447 setOperationAction(ISD::FLOG10, VT, Expand);
448 setOperationAction(ISD::FLOG2, VT, Expand);
449 setOperationAction(ISD::FEXP, VT, Expand);
450 setOperationAction(ISD::FEXP2, VT, Expand);
451 setOperationAction(ISD::FSIN, VT, Expand);
452 setOperationAction(ISD::FCOS, VT, Expand);
453 setOperationAction(ISD::FABS, VT, Expand);
454 setOperationAction(ISD::FPOWI, VT, Expand);
455 setOperationAction(ISD::FFLOOR, VT, Expand);
456 setOperationAction(ISD::FCEIL, VT, Expand);
457 setOperationAction(ISD::FTRUNC, VT, Expand);
458 setOperationAction(ISD::FRINT, VT, Expand);
459 setOperationAction(ISD::FNEARBYINT, VT, Expand);
460 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
461 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
462 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
463 setOperationAction(ISD::MULHU, VT, Expand);
464 setOperationAction(ISD::MULHS, VT, Expand);
465 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
466 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
467 setOperationAction(ISD::UDIVREM, VT, Expand);
468 setOperationAction(ISD::SDIVREM, VT, Expand);
469 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
470 setOperationAction(ISD::FPOW, VT, Expand);
471 setOperationAction(ISD::BSWAP, VT, Expand);
472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
473 setOperationAction(ISD::CTTZ, VT, Expand);
474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
475 setOperationAction(ISD::VSELECT, VT, Expand);
476 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
478 for (MVT InnerVT : MVT::vector_valuetypes()) {
479 setTruncStoreAction(VT, InnerVT, Expand);
480 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
481 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
482 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
486 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
487 // with merges, splats, etc.
488 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
490 setOperationAction(ISD::AND , MVT::v4i32, Legal);
491 setOperationAction(ISD::OR , MVT::v4i32, Legal);
492 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
493 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
494 setOperationAction(ISD::SELECT, MVT::v4i32,
495 Subtarget.useCRBits() ? Legal : Expand);
496 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
497 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
498 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
499 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
500 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
501 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
502 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
503 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
504 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
506 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
507 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
508 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
509 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
511 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
512 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
514 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
515 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
516 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
520 if (Subtarget.hasP8Altivec())
521 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
523 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
525 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
528 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
529 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
531 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
532 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
533 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
534 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
536 // Altivec does not contain unordered floating-point compare instructions
537 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
538 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
539 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
540 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
542 if (Subtarget.hasVSX()) {
543 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
544 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
546 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
547 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
548 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
549 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
550 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
552 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
554 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
555 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
557 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
558 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
560 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
561 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
562 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
563 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
564 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
566 // Share the Altivec comparison restrictions.
567 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
568 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
569 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
570 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
572 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
573 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
575 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
577 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
579 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
580 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
582 if (Subtarget.hasP8Altivec()) {
583 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
584 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
585 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
587 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
590 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
591 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
592 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
594 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
596 // VSX v2i64 only supports non-arithmetic operations.
597 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
598 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
601 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
602 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
603 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
604 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
606 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
608 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
609 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
610 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
611 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
613 // Vector operation legalization checks the result type of
614 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
615 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
616 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
617 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
618 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
620 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
623 if (Subtarget.hasP8Altivec())
624 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
627 if (Subtarget.hasQPX()) {
628 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
629 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
630 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
631 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
633 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
634 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
636 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
637 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
639 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
640 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
642 if (!Subtarget.useCRBits())
643 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
644 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
646 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
647 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
648 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
649 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
650 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
652 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
654 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
655 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
657 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
658 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
659 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
661 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
662 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
663 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
664 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
665 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
666 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
667 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
668 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
669 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
670 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
671 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
673 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
674 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
676 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
677 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
679 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
681 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
682 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
683 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
684 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
686 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
687 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
689 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
690 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
692 if (!Subtarget.useCRBits())
693 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
694 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
696 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
697 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
698 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
699 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
700 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
701 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
702 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
704 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
705 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
707 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
708 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
709 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
710 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
711 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
712 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
713 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
714 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
715 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
716 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
717 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
719 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
720 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
722 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
723 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
725 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
727 setOperationAction(ISD::AND , MVT::v4i1, Legal);
728 setOperationAction(ISD::OR , MVT::v4i1, Legal);
729 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
731 if (!Subtarget.useCRBits())
732 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
733 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
735 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
736 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
738 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
739 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
740 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
741 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
742 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
743 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
744 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
746 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
747 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
749 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
751 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
752 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
753 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
754 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
756 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
757 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
758 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
759 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
761 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
762 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
764 // These need to set FE_INEXACT, and so cannot be vectorized here.
765 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
766 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
768 if (TM.Options.UnsafeFPMath) {
769 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
770 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
772 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
773 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
775 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
776 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
778 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
779 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
783 if (Subtarget.has64BitSupport())
784 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
786 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
789 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
790 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
793 setBooleanContents(ZeroOrOneBooleanContent);
795 if (Subtarget.hasAltivec()) {
796 // Altivec instructions set fields to all zeros or all ones.
797 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
801 // These libcalls are not available in 32-bit.
802 setLibcallName(RTLIB::SHL_I128, nullptr);
803 setLibcallName(RTLIB::SRL_I128, nullptr);
804 setLibcallName(RTLIB::SRA_I128, nullptr);
808 setStackPointerRegisterToSaveRestore(PPC::X1);
809 setExceptionPointerRegister(PPC::X3);
810 setExceptionSelectorRegister(PPC::X4);
812 setStackPointerRegisterToSaveRestore(PPC::R1);
813 setExceptionPointerRegister(PPC::R3);
814 setExceptionSelectorRegister(PPC::R4);
817 // We have target-specific dag combine patterns for the following nodes:
818 setTargetDAGCombine(ISD::SINT_TO_FP);
819 if (Subtarget.hasFPCVT())
820 setTargetDAGCombine(ISD::UINT_TO_FP);
821 setTargetDAGCombine(ISD::LOAD);
822 setTargetDAGCombine(ISD::STORE);
823 setTargetDAGCombine(ISD::BR_CC);
824 if (Subtarget.useCRBits())
825 setTargetDAGCombine(ISD::BRCOND);
826 setTargetDAGCombine(ISD::BSWAP);
827 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
828 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
829 setTargetDAGCombine(ISD::INTRINSIC_VOID);
831 setTargetDAGCombine(ISD::SIGN_EXTEND);
832 setTargetDAGCombine(ISD::ZERO_EXTEND);
833 setTargetDAGCombine(ISD::ANY_EXTEND);
835 if (Subtarget.useCRBits()) {
836 setTargetDAGCombine(ISD::TRUNCATE);
837 setTargetDAGCombine(ISD::SETCC);
838 setTargetDAGCombine(ISD::SELECT_CC);
841 // Use reciprocal estimates.
842 if (TM.Options.UnsafeFPMath) {
843 setTargetDAGCombine(ISD::FDIV);
844 setTargetDAGCombine(ISD::FSQRT);
847 // Darwin long double math library functions have $LDBL128 appended.
848 if (Subtarget.isDarwin()) {
849 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
850 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
851 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
852 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
853 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
854 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
855 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
856 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
857 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
858 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
861 // With 32 condition bits, we don't need to sink (and duplicate) compares
862 // aggressively in CodeGenPrep.
863 if (Subtarget.useCRBits()) {
864 setHasMultipleConditionRegisters();
865 setJumpIsExpensive();
868 setMinFunctionAlignment(2);
869 if (Subtarget.isDarwin())
870 setPrefFunctionAlignment(4);
872 switch (Subtarget.getDarwinDirective()) {
876 case PPC::DIR_E500mc:
885 setPrefFunctionAlignment(4);
886 setPrefLoopAlignment(4);
890 setInsertFencesForAtomic(true);
892 if (Subtarget.enableMachineScheduler())
893 setSchedulingPreference(Sched::Source);
895 setSchedulingPreference(Sched::Hybrid);
897 computeRegisterProperties(STI.getRegisterInfo());
899 // The Freescale cores do better with aggressive inlining of memcpy and
900 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
901 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
902 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
903 MaxStoresPerMemset = 32;
904 MaxStoresPerMemsetOptSize = 16;
905 MaxStoresPerMemcpy = 32;
906 MaxStoresPerMemcpyOptSize = 8;
907 MaxStoresPerMemmove = 32;
908 MaxStoresPerMemmoveOptSize = 8;
909 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
910 // The A2 also benefits from (very) aggressive inlining of memcpy and
911 // friends. The overhead of a the function call, even when warm, can be
912 // over one hundred cycles.
913 MaxStoresPerMemset = 128;
914 MaxStoresPerMemcpy = 128;
915 MaxStoresPerMemmove = 128;
919 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
920 /// the desired ByVal argument alignment.
921 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
922 unsigned MaxMaxAlign) {
923 if (MaxAlign == MaxMaxAlign)
925 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
926 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
928 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
930 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
931 unsigned EltAlign = 0;
932 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
933 if (EltAlign > MaxAlign)
935 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
936 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
937 unsigned EltAlign = 0;
938 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
939 if (EltAlign > MaxAlign)
941 if (MaxAlign == MaxMaxAlign)
947 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
948 /// function arguments in the caller parameter area.
949 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
950 // Darwin passes everything on 4 byte boundary.
951 if (Subtarget.isDarwin())
954 // 16byte and wider vectors are passed on 16byte boundary.
955 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
956 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
957 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
958 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
962 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
964 default: return nullptr;
965 case PPCISD::FSEL: return "PPCISD::FSEL";
966 case PPCISD::FCFID: return "PPCISD::FCFID";
967 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
968 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
969 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
970 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
971 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
972 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
973 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
974 case PPCISD::FRE: return "PPCISD::FRE";
975 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
976 case PPCISD::STFIWX: return "PPCISD::STFIWX";
977 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
978 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
979 case PPCISD::VPERM: return "PPCISD::VPERM";
980 case PPCISD::CMPB: return "PPCISD::CMPB";
981 case PPCISD::Hi: return "PPCISD::Hi";
982 case PPCISD::Lo: return "PPCISD::Lo";
983 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
984 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
985 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
986 case PPCISD::SRL: return "PPCISD::SRL";
987 case PPCISD::SRA: return "PPCISD::SRA";
988 case PPCISD::SHL: return "PPCISD::SHL";
989 case PPCISD::CALL: return "PPCISD::CALL";
990 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
991 case PPCISD::MTCTR: return "PPCISD::MTCTR";
992 case PPCISD::BCTRL: return "PPCISD::BCTRL";
993 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
994 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
995 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
996 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
997 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
998 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
999 case PPCISD::VCMP: return "PPCISD::VCMP";
1000 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1001 case PPCISD::LBRX: return "PPCISD::LBRX";
1002 case PPCISD::STBRX: return "PPCISD::STBRX";
1003 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1004 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1005 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1006 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1007 case PPCISD::BDZ: return "PPCISD::BDZ";
1008 case PPCISD::MFFS: return "PPCISD::MFFS";
1009 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1010 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1011 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1012 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1013 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1014 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1015 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1016 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1017 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1018 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1019 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1020 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1021 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1022 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1023 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1024 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1025 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1026 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1027 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1028 case PPCISD::SC: return "PPCISD::SC";
1029 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1030 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1031 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1032 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1033 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1034 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1038 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1040 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1042 if (Subtarget.hasQPX())
1043 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1045 return VT.changeVectorElementTypeToInteger();
1048 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1049 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1053 //===----------------------------------------------------------------------===//
1054 // Node matching predicates, for use by the tblgen matching code.
1055 //===----------------------------------------------------------------------===//
1057 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1058 static bool isFloatingPointZero(SDValue Op) {
1059 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1060 return CFP->getValueAPF().isZero();
1061 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1062 // Maybe this has already been legalized into the constant pool?
1063 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1064 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1065 return CFP->getValueAPF().isZero();
1070 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1071 /// true if Op is undef or if it matches the specified value.
1072 static bool isConstantOrUndef(int Op, int Val) {
1073 return Op < 0 || Op == Val;
1076 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1077 /// VPKUHUM instruction.
1078 /// The ShuffleKind distinguishes between big-endian operations with
1079 /// two different inputs (0), either-endian operations with two identical
1080 /// inputs (1), and little-endian operantion with two different inputs (2).
1081 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1082 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1083 SelectionDAG &DAG) {
1084 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1085 if (ShuffleKind == 0) {
1088 for (unsigned i = 0; i != 16; ++i)
1089 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1091 } else if (ShuffleKind == 2) {
1094 for (unsigned i = 0; i != 16; ++i)
1095 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1097 } else if (ShuffleKind == 1) {
1098 unsigned j = IsLE ? 0 : 1;
1099 for (unsigned i = 0; i != 8; ++i)
1100 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1101 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1107 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1108 /// VPKUWUM instruction.
1109 /// The ShuffleKind distinguishes between big-endian operations with
1110 /// two different inputs (0), either-endian operations with two identical
1111 /// inputs (1), and little-endian operantion with two different inputs (2).
1112 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1113 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1114 SelectionDAG &DAG) {
1115 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1116 if (ShuffleKind == 0) {
1119 for (unsigned i = 0; i != 16; i += 2)
1120 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1121 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1123 } else if (ShuffleKind == 2) {
1126 for (unsigned i = 0; i != 16; i += 2)
1127 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1128 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1130 } else if (ShuffleKind == 1) {
1131 unsigned j = IsLE ? 0 : 2;
1132 for (unsigned i = 0; i != 8; i += 2)
1133 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1134 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1135 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1136 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1142 /// isVMerge - Common function, used to match vmrg* shuffles.
1144 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1145 unsigned LHSStart, unsigned RHSStart) {
1146 if (N->getValueType(0) != MVT::v16i8)
1148 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1149 "Unsupported merge size!");
1151 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1152 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1153 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1154 LHSStart+j+i*UnitSize) ||
1155 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1156 RHSStart+j+i*UnitSize))
1162 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1163 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1164 /// The ShuffleKind distinguishes between big-endian merges with two
1165 /// different inputs (0), either-endian merges with two identical inputs (1),
1166 /// and little-endian merges with two different inputs (2). For the latter,
1167 /// the input operands are swapped (see PPCInstrAltivec.td).
1168 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1169 unsigned ShuffleKind, SelectionDAG &DAG) {
1170 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1171 if (ShuffleKind == 1) // unary
1172 return isVMerge(N, UnitSize, 0, 0);
1173 else if (ShuffleKind == 2) // swapped
1174 return isVMerge(N, UnitSize, 0, 16);
1178 if (ShuffleKind == 1) // unary
1179 return isVMerge(N, UnitSize, 8, 8);
1180 else if (ShuffleKind == 0) // normal
1181 return isVMerge(N, UnitSize, 8, 24);
1187 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1188 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1189 /// The ShuffleKind distinguishes between big-endian merges with two
1190 /// different inputs (0), either-endian merges with two identical inputs (1),
1191 /// and little-endian merges with two different inputs (2). For the latter,
1192 /// the input operands are swapped (see PPCInstrAltivec.td).
1193 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1194 unsigned ShuffleKind, SelectionDAG &DAG) {
1195 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1196 if (ShuffleKind == 1) // unary
1197 return isVMerge(N, UnitSize, 8, 8);
1198 else if (ShuffleKind == 2) // swapped
1199 return isVMerge(N, UnitSize, 8, 24);
1203 if (ShuffleKind == 1) // unary
1204 return isVMerge(N, UnitSize, 0, 0);
1205 else if (ShuffleKind == 0) // normal
1206 return isVMerge(N, UnitSize, 0, 16);
1213 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1214 /// amount, otherwise return -1.
1215 /// The ShuffleKind distinguishes between big-endian operations with two
1216 /// different inputs (0), either-endian operations with two identical inputs
1217 /// (1), and little-endian operations with two different inputs (2). For the
1218 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1219 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1220 SelectionDAG &DAG) {
1221 if (N->getValueType(0) != MVT::v16i8)
1224 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1226 // Find the first non-undef value in the shuffle mask.
1228 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1231 if (i == 16) return -1; // all undef.
1233 // Otherwise, check to see if the rest of the elements are consecutively
1234 // numbered from this value.
1235 unsigned ShiftAmt = SVOp->getMaskElt(i);
1236 if (ShiftAmt < i) return -1;
1239 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1241 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1242 // Check the rest of the elements to see if they are consecutive.
1243 for (++i; i != 16; ++i)
1244 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1246 } else if (ShuffleKind == 1) {
1247 // Check the rest of the elements to see if they are consecutive.
1248 for (++i; i != 16; ++i)
1249 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1254 if (ShuffleKind == 2 && isLE)
1255 ShiftAmt = 16 - ShiftAmt;
1260 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1261 /// specifies a splat of a single element that is suitable for input to
1262 /// VSPLTB/VSPLTH/VSPLTW.
1263 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1264 assert(N->getValueType(0) == MVT::v16i8 &&
1265 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1267 // This is a splat operation if each element of the permute is the same, and
1268 // if the value doesn't reference the second vector.
1269 unsigned ElementBase = N->getMaskElt(0);
1271 // FIXME: Handle UNDEF elements too!
1272 if (ElementBase >= 16)
1275 // Check that the indices are consecutive, in the case of a multi-byte element
1276 // splatted with a v16i8 mask.
1277 for (unsigned i = 1; i != EltSize; ++i)
1278 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1281 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1282 if (N->getMaskElt(i) < 0) continue;
1283 for (unsigned j = 0; j != EltSize; ++j)
1284 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1290 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1292 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1293 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1295 APInt APVal, APUndef;
1299 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1300 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1301 return CFP->getValueAPF().isNegZero();
1306 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1307 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1308 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1309 SelectionDAG &DAG) {
1310 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1311 assert(isSplatShuffleMask(SVOp, EltSize));
1312 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1313 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1315 return SVOp->getMaskElt(0) / EltSize;
1318 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1319 /// by using a vspltis[bhw] instruction of the specified element size, return
1320 /// the constant being splatted. The ByteSize field indicates the number of
1321 /// bytes of each element [124] -> [bhw].
1322 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1323 SDValue OpVal(nullptr, 0);
1325 // If ByteSize of the splat is bigger than the element size of the
1326 // build_vector, then we have a case where we are checking for a splat where
1327 // multiple elements of the buildvector are folded together into a single
1328 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1329 unsigned EltSize = 16/N->getNumOperands();
1330 if (EltSize < ByteSize) {
1331 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1332 SDValue UniquedVals[4];
1333 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1335 // See if all of the elements in the buildvector agree across.
1336 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1337 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1338 // If the element isn't a constant, bail fully out.
1339 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1342 if (!UniquedVals[i&(Multiple-1)].getNode())
1343 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1344 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1345 return SDValue(); // no match.
1348 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1349 // either constant or undef values that are identical for each chunk. See
1350 // if these chunks can form into a larger vspltis*.
1352 // Check to see if all of the leading entries are either 0 or -1. If
1353 // neither, then this won't fit into the immediate field.
1354 bool LeadingZero = true;
1355 bool LeadingOnes = true;
1356 for (unsigned i = 0; i != Multiple-1; ++i) {
1357 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1359 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1360 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1362 // Finally, check the least significant entry.
1364 if (!UniquedVals[Multiple-1].getNode())
1365 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1366 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1368 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1371 if (!UniquedVals[Multiple-1].getNode())
1372 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1373 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1374 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1375 return DAG.getTargetConstant(Val, MVT::i32);
1381 // Check to see if this buildvec has a single non-undef value in its elements.
1382 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1383 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1384 if (!OpVal.getNode())
1385 OpVal = N->getOperand(i);
1386 else if (OpVal != N->getOperand(i))
1390 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1392 unsigned ValSizeInBytes = EltSize;
1394 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1395 Value = CN->getZExtValue();
1396 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1397 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1398 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1401 // If the splat value is larger than the element value, then we can never do
1402 // this splat. The only case that we could fit the replicated bits into our
1403 // immediate field for would be zero, and we prefer to use vxor for it.
1404 if (ValSizeInBytes < ByteSize) return SDValue();
1406 // If the element value is larger than the splat value, cut it in half and
1407 // check to see if the two halves are equal. Continue doing this until we
1408 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1409 while (ValSizeInBytes > ByteSize) {
1410 ValSizeInBytes >>= 1;
1412 // If the top half equals the bottom half, we're still ok.
1413 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1414 (Value & ((1 << (8*ValSizeInBytes))-1)))
1418 // Properly sign extend the value.
1419 int MaskVal = SignExtend32(Value, ByteSize * 8);
1421 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1422 if (MaskVal == 0) return SDValue();
1424 // Finally, if this value fits in a 5 bit sext field, return it
1425 if (SignExtend32<5>(MaskVal) == MaskVal)
1426 return DAG.getTargetConstant(MaskVal, MVT::i32);
1430 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1431 /// amount, otherwise return -1.
1432 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1433 EVT VT = N->getValueType(0);
1434 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1437 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1439 // Find the first non-undef value in the shuffle mask.
1441 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1444 if (i == 4) return -1; // all undef.
1446 // Otherwise, check to see if the rest of the elements are consecutively
1447 // numbered from this value.
1448 unsigned ShiftAmt = SVOp->getMaskElt(i);
1449 if (ShiftAmt < i) return -1;
1452 // Check the rest of the elements to see if they are consecutive.
1453 for (++i; i != 4; ++i)
1454 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1460 //===----------------------------------------------------------------------===//
1461 // Addressing Mode Selection
1462 //===----------------------------------------------------------------------===//
1464 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1465 /// or 64-bit immediate, and if the value can be accurately represented as a
1466 /// sign extension from a 16-bit value. If so, this returns true and the
1468 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1469 if (!isa<ConstantSDNode>(N))
1472 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1473 if (N->getValueType(0) == MVT::i32)
1474 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1476 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1478 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1479 return isIntS16Immediate(Op.getNode(), Imm);
1483 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1484 /// can be represented as an indexed [r+r] operation. Returns false if it
1485 /// can be more efficiently represented with [r+imm].
1486 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1488 SelectionDAG &DAG) const {
1490 if (N.getOpcode() == ISD::ADD) {
1491 if (isIntS16Immediate(N.getOperand(1), imm))
1492 return false; // r+i
1493 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1494 return false; // r+i
1496 Base = N.getOperand(0);
1497 Index = N.getOperand(1);
1499 } else if (N.getOpcode() == ISD::OR) {
1500 if (isIntS16Immediate(N.getOperand(1), imm))
1501 return false; // r+i can fold it if we can.
1503 // If this is an or of disjoint bitfields, we can codegen this as an add
1504 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1506 APInt LHSKnownZero, LHSKnownOne;
1507 APInt RHSKnownZero, RHSKnownOne;
1508 DAG.computeKnownBits(N.getOperand(0),
1509 LHSKnownZero, LHSKnownOne);
1511 if (LHSKnownZero.getBoolValue()) {
1512 DAG.computeKnownBits(N.getOperand(1),
1513 RHSKnownZero, RHSKnownOne);
1514 // If all of the bits are known zero on the LHS or RHS, the add won't
1516 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1517 Base = N.getOperand(0);
1518 Index = N.getOperand(1);
1527 // If we happen to be doing an i64 load or store into a stack slot that has
1528 // less than a 4-byte alignment, then the frame-index elimination may need to
1529 // use an indexed load or store instruction (because the offset may not be a
1530 // multiple of 4). The extra register needed to hold the offset comes from the
1531 // register scavenger, and it is possible that the scavenger will need to use
1532 // an emergency spill slot. As a result, we need to make sure that a spill slot
1533 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1535 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1536 // FIXME: This does not handle the LWA case.
1540 // NOTE: We'll exclude negative FIs here, which come from argument
1541 // lowering, because there are no known test cases triggering this problem
1542 // using packed structures (or similar). We can remove this exclusion if
1543 // we find such a test case. The reason why this is so test-case driven is
1544 // because this entire 'fixup' is only to prevent crashes (from the
1545 // register scavenger) on not-really-valid inputs. For example, if we have:
1547 // %b = bitcast i1* %a to i64*
1548 // store i64* a, i64 b
1549 // then the store should really be marked as 'align 1', but is not. If it
1550 // were marked as 'align 1' then the indexed form would have been
1551 // instruction-selected initially, and the problem this 'fixup' is preventing
1552 // won't happen regardless.
1556 MachineFunction &MF = DAG.getMachineFunction();
1557 MachineFrameInfo *MFI = MF.getFrameInfo();
1559 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1563 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1564 FuncInfo->setHasNonRISpills();
1567 /// Returns true if the address N can be represented by a base register plus
1568 /// a signed 16-bit displacement [r+imm], and if it is not better
1569 /// represented as reg+reg. If Aligned is true, only accept displacements
1570 /// suitable for STD and friends, i.e. multiples of 4.
1571 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1574 bool Aligned) const {
1575 // FIXME dl should come from parent load or store, not from address
1577 // If this can be more profitably realized as r+r, fail.
1578 if (SelectAddressRegReg(N, Disp, Base, DAG))
1581 if (N.getOpcode() == ISD::ADD) {
1583 if (isIntS16Immediate(N.getOperand(1), imm) &&
1584 (!Aligned || (imm & 3) == 0)) {
1585 Disp = DAG.getTargetConstant(imm, N.getValueType());
1586 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1587 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1588 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1590 Base = N.getOperand(0);
1592 return true; // [r+i]
1593 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1594 // Match LOAD (ADD (X, Lo(G))).
1595 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1596 && "Cannot handle constant offsets yet!");
1597 Disp = N.getOperand(1).getOperand(0); // The global address.
1598 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1599 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1600 Disp.getOpcode() == ISD::TargetConstantPool ||
1601 Disp.getOpcode() == ISD::TargetJumpTable);
1602 Base = N.getOperand(0);
1603 return true; // [&g+r]
1605 } else if (N.getOpcode() == ISD::OR) {
1607 if (isIntS16Immediate(N.getOperand(1), imm) &&
1608 (!Aligned || (imm & 3) == 0)) {
1609 // If this is an or of disjoint bitfields, we can codegen this as an add
1610 // (for better address arithmetic) if the LHS and RHS of the OR are
1611 // provably disjoint.
1612 APInt LHSKnownZero, LHSKnownOne;
1613 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1615 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1616 // If all of the bits are known zero on the LHS or RHS, the add won't
1618 if (FrameIndexSDNode *FI =
1619 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1620 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1621 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1623 Base = N.getOperand(0);
1625 Disp = DAG.getTargetConstant(imm, N.getValueType());
1629 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1630 // Loading from a constant address.
1632 // If this address fits entirely in a 16-bit sext immediate field, codegen
1635 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1636 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1637 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1638 CN->getValueType(0));
1642 // Handle 32-bit sext immediates with LIS + addr mode.
1643 if ((CN->getValueType(0) == MVT::i32 ||
1644 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1645 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1646 int Addr = (int)CN->getZExtValue();
1648 // Otherwise, break this down into an LIS + disp.
1649 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1651 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1652 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1653 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1658 Disp = DAG.getTargetConstant(0, getPointerTy());
1659 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1660 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1661 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1664 return true; // [r+0]
1667 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1668 /// represented as an indexed [r+r] operation.
1669 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1671 SelectionDAG &DAG) const {
1672 // Check to see if we can easily represent this as an [r+r] address. This
1673 // will fail if it thinks that the address is more profitably represented as
1674 // reg+imm, e.g. where imm = 0.
1675 if (SelectAddressRegReg(N, Base, Index, DAG))
1678 // If the operand is an addition, always emit this as [r+r], since this is
1679 // better (for code size, and execution, as the memop does the add for free)
1680 // than emitting an explicit add.
1681 if (N.getOpcode() == ISD::ADD) {
1682 Base = N.getOperand(0);
1683 Index = N.getOperand(1);
1687 // Otherwise, do it the hard way, using R0 as the base register.
1688 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1694 /// getPreIndexedAddressParts - returns true by value, base pointer and
1695 /// offset pointer and addressing mode by reference if the node's address
1696 /// can be legally represented as pre-indexed load / store address.
1697 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1699 ISD::MemIndexedMode &AM,
1700 SelectionDAG &DAG) const {
1701 if (DisablePPCPreinc) return false;
1707 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1708 Ptr = LD->getBasePtr();
1709 VT = LD->getMemoryVT();
1710 Alignment = LD->getAlignment();
1711 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1712 Ptr = ST->getBasePtr();
1713 VT = ST->getMemoryVT();
1714 Alignment = ST->getAlignment();
1719 // PowerPC doesn't have preinc load/store instructions for vectors (except
1720 // for QPX, which does have preinc r+r forms).
1721 if (VT.isVector()) {
1722 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1724 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1730 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1732 // Common code will reject creating a pre-inc form if the base pointer
1733 // is a frame index, or if N is a store and the base pointer is either
1734 // the same as or a predecessor of the value being stored. Check for
1735 // those situations here, and try with swapped Base/Offset instead.
1738 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1741 SDValue Val = cast<StoreSDNode>(N)->getValue();
1742 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1747 std::swap(Base, Offset);
1753 // LDU/STU can only handle immediates that are a multiple of 4.
1754 if (VT != MVT::i64) {
1755 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1758 // LDU/STU need an address with at least 4-byte alignment.
1762 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1766 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1767 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1768 // sext i32 to i64 when addr mode is r+i.
1769 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1770 LD->getExtensionType() == ISD::SEXTLOAD &&
1771 isa<ConstantSDNode>(Offset))
1779 //===----------------------------------------------------------------------===//
1780 // LowerOperation implementation
1781 //===----------------------------------------------------------------------===//
1783 /// GetLabelAccessInfo - Return true if we should reference labels using a
1784 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1785 static bool GetLabelAccessInfo(const TargetMachine &TM,
1786 const PPCSubtarget &Subtarget,
1787 unsigned &HiOpFlags, unsigned &LoOpFlags,
1788 const GlobalValue *GV = nullptr) {
1789 HiOpFlags = PPCII::MO_HA;
1790 LoOpFlags = PPCII::MO_LO;
1792 // Don't use the pic base if not in PIC relocation model.
1793 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1796 HiOpFlags |= PPCII::MO_PIC_FLAG;
1797 LoOpFlags |= PPCII::MO_PIC_FLAG;
1800 // If this is a reference to a global value that requires a non-lazy-ptr, make
1801 // sure that instruction lowering adds it.
1802 if (GV && Subtarget.hasLazyResolverStub(GV)) {
1803 HiOpFlags |= PPCII::MO_NLP_FLAG;
1804 LoOpFlags |= PPCII::MO_NLP_FLAG;
1806 if (GV->hasHiddenVisibility()) {
1807 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1808 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1815 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1816 SelectionDAG &DAG) {
1817 EVT PtrVT = HiPart.getValueType();
1818 SDValue Zero = DAG.getConstant(0, PtrVT);
1821 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1822 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1824 // With PIC, the first instruction is actually "GR+hi(&G)".
1826 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1827 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1829 // Generate non-pic code that has direct accesses to the constant pool.
1830 // The address of the global is just (hi(&g)+lo(&g)).
1831 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1834 static void setUsesTOCBasePtr(MachineFunction &MF) {
1835 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1836 FuncInfo->setUsesTOCBasePtr();
1839 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1840 setUsesTOCBasePtr(DAG.getMachineFunction());
1843 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1845 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1846 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1847 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1849 SDValue Ops[] = { GA, Reg };
1850 return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1851 DAG.getVTList(VT, MVT::Other), Ops, VT,
1852 MachinePointerInfo::getGOT(), 0, false, true,
1856 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1857 SelectionDAG &DAG) const {
1858 EVT PtrVT = Op.getValueType();
1859 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1860 const Constant *C = CP->getConstVal();
1862 // 64-bit SVR4 ABI code is always position-independent.
1863 // The actual address of the GlobalValue is stored in the TOC.
1864 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1865 setUsesTOCBasePtr(DAG);
1866 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1867 return getTOCEntry(DAG, SDLoc(CP), true, GA);
1870 unsigned MOHiFlag, MOLoFlag;
1872 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1874 if (isPIC && Subtarget.isSVR4ABI()) {
1875 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1876 PPCII::MO_PIC_FLAG);
1877 return getTOCEntry(DAG, SDLoc(CP), false, GA);
1881 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1883 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1884 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1887 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1888 EVT PtrVT = Op.getValueType();
1889 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1891 // 64-bit SVR4 ABI code is always position-independent.
1892 // The actual address of the GlobalValue is stored in the TOC.
1893 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1894 setUsesTOCBasePtr(DAG);
1895 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1896 return getTOCEntry(DAG, SDLoc(JT), true, GA);
1899 unsigned MOHiFlag, MOLoFlag;
1901 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1903 if (isPIC && Subtarget.isSVR4ABI()) {
1904 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1905 PPCII::MO_PIC_FLAG);
1906 return getTOCEntry(DAG, SDLoc(GA), false, GA);
1909 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1910 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1911 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1914 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1915 SelectionDAG &DAG) const {
1916 EVT PtrVT = Op.getValueType();
1917 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1918 const BlockAddress *BA = BASDN->getBlockAddress();
1920 // 64-bit SVR4 ABI code is always position-independent.
1921 // The actual BlockAddress is stored in the TOC.
1922 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1923 setUsesTOCBasePtr(DAG);
1924 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1925 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1928 unsigned MOHiFlag, MOLoFlag;
1930 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1931 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1932 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1933 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1936 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1937 SelectionDAG &DAG) const {
1939 // FIXME: TLS addresses currently use medium model code sequences,
1940 // which is the most useful form. Eventually support for small and
1941 // large models could be added if users need it, at the cost of
1942 // additional complexity.
1943 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1945 const GlobalValue *GV = GA->getGlobal();
1946 EVT PtrVT = getPointerTy();
1947 bool is64bit = Subtarget.isPPC64();
1948 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1949 PICLevel::Level picLevel = M->getPICLevel();
1951 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1953 if (Model == TLSModel::LocalExec) {
1954 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1955 PPCII::MO_TPREL_HA);
1956 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1957 PPCII::MO_TPREL_LO);
1958 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1959 is64bit ? MVT::i64 : MVT::i32);
1960 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1961 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1964 if (Model == TLSModel::InitialExec) {
1965 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1966 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1970 setUsesTOCBasePtr(DAG);
1971 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1972 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1973 PtrVT, GOTReg, TGA);
1975 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1976 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1977 PtrVT, TGA, GOTPtr);
1978 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1981 if (Model == TLSModel::GeneralDynamic) {
1982 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1985 setUsesTOCBasePtr(DAG);
1986 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1987 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1990 if (picLevel == PICLevel::Small)
1991 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1993 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1995 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1999 if (Model == TLSModel::LocalDynamic) {
2000 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2003 setUsesTOCBasePtr(DAG);
2004 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2005 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2008 if (picLevel == PICLevel::Small)
2009 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2011 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2013 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2014 PtrVT, GOTPtr, TGA, TGA);
2015 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2016 PtrVT, TLSAddr, TGA);
2017 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2020 llvm_unreachable("Unknown TLS model!");
2023 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2024 SelectionDAG &DAG) const {
2025 EVT PtrVT = Op.getValueType();
2026 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2028 const GlobalValue *GV = GSDN->getGlobal();
2030 // 64-bit SVR4 ABI code is always position-independent.
2031 // The actual address of the GlobalValue is stored in the TOC.
2032 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2033 setUsesTOCBasePtr(DAG);
2034 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2035 return getTOCEntry(DAG, DL, true, GA);
2038 unsigned MOHiFlag, MOLoFlag;
2040 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2042 if (isPIC && Subtarget.isSVR4ABI()) {
2043 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2045 PPCII::MO_PIC_FLAG);
2046 return getTOCEntry(DAG, DL, false, GA);
2050 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2052 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2054 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2056 // If the global reference is actually to a non-lazy-pointer, we have to do an
2057 // extra load to get the address of the global.
2058 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2059 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2060 false, false, false, 0);
2064 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2065 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2068 if (Op.getValueType() == MVT::v2i64) {
2069 // When the operands themselves are v2i64 values, we need to do something
2070 // special because VSX has no underlying comparison operations for these.
2071 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2072 // Equality can be handled by casting to the legal type for Altivec
2073 // comparisons, everything else needs to be expanded.
2074 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2075 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2076 DAG.getSetCC(dl, MVT::v4i32,
2077 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2078 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2085 // We handle most of these in the usual way.
2089 // If we're comparing for equality to zero, expose the fact that this is
2090 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2091 // fold the new nodes.
2092 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2093 if (C->isNullValue() && CC == ISD::SETEQ) {
2094 EVT VT = Op.getOperand(0).getValueType();
2095 SDValue Zext = Op.getOperand(0);
2096 if (VT.bitsLT(MVT::i32)) {
2098 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2100 unsigned Log2b = Log2_32(VT.getSizeInBits());
2101 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2102 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2103 DAG.getConstant(Log2b, MVT::i32));
2104 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2106 // Leave comparisons against 0 and -1 alone for now, since they're usually
2107 // optimized. FIXME: revisit this when we can custom lower all setcc
2109 if (C->isAllOnesValue() || C->isNullValue())
2113 // If we have an integer seteq/setne, turn it into a compare against zero
2114 // by xor'ing the rhs with the lhs, which is faster than setting a
2115 // condition register, reading it back out, and masking the correct bit. The
2116 // normal approach here uses sub to do this instead of xor. Using xor exposes
2117 // the result to other bit-twiddling opportunities.
2118 EVT LHSVT = Op.getOperand(0).getValueType();
2119 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2120 EVT VT = Op.getValueType();
2121 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2123 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2128 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2129 const PPCSubtarget &Subtarget) const {
2130 SDNode *Node = Op.getNode();
2131 EVT VT = Node->getValueType(0);
2132 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2133 SDValue InChain = Node->getOperand(0);
2134 SDValue VAListPtr = Node->getOperand(1);
2135 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2138 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2141 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2142 VAListPtr, MachinePointerInfo(SV), MVT::i8,
2143 false, false, false, 0);
2144 InChain = GprIndex.getValue(1);
2146 if (VT == MVT::i64) {
2147 // Check if GprIndex is even
2148 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2149 DAG.getConstant(1, MVT::i32));
2150 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2151 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2152 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2153 DAG.getConstant(1, MVT::i32));
2154 // Align GprIndex to be even if it isn't
2155 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2159 // fpr index is 1 byte after gpr
2160 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2161 DAG.getConstant(1, MVT::i32));
2164 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2165 FprPtr, MachinePointerInfo(SV), MVT::i8,
2166 false, false, false, 0);
2167 InChain = FprIndex.getValue(1);
2169 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2170 DAG.getConstant(8, MVT::i32));
2172 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2173 DAG.getConstant(4, MVT::i32));
2176 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2177 MachinePointerInfo(), false, false,
2179 InChain = OverflowArea.getValue(1);
2181 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2182 MachinePointerInfo(), false, false,
2184 InChain = RegSaveArea.getValue(1);
2186 // select overflow_area if index > 8
2187 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2188 DAG.getConstant(8, MVT::i32), ISD::SETLT);
2190 // adjustment constant gpr_index * 4/8
2191 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2192 VT.isInteger() ? GprIndex : FprIndex,
2193 DAG.getConstant(VT.isInteger() ? 4 : 8,
2196 // OurReg = RegSaveArea + RegConstant
2197 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2200 // Floating types are 32 bytes into RegSaveArea
2201 if (VT.isFloatingPoint())
2202 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2203 DAG.getConstant(32, MVT::i32));
2205 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2206 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2207 VT.isInteger() ? GprIndex : FprIndex,
2208 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2211 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2212 VT.isInteger() ? VAListPtr : FprPtr,
2213 MachinePointerInfo(SV),
2214 MVT::i8, false, false, 0);
2216 // determine if we should load from reg_save_area or overflow_area
2217 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2219 // increase overflow_area by 4/8 if gpr/fpr > 8
2220 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2221 DAG.getConstant(VT.isInteger() ? 4 : 8,
2224 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2227 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2229 MachinePointerInfo(),
2230 MVT::i32, false, false, 0);
2232 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2233 false, false, false, 0);
2236 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2237 const PPCSubtarget &Subtarget) const {
2238 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2240 // We have to copy the entire va_list struct:
2241 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2242 return DAG.getMemcpy(Op.getOperand(0), Op,
2243 Op.getOperand(1), Op.getOperand(2),
2244 DAG.getConstant(12, MVT::i32), 8, false, true,
2245 MachinePointerInfo(), MachinePointerInfo());
2248 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2249 SelectionDAG &DAG) const {
2250 return Op.getOperand(0);
2253 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2254 SelectionDAG &DAG) const {
2255 SDValue Chain = Op.getOperand(0);
2256 SDValue Trmp = Op.getOperand(1); // trampoline
2257 SDValue FPtr = Op.getOperand(2); // nested function
2258 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2261 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2262 bool isPPC64 = (PtrVT == MVT::i64);
2264 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2267 TargetLowering::ArgListTy Args;
2268 TargetLowering::ArgListEntry Entry;
2270 Entry.Ty = IntPtrTy;
2271 Entry.Node = Trmp; Args.push_back(Entry);
2273 // TrampSize == (isPPC64 ? 48 : 40);
2274 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2275 isPPC64 ? MVT::i64 : MVT::i32);
2276 Args.push_back(Entry);
2278 Entry.Node = FPtr; Args.push_back(Entry);
2279 Entry.Node = Nest; Args.push_back(Entry);
2281 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2282 TargetLowering::CallLoweringInfo CLI(DAG);
2283 CLI.setDebugLoc(dl).setChain(Chain)
2284 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2285 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2286 std::move(Args), 0);
2288 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2289 return CallResult.second;
2292 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2293 const PPCSubtarget &Subtarget) const {
2294 MachineFunction &MF = DAG.getMachineFunction();
2295 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2299 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2300 // vastart just stores the address of the VarArgsFrameIndex slot into the
2301 // memory location argument.
2302 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2303 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2304 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2305 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2306 MachinePointerInfo(SV),
2310 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2311 // We suppose the given va_list is already allocated.
2314 // char gpr; /* index into the array of 8 GPRs
2315 // * stored in the register save area
2316 // * gpr=0 corresponds to r3,
2317 // * gpr=1 to r4, etc.
2319 // char fpr; /* index into the array of 8 FPRs
2320 // * stored in the register save area
2321 // * fpr=0 corresponds to f1,
2322 // * fpr=1 to f2, etc.
2324 // char *overflow_arg_area;
2325 // /* location on stack that holds
2326 // * the next overflow argument
2328 // char *reg_save_area;
2329 // /* where r3:r10 and f1:f8 (if saved)
2335 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2336 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2339 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2341 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2343 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2346 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2347 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2349 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2350 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2352 uint64_t FPROffset = 1;
2353 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2355 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2357 // Store first byte : number of int regs
2358 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2360 MachinePointerInfo(SV),
2361 MVT::i8, false, false, 0);
2362 uint64_t nextOffset = FPROffset;
2363 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2366 // Store second byte : number of float regs
2367 SDValue secondStore =
2368 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2369 MachinePointerInfo(SV, nextOffset), MVT::i8,
2371 nextOffset += StackOffset;
2372 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2374 // Store second word : arguments given on stack
2375 SDValue thirdStore =
2376 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2377 MachinePointerInfo(SV, nextOffset),
2379 nextOffset += FrameOffset;
2380 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2382 // Store third word : arguments given in registers
2383 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2384 MachinePointerInfo(SV, nextOffset),
2389 #include "PPCGenCallingConv.inc"
2391 // Function whose sole purpose is to kill compiler warnings
2392 // stemming from unused functions included from PPCGenCallingConv.inc.
2393 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2394 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2397 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2398 CCValAssign::LocInfo &LocInfo,
2399 ISD::ArgFlagsTy &ArgFlags,
2404 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2406 CCValAssign::LocInfo &LocInfo,
2407 ISD::ArgFlagsTy &ArgFlags,
2409 static const MCPhysReg ArgRegs[] = {
2410 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2411 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2413 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2415 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2417 // Skip one register if the first unallocated register has an even register
2418 // number and there are still argument registers available which have not been
2419 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2420 // need to skip a register if RegNum is odd.
2421 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2422 State.AllocateReg(ArgRegs[RegNum]);
2425 // Always return false here, as this function only makes sure that the first
2426 // unallocated register has an odd register number and does not actually
2427 // allocate a register for the current argument.
2431 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2433 CCValAssign::LocInfo &LocInfo,
2434 ISD::ArgFlagsTy &ArgFlags,
2436 static const MCPhysReg ArgRegs[] = {
2437 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2441 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2443 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2445 // If there is only one Floating-point register left we need to put both f64
2446 // values of a split ppc_fp128 value on the stack.
2447 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2448 State.AllocateReg(ArgRegs[RegNum]);
2451 // Always return false here, as this function only makes sure that the two f64
2452 // values a ppc_fp128 value is split into are both passed in registers or both
2453 // passed on the stack and does not actually allocate a register for the
2454 // current argument.
2458 /// FPR - The set of FP registers that should be allocated for arguments,
2460 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2461 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2462 PPC::F11, PPC::F12, PPC::F13};
2464 /// QFPR - The set of QPX registers that should be allocated for arguments.
2465 static const MCPhysReg QFPR[] = {
2466 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2467 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2469 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2471 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2472 unsigned PtrByteSize) {
2473 unsigned ArgSize = ArgVT.getStoreSize();
2474 if (Flags.isByVal())
2475 ArgSize = Flags.getByValSize();
2477 // Round up to multiples of the pointer size, except for array members,
2478 // which are always packed.
2479 if (!Flags.isInConsecutiveRegs())
2480 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2485 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2487 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2488 ISD::ArgFlagsTy Flags,
2489 unsigned PtrByteSize) {
2490 unsigned Align = PtrByteSize;
2492 // Altivec parameters are padded to a 16 byte boundary.
2493 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2494 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2495 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2497 // QPX vector types stored in double-precision are padded to a 32 byte
2499 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2502 // ByVal parameters are aligned as requested.
2503 if (Flags.isByVal()) {
2504 unsigned BVAlign = Flags.getByValAlign();
2505 if (BVAlign > PtrByteSize) {
2506 if (BVAlign % PtrByteSize != 0)
2508 "ByVal alignment is not a multiple of the pointer size");
2514 // Array members are always packed to their original alignment.
2515 if (Flags.isInConsecutiveRegs()) {
2516 // If the array member was split into multiple registers, the first
2517 // needs to be aligned to the size of the full type. (Except for
2518 // ppcf128, which is only aligned as its f64 components.)
2519 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2520 Align = OrigVT.getStoreSize();
2522 Align = ArgVT.getStoreSize();
2528 /// CalculateStackSlotUsed - Return whether this argument will use its
2529 /// stack slot (instead of being passed in registers). ArgOffset,
2530 /// AvailableFPRs, and AvailableVRs must hold the current argument
2531 /// position, and will be updated to account for this argument.
2532 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2533 ISD::ArgFlagsTy Flags,
2534 unsigned PtrByteSize,
2535 unsigned LinkageSize,
2536 unsigned ParamAreaSize,
2537 unsigned &ArgOffset,
2538 unsigned &AvailableFPRs,
2539 unsigned &AvailableVRs, bool HasQPX) {
2540 bool UseMemory = false;
2542 // Respect alignment of argument on the stack.
2544 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2545 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2546 // If there's no space left in the argument save area, we must
2547 // use memory (this check also catches zero-sized arguments).
2548 if (ArgOffset >= LinkageSize + ParamAreaSize)
2551 // Allocate argument on the stack.
2552 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2553 if (Flags.isInConsecutiveRegsLast())
2554 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2555 // If we overran the argument save area, we must use memory
2556 // (this check catches arguments passed partially in memory)
2557 if (ArgOffset > LinkageSize + ParamAreaSize)
2560 // However, if the argument is actually passed in an FPR or a VR,
2561 // we don't use memory after all.
2562 if (!Flags.isByVal()) {
2563 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2564 // QPX registers overlap with the scalar FP registers.
2565 (HasQPX && (ArgVT == MVT::v4f32 ||
2566 ArgVT == MVT::v4f64 ||
2567 ArgVT == MVT::v4i1)))
2568 if (AvailableFPRs > 0) {
2572 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2573 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2574 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2575 if (AvailableVRs > 0) {
2584 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2585 /// ensure minimum alignment required for target.
2586 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2587 unsigned NumBytes) {
2588 unsigned TargetAlign = Lowering->getStackAlignment();
2589 unsigned AlignMask = TargetAlign - 1;
2590 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2595 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2596 CallingConv::ID CallConv, bool isVarArg,
2597 const SmallVectorImpl<ISD::InputArg>
2599 SDLoc dl, SelectionDAG &DAG,
2600 SmallVectorImpl<SDValue> &InVals)
2602 if (Subtarget.isSVR4ABI()) {
2603 if (Subtarget.isPPC64())
2604 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2607 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2610 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2616 PPCTargetLowering::LowerFormalArguments_32SVR4(
2618 CallingConv::ID CallConv, bool isVarArg,
2619 const SmallVectorImpl<ISD::InputArg>
2621 SDLoc dl, SelectionDAG &DAG,
2622 SmallVectorImpl<SDValue> &InVals) const {
2624 // 32-bit SVR4 ABI Stack Frame Layout:
2625 // +-----------------------------------+
2626 // +--> | Back chain |
2627 // | +-----------------------------------+
2628 // | | Floating-point register save area |
2629 // | +-----------------------------------+
2630 // | | General register save area |
2631 // | +-----------------------------------+
2632 // | | CR save word |
2633 // | +-----------------------------------+
2634 // | | VRSAVE save word |
2635 // | +-----------------------------------+
2636 // | | Alignment padding |
2637 // | +-----------------------------------+
2638 // | | Vector register save area |
2639 // | +-----------------------------------+
2640 // | | Local variable space |
2641 // | +-----------------------------------+
2642 // | | Parameter list area |
2643 // | +-----------------------------------+
2644 // | | LR save word |
2645 // | +-----------------------------------+
2646 // SP--> +--- | Back chain |
2647 // +-----------------------------------+
2650 // System V Application Binary Interface PowerPC Processor Supplement
2651 // AltiVec Technology Programming Interface Manual
2653 MachineFunction &MF = DAG.getMachineFunction();
2654 MachineFrameInfo *MFI = MF.getFrameInfo();
2655 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2657 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2658 // Potential tail calls could cause overwriting of argument stack slots.
2659 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2660 (CallConv == CallingConv::Fast));
2661 unsigned PtrByteSize = 4;
2663 // Assign locations to all of the incoming arguments.
2664 SmallVector<CCValAssign, 16> ArgLocs;
2665 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2668 // Reserve space for the linkage area on the stack.
2669 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2670 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2672 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2674 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2675 CCValAssign &VA = ArgLocs[i];
2677 // Arguments stored in registers.
2678 if (VA.isRegLoc()) {
2679 const TargetRegisterClass *RC;
2680 EVT ValVT = VA.getValVT();
2682 switch (ValVT.getSimpleVT().SimpleTy) {
2684 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2687 RC = &PPC::GPRCRegClass;
2690 RC = &PPC::F4RCRegClass;
2693 if (Subtarget.hasVSX())
2694 RC = &PPC::VSFRCRegClass;
2696 RC = &PPC::F8RCRegClass;
2701 RC = &PPC::VRRCRegClass;
2704 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2708 RC = &PPC::VSHRCRegClass;
2711 RC = &PPC::QFRCRegClass;
2714 RC = &PPC::QBRCRegClass;
2718 // Transform the arguments stored in physical registers into virtual ones.
2719 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2720 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2721 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2723 if (ValVT == MVT::i1)
2724 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2726 InVals.push_back(ArgValue);
2728 // Argument stored in memory.
2729 assert(VA.isMemLoc());
2731 unsigned ArgSize = VA.getLocVT().getStoreSize();
2732 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2735 // Create load nodes to retrieve arguments from the stack.
2736 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2737 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2738 MachinePointerInfo(),
2739 false, false, false, 0));
2743 // Assign locations to all of the incoming aggregate by value arguments.
2744 // Aggregates passed by value are stored in the local variable space of the
2745 // caller's stack frame, right above the parameter list area.
2746 SmallVector<CCValAssign, 16> ByValArgLocs;
2747 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2748 ByValArgLocs, *DAG.getContext());
2750 // Reserve stack space for the allocations in CCInfo.
2751 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2753 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2755 // Area that is at least reserved in the caller of this function.
2756 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2757 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2759 // Set the size that is at least reserved in caller of this function. Tail
2760 // call optimized function's reserved stack space needs to be aligned so that
2761 // taking the difference between two stack areas will result in an aligned
2764 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2765 FuncInfo->setMinReservedArea(MinReservedArea);
2767 SmallVector<SDValue, 8> MemOps;
2769 // If the function takes variable number of arguments, make a frame index for
2770 // the start of the first vararg value... for expansion of llvm.va_start.
2772 static const MCPhysReg GPArgRegs[] = {
2773 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2774 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2776 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2778 static const MCPhysReg FPArgRegs[] = {
2779 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2782 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2783 if (DisablePPCFloatInVariadic)
2786 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2787 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2789 // Make room for NumGPArgRegs and NumFPArgRegs.
2790 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2791 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2793 FuncInfo->setVarArgsStackOffset(
2794 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2795 CCInfo.getNextStackOffset(), true));
2797 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2798 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2800 // The fixed integer arguments of a variadic function are stored to the
2801 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2802 // the result of va_next.
2803 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2804 // Get an existing live-in vreg, or add a new one.
2805 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2807 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2809 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2810 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2811 MachinePointerInfo(), false, false, 0);
2812 MemOps.push_back(Store);
2813 // Increment the address by four for the next argument to store
2814 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2815 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2818 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2820 // The double arguments are stored to the VarArgsFrameIndex
2822 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2823 // Get an existing live-in vreg, or add a new one.
2824 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2826 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2828 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2829 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2830 MachinePointerInfo(), false, false, 0);
2831 MemOps.push_back(Store);
2832 // Increment the address by eight for the next argument to store
2833 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2835 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2839 if (!MemOps.empty())
2840 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2845 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2846 // value to MVT::i64 and then truncate to the correct register size.
2848 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2849 SelectionDAG &DAG, SDValue ArgVal,
2852 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2853 DAG.getValueType(ObjectVT));
2854 else if (Flags.isZExt())
2855 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2856 DAG.getValueType(ObjectVT));
2858 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2862 PPCTargetLowering::LowerFormalArguments_64SVR4(
2864 CallingConv::ID CallConv, bool isVarArg,
2865 const SmallVectorImpl<ISD::InputArg>
2867 SDLoc dl, SelectionDAG &DAG,
2868 SmallVectorImpl<SDValue> &InVals) const {
2869 // TODO: add description of PPC stack frame format, or at least some docs.
2871 bool isELFv2ABI = Subtarget.isELFv2ABI();
2872 bool isLittleEndian = Subtarget.isLittleEndian();
2873 MachineFunction &MF = DAG.getMachineFunction();
2874 MachineFrameInfo *MFI = MF.getFrameInfo();
2875 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2877 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2878 "fastcc not supported on varargs functions");
2880 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2881 // Potential tail calls could cause overwriting of argument stack slots.
2882 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2883 (CallConv == CallingConv::Fast));
2884 unsigned PtrByteSize = 8;
2885 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2887 static const MCPhysReg GPR[] = {
2888 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2889 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2891 static const MCPhysReg VR[] = {
2892 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2893 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2895 static const MCPhysReg VSRH[] = {
2896 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2897 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2900 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2901 const unsigned Num_FPR_Regs = 13;
2902 const unsigned Num_VR_Regs = array_lengthof(VR);
2903 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2905 // Do a first pass over the arguments to determine whether the ABI
2906 // guarantees that our caller has allocated the parameter save area
2907 // on its stack frame. In the ELFv1 ABI, this is always the case;
2908 // in the ELFv2 ABI, it is true if this is a vararg function or if
2909 // any parameter is located in a stack slot.
2911 bool HasParameterArea = !isELFv2ABI || isVarArg;
2912 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2913 unsigned NumBytes = LinkageSize;
2914 unsigned AvailableFPRs = Num_FPR_Regs;
2915 unsigned AvailableVRs = Num_VR_Regs;
2916 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2917 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2918 PtrByteSize, LinkageSize, ParamAreaSize,
2919 NumBytes, AvailableFPRs, AvailableVRs,
2920 Subtarget.hasQPX()))
2921 HasParameterArea = true;
2923 // Add DAG nodes to load the arguments or copy them out of registers. On
2924 // entry to a function on PPC, the arguments start after the linkage area,
2925 // although the first ones are often in registers.
2927 unsigned ArgOffset = LinkageSize;
2928 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2929 unsigned &QFPR_idx = FPR_idx;
2930 SmallVector<SDValue, 8> MemOps;
2931 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2932 unsigned CurArgIdx = 0;
2933 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2935 bool needsLoad = false;
2936 EVT ObjectVT = Ins[ArgNo].VT;
2937 EVT OrigVT = Ins[ArgNo].ArgVT;
2938 unsigned ObjSize = ObjectVT.getStoreSize();
2939 unsigned ArgSize = ObjSize;
2940 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2941 if (Ins[ArgNo].isOrigArg()) {
2942 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2943 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2945 // We re-align the argument offset for each argument, except when using the
2946 // fast calling convention, when we need to make sure we do that only when
2947 // we'll actually use a stack slot.
2948 unsigned CurArgOffset, Align;
2949 auto ComputeArgOffset = [&]() {
2950 /* Respect alignment of argument on the stack. */
2951 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2952 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2953 CurArgOffset = ArgOffset;
2956 if (CallConv != CallingConv::Fast) {
2959 /* Compute GPR index associated with argument offset. */
2960 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2961 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2964 // FIXME the codegen can be much improved in some cases.
2965 // We do not have to keep everything in memory.
2966 if (Flags.isByVal()) {
2967 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2969 if (CallConv == CallingConv::Fast)
2972 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2973 ObjSize = Flags.getByValSize();
2974 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2975 // Empty aggregate parameters do not take up registers. Examples:
2979 // etc. However, we have to provide a place-holder in InVals, so
2980 // pretend we have an 8-byte item at the current address for that
2983 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2984 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2985 InVals.push_back(FIN);
2989 // Create a stack object covering all stack doublewords occupied
2990 // by the argument. If the argument is (fully or partially) on
2991 // the stack, or if the argument is fully in registers but the
2992 // caller has allocated the parameter save anyway, we can refer
2993 // directly to the caller's stack frame. Otherwise, create a
2994 // local copy in our own frame.
2996 if (HasParameterArea ||
2997 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2998 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3000 FI = MFI->CreateStackObject(ArgSize, Align, false);
3001 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3003 // Handle aggregates smaller than 8 bytes.
3004 if (ObjSize < PtrByteSize) {
3005 // The value of the object is its address, which differs from the
3006 // address of the enclosing doubleword on big-endian systems.
3008 if (!isLittleEndian) {
3009 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
3010 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3012 InVals.push_back(Arg);
3014 if (GPR_idx != Num_GPR_Regs) {
3015 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3016 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3019 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3020 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3021 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3022 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3023 MachinePointerInfo(FuncArg),
3024 ObjType, false, false, 0);
3026 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3027 // store the whole register as-is to the parameter save area
3029 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3030 MachinePointerInfo(FuncArg),
3034 MemOps.push_back(Store);
3036 // Whether we copied from a register or not, advance the offset
3037 // into the parameter save area by a full doubleword.
3038 ArgOffset += PtrByteSize;
3042 // The value of the object is its address, which is the address of
3043 // its first stack doubleword.
3044 InVals.push_back(FIN);
3046 // Store whatever pieces of the object are in registers to memory.
3047 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3048 if (GPR_idx == Num_GPR_Regs)
3051 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3052 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3055 SDValue Off = DAG.getConstant(j, PtrVT);
3056 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3058 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3059 MachinePointerInfo(FuncArg, j),
3061 MemOps.push_back(Store);
3064 ArgOffset += ArgSize;
3068 switch (ObjectVT.getSimpleVT().SimpleTy) {
3069 default: llvm_unreachable("Unhandled argument type!");
3073 // These can be scalar arguments or elements of an integer array type
3074 // passed directly. Clang may use those instead of "byval" aggregate
3075 // types to avoid forcing arguments to memory unnecessarily.
3076 if (GPR_idx != Num_GPR_Regs) {
3077 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3078 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3080 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3081 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3082 // value to MVT::i64 and then truncate to the correct register size.
3083 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3085 if (CallConv == CallingConv::Fast)
3089 ArgSize = PtrByteSize;
3091 if (CallConv != CallingConv::Fast || needsLoad)
3097 // These can be scalar arguments or elements of a float array type
3098 // passed directly. The latter are used to implement ELFv2 homogenous
3099 // float aggregates.
3100 if (FPR_idx != Num_FPR_Regs) {
3103 if (ObjectVT == MVT::f32)
3104 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3106 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3107 ? &PPC::VSFRCRegClass
3108 : &PPC::F8RCRegClass);
3110 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3112 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3113 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3114 // once we support fp <-> gpr moves.
3116 // This can only ever happen in the presence of f32 array types,
3117 // since otherwise we never run out of FPRs before running out
3119 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3120 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3122 if (ObjectVT == MVT::f32) {
3123 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3124 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3125 DAG.getConstant(32, MVT::i32));
3126 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3129 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3131 if (CallConv == CallingConv::Fast)
3137 // When passing an array of floats, the array occupies consecutive
3138 // space in the argument area; only round up to the next doubleword
3139 // at the end of the array. Otherwise, each float takes 8 bytes.
3140 if (CallConv != CallingConv::Fast || needsLoad) {
3141 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3142 ArgOffset += ArgSize;
3143 if (Flags.isInConsecutiveRegsLast())
3144 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3153 if (!Subtarget.hasQPX()) {
3154 // These can be scalar arguments or elements of a vector array type
3155 // passed directly. The latter are used to implement ELFv2 homogenous
3156 // vector aggregates.
3157 if (VR_idx != Num_VR_Regs) {
3158 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3159 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3160 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3161 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3164 if (CallConv == CallingConv::Fast)
3169 if (CallConv != CallingConv::Fast || needsLoad)
3174 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3175 "Invalid QPX parameter type");
3180 // QPX vectors are treated like their scalar floating-point subregisters
3181 // (except that they're larger).
3182 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3183 if (QFPR_idx != Num_QFPR_Regs) {
3184 const TargetRegisterClass *RC;
3185 switch (ObjectVT.getSimpleVT().SimpleTy) {
3186 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3187 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3188 default: RC = &PPC::QBRCRegClass; break;
3191 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3192 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3195 if (CallConv == CallingConv::Fast)
3199 if (CallConv != CallingConv::Fast || needsLoad)
3204 // We need to load the argument to a virtual register if we determined
3205 // above that we ran out of physical registers of the appropriate type.
3207 if (ObjSize < ArgSize && !isLittleEndian)
3208 CurArgOffset += ArgSize - ObjSize;
3209 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3210 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3211 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3212 false, false, false, 0);
3215 InVals.push_back(ArgVal);
3218 // Area that is at least reserved in the caller of this function.
3219 unsigned MinReservedArea;
3220 if (HasParameterArea)
3221 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3223 MinReservedArea = LinkageSize;
3225 // Set the size that is at least reserved in caller of this function. Tail
3226 // call optimized functions' reserved stack space needs to be aligned so that
3227 // taking the difference between two stack areas will result in an aligned
3230 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3231 FuncInfo->setMinReservedArea(MinReservedArea);
3233 // If the function takes variable number of arguments, make a frame index for
3234 // the start of the first vararg value... for expansion of llvm.va_start.
3236 int Depth = ArgOffset;
3238 FuncInfo->setVarArgsFrameIndex(
3239 MFI->CreateFixedObject(PtrByteSize, Depth, true));
3240 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3242 // If this function is vararg, store any remaining integer argument regs
3243 // to their spots on the stack so that they may be loaded by deferencing the
3244 // result of va_next.
3245 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3246 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3247 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3248 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3249 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3250 MachinePointerInfo(), false, false, 0);
3251 MemOps.push_back(Store);
3252 // Increment the address by four for the next argument to store
3253 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3254 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3258 if (!MemOps.empty())
3259 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3265 PPCTargetLowering::LowerFormalArguments_Darwin(
3267 CallingConv::ID CallConv, bool isVarArg,
3268 const SmallVectorImpl<ISD::InputArg>
3270 SDLoc dl, SelectionDAG &DAG,
3271 SmallVectorImpl<SDValue> &InVals) const {
3272 // TODO: add description of PPC stack frame format, or at least some docs.
3274 MachineFunction &MF = DAG.getMachineFunction();
3275 MachineFrameInfo *MFI = MF.getFrameInfo();
3276 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3278 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3279 bool isPPC64 = PtrVT == MVT::i64;
3280 // Potential tail calls could cause overwriting of argument stack slots.
3281 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3282 (CallConv == CallingConv::Fast));
3283 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3284 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3285 unsigned ArgOffset = LinkageSize;
3286 // Area that is at least reserved in caller of this function.
3287 unsigned MinReservedArea = ArgOffset;
3289 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3290 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3291 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3293 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3294 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3295 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3297 static const MCPhysReg VR[] = {
3298 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3299 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3302 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3303 const unsigned Num_FPR_Regs = 13;
3304 const unsigned Num_VR_Regs = array_lengthof( VR);
3306 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3308 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3310 // In 32-bit non-varargs functions, the stack space for vectors is after the
3311 // stack space for non-vectors. We do not use this space unless we have
3312 // too many vectors to fit in registers, something that only occurs in
3313 // constructed examples:), but we have to walk the arglist to figure
3314 // that out...for the pathological case, compute VecArgOffset as the
3315 // start of the vector parameter area. Computing VecArgOffset is the
3316 // entire point of the following loop.
3317 unsigned VecArgOffset = ArgOffset;
3318 if (!isVarArg && !isPPC64) {
3319 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3321 EVT ObjectVT = Ins[ArgNo].VT;
3322 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3324 if (Flags.isByVal()) {
3325 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3326 unsigned ObjSize = Flags.getByValSize();
3328 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3329 VecArgOffset += ArgSize;
3333 switch(ObjectVT.getSimpleVT().SimpleTy) {
3334 default: llvm_unreachable("Unhandled argument type!");
3340 case MVT::i64: // PPC64
3342 // FIXME: We are guaranteed to be !isPPC64 at this point.
3343 // Does MVT::i64 apply?
3350 // Nothing to do, we're only looking at Nonvector args here.
3355 // We've found where the vector parameter area in memory is. Skip the
3356 // first 12 parameters; these don't use that memory.
3357 VecArgOffset = ((VecArgOffset+15)/16)*16;
3358 VecArgOffset += 12*16;
3360 // Add DAG nodes to load the arguments or copy them out of registers. On
3361 // entry to a function on PPC, the arguments start after the linkage area,
3362 // although the first ones are often in registers.
3364 SmallVector<SDValue, 8> MemOps;
3365 unsigned nAltivecParamsAtEnd = 0;
3366 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3367 unsigned CurArgIdx = 0;
3368 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3370 bool needsLoad = false;
3371 EVT ObjectVT = Ins[ArgNo].VT;
3372 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3373 unsigned ArgSize = ObjSize;
3374 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3375 if (Ins[ArgNo].isOrigArg()) {
3376 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3377 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3379 unsigned CurArgOffset = ArgOffset;
3381 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3382 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3383 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3384 if (isVarArg || isPPC64) {
3385 MinReservedArea = ((MinReservedArea+15)/16)*16;
3386 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3389 } else nAltivecParamsAtEnd++;
3391 // Calculate min reserved area.
3392 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3396 // FIXME the codegen can be much improved in some cases.
3397 // We do not have to keep everything in memory.
3398 if (Flags.isByVal()) {
3399 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3401 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3402 ObjSize = Flags.getByValSize();
3403 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3404 // Objects of size 1 and 2 are right justified, everything else is
3405 // left justified. This means the memory address is adjusted forwards.
3406 if (ObjSize==1 || ObjSize==2) {
3407 CurArgOffset = CurArgOffset + (4 - ObjSize);
3409 // The value of the object is its address.
3410 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3411 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3412 InVals.push_back(FIN);
3413 if (ObjSize==1 || ObjSize==2) {
3414 if (GPR_idx != Num_GPR_Regs) {
3417 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3419 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3420 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3421 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3422 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3423 MachinePointerInfo(FuncArg),
3424 ObjType, false, false, 0);
3425 MemOps.push_back(Store);
3429 ArgOffset += PtrByteSize;
3433 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3434 // Store whatever pieces of the object are in registers
3435 // to memory. ArgOffset will be the address of the beginning
3437 if (GPR_idx != Num_GPR_Regs) {
3440 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3442 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3443 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3444 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3445 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3446 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3447 MachinePointerInfo(FuncArg, j),
3449 MemOps.push_back(Store);
3451 ArgOffset += PtrByteSize;
3453 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3460 switch (ObjectVT.getSimpleVT().SimpleTy) {
3461 default: llvm_unreachable("Unhandled argument type!");
3465 if (GPR_idx != Num_GPR_Regs) {
3466 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3467 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3469 if (ObjectVT == MVT::i1)
3470 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3475 ArgSize = PtrByteSize;
3477 // All int arguments reserve stack space in the Darwin ABI.
3478 ArgOffset += PtrByteSize;
3482 case MVT::i64: // PPC64
3483 if (GPR_idx != Num_GPR_Regs) {
3484 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3485 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3487 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3488 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3489 // value to MVT::i64 and then truncate to the correct register size.
3490 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3495 ArgSize = PtrByteSize;
3497 // All int arguments reserve stack space in the Darwin ABI.
3503 // Every 4 bytes of argument space consumes one of the GPRs available for
3504 // argument passing.
3505 if (GPR_idx != Num_GPR_Regs) {
3507 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3510 if (FPR_idx != Num_FPR_Regs) {
3513 if (ObjectVT == MVT::f32)
3514 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3516 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3518 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3524 // All FP arguments reserve stack space in the Darwin ABI.
3525 ArgOffset += isPPC64 ? 8 : ObjSize;
3531 // Note that vector arguments in registers don't reserve stack space,
3532 // except in varargs functions.
3533 if (VR_idx != Num_VR_Regs) {
3534 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3535 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3537 while ((ArgOffset % 16) != 0) {
3538 ArgOffset += PtrByteSize;
3539 if (GPR_idx != Num_GPR_Regs)
3543 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3547 if (!isVarArg && !isPPC64) {
3548 // Vectors go after all the nonvectors.
3549 CurArgOffset = VecArgOffset;
3552 // Vectors are aligned.
3553 ArgOffset = ((ArgOffset+15)/16)*16;
3554 CurArgOffset = ArgOffset;
3562 // We need to load the argument to a virtual register if we determined above
3563 // that we ran out of physical registers of the appropriate type.
3565 int FI = MFI->CreateFixedObject(ObjSize,
3566 CurArgOffset + (ArgSize - ObjSize),
3568 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3569 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3570 false, false, false, 0);
3573 InVals.push_back(ArgVal);
3576 // Allow for Altivec parameters at the end, if needed.
3577 if (nAltivecParamsAtEnd) {
3578 MinReservedArea = ((MinReservedArea+15)/16)*16;
3579 MinReservedArea += 16*nAltivecParamsAtEnd;
3582 // Area that is at least reserved in the caller of this function.
3583 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3585 // Set the size that is at least reserved in caller of this function. Tail
3586 // call optimized functions' reserved stack space needs to be aligned so that
3587 // taking the difference between two stack areas will result in an aligned
3590 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3591 FuncInfo->setMinReservedArea(MinReservedArea);
3593 // If the function takes variable number of arguments, make a frame index for
3594 // the start of the first vararg value... for expansion of llvm.va_start.
3596 int Depth = ArgOffset;
3598 FuncInfo->setVarArgsFrameIndex(
3599 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3601 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3603 // If this function is vararg, store any remaining integer argument regs
3604 // to their spots on the stack so that they may be loaded by deferencing the
3605 // result of va_next.
3606 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3610 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3612 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3614 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3615 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3616 MachinePointerInfo(), false, false, 0);
3617 MemOps.push_back(Store);
3618 // Increment the address by four for the next argument to store
3619 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3620 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3624 if (!MemOps.empty())
3625 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3630 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3631 /// adjusted to accommodate the arguments for the tailcall.
3632 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3633 unsigned ParamSize) {
3635 if (!isTailCall) return 0;
3637 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3638 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3639 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3640 // Remember only if the new adjustement is bigger.
3641 if (SPDiff < FI->getTailCallSPDelta())
3642 FI->setTailCallSPDelta(SPDiff);
3647 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3648 /// for tail call optimization. Targets which want to do tail call
3649 /// optimization should implement this function.
3651 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3652 CallingConv::ID CalleeCC,
3654 const SmallVectorImpl<ISD::InputArg> &Ins,
3655 SelectionDAG& DAG) const {
3656 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3659 // Variable argument functions are not supported.
3663 MachineFunction &MF = DAG.getMachineFunction();
3664 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3665 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3666 // Functions containing by val parameters are not supported.
3667 for (unsigned i = 0; i != Ins.size(); i++) {
3668 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3669 if (Flags.isByVal()) return false;
3672 // Non-PIC/GOT tail calls are supported.
3673 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3676 // At the moment we can only do local tail calls (in same module, hidden
3677 // or protected) if we are generating PIC.
3678 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3679 return G->getGlobal()->hasHiddenVisibility()
3680 || G->getGlobal()->hasProtectedVisibility();
3686 /// isCallCompatibleAddress - Return the immediate to use if the specified
3687 /// 32-bit value is representable in the immediate field of a BxA instruction.
3688 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3689 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3690 if (!C) return nullptr;
3692 int Addr = C->getZExtValue();
3693 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3694 SignExtend32<26>(Addr) != Addr)
3695 return nullptr; // Top 6 bits have to be sext of immediate.
3697 return DAG.getConstant((int)C->getZExtValue() >> 2,
3698 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3703 struct TailCallArgumentInfo {
3708 TailCallArgumentInfo() : FrameIdx(0) {}
3713 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3715 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3717 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3718 SmallVectorImpl<SDValue> &MemOpChains,
3720 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3721 SDValue Arg = TailCallArgs[i].Arg;
3722 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3723 int FI = TailCallArgs[i].FrameIdx;
3724 // Store relative to framepointer.
3725 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3726 MachinePointerInfo::getFixedStack(FI),
3731 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3732 /// the appropriate stack slot for the tail call optimized function call.
3733 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3734 MachineFunction &MF,
3743 // Calculate the new stack slot for the return address.
3744 int SlotSize = isPPC64 ? 8 : 4;
3745 const PPCFrameLowering *FL =
3746 MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3747 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3748 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3749 NewRetAddrLoc, true);
3750 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3751 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3752 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3753 MachinePointerInfo::getFixedStack(NewRetAddr),
3756 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3757 // slot as the FP is never overwritten.
3759 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3760 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3762 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3763 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3764 MachinePointerInfo::getFixedStack(NewFPIdx),
3771 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3772 /// the position of the argument.
3774 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3775 SDValue Arg, int SPDiff, unsigned ArgOffset,
3776 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3777 int Offset = ArgOffset + SPDiff;
3778 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3779 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3780 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3781 SDValue FIN = DAG.getFrameIndex(FI, VT);
3782 TailCallArgumentInfo Info;
3784 Info.FrameIdxOp = FIN;
3786 TailCallArguments.push_back(Info);
3789 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3790 /// stack slot. Returns the chain as result and the loaded frame pointers in
3791 /// LROpOut/FPOpout. Used when tail calling.
3792 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3800 // Load the LR and FP stack slot for later adjusting.
3801 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3802 LROpOut = getReturnAddrFrameIndex(DAG);
3803 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3804 false, false, false, 0);
3805 Chain = SDValue(LROpOut.getNode(), 1);
3807 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3808 // slot as the FP is never overwritten.
3810 FPOpOut = getFramePointerFrameIndex(DAG);
3811 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3812 false, false, false, 0);
3813 Chain = SDValue(FPOpOut.getNode(), 1);
3819 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3820 /// by "Src" to address "Dst" of size "Size". Alignment information is
3821 /// specified by the specific parameter attribute. The copy will be passed as
3822 /// a byval function parameter.
3823 /// Sometimes what we are copying is the end of a larger object, the part that
3824 /// does not fit in registers.
3826 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3827 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3829 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3830 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3831 false, false, MachinePointerInfo(),
3832 MachinePointerInfo());
3835 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3838 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3839 SDValue Arg, SDValue PtrOff, int SPDiff,
3840 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3841 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3842 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3844 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3849 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3851 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3852 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3853 DAG.getConstant(ArgOffset, PtrVT));
3855 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3856 MachinePointerInfo(), false, false, 0));
3857 // Calculate and remember argument location.
3858 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3863 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3864 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3865 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3866 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3867 MachineFunction &MF = DAG.getMachineFunction();
3869 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3870 // might overwrite each other in case of tail call optimization.
3871 SmallVector<SDValue, 8> MemOpChains2;
3872 // Do not flag preceding copytoreg stuff together with the following stuff.
3874 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3876 if (!MemOpChains2.empty())
3877 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3879 // Store the return address to the appropriate stack slot.
3880 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3881 isPPC64, isDarwinABI, dl);
3883 // Emit callseq_end just before tailcall node.
3884 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3885 DAG.getIntPtrConstant(0, true), InFlag, dl);
3886 InFlag = Chain.getValue(1);
3889 // Is this global address that of a function that can be called by name? (as
3890 // opposed to something that must hold a descriptor for an indirect call).
3891 static bool isFunctionGlobalAddress(SDValue Callee) {
3892 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3893 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3894 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3897 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3904 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3905 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3906 bool isTailCall, bool IsPatchPoint,
3907 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3908 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3909 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3911 bool isPPC64 = Subtarget.isPPC64();
3912 bool isSVR4ABI = Subtarget.isSVR4ABI();
3913 bool isELFv2ABI = Subtarget.isELFv2ABI();
3915 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3916 NodeTys.push_back(MVT::Other); // Returns a chain
3917 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3919 unsigned CallOpc = PPCISD::CALL;
3921 bool needIndirectCall = true;
3922 if (!isSVR4ABI || !isPPC64)
3923 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3924 // If this is an absolute destination address, use the munged value.
3925 Callee = SDValue(Dest, 0);
3926 needIndirectCall = false;
3929 if (isFunctionGlobalAddress(Callee)) {
3930 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3931 // A call to a TLS address is actually an indirect call to a
3932 // thread-specific pointer.
3933 unsigned OpFlags = 0;
3934 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3935 (Subtarget.getTargetTriple().isMacOSX() &&
3936 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3937 (G->getGlobal()->isDeclaration() ||
3938 G->getGlobal()->isWeakForLinker())) ||
3939 (Subtarget.isTargetELF() && !isPPC64 &&
3940 !G->getGlobal()->hasLocalLinkage() &&
3941 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3942 // PC-relative references to external symbols should go through $stub,
3943 // unless we're building with the leopard linker or later, which
3944 // automatically synthesizes these stubs.
3945 OpFlags = PPCII::MO_PLT_OR_STUB;
3948 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3949 // every direct call is) turn it into a TargetGlobalAddress /
3950 // TargetExternalSymbol node so that legalize doesn't hack it.
3951 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3952 Callee.getValueType(), 0, OpFlags);
3953 needIndirectCall = false;
3956 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3957 unsigned char OpFlags = 0;
3959 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3960 (Subtarget.getTargetTriple().isMacOSX() &&
3961 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3962 (Subtarget.isTargetELF() && !isPPC64 &&
3963 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3964 // PC-relative references to external symbols should go through $stub,
3965 // unless we're building with the leopard linker or later, which
3966 // automatically synthesizes these stubs.
3967 OpFlags = PPCII::MO_PLT_OR_STUB;
3970 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3972 needIndirectCall = false;
3976 // We'll form an invalid direct call when lowering a patchpoint; the full
3977 // sequence for an indirect call is complicated, and many of the
3978 // instructions introduced might have side effects (and, thus, can't be
3979 // removed later). The call itself will be removed as soon as the
3980 // argument/return lowering is complete, so the fact that it has the wrong
3981 // kind of operands should not really matter.
3982 needIndirectCall = false;
3985 if (needIndirectCall) {
3986 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3987 // to do the call, we can't use PPCISD::CALL.
3988 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3990 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3991 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3992 // entry point, but to the function descriptor (the function entry point
3993 // address is part of the function descriptor though).
3994 // The function descriptor is a three doubleword structure with the
3995 // following fields: function entry point, TOC base address and
3996 // environment pointer.
3997 // Thus for a call through a function pointer, the following actions need
3999 // 1. Save the TOC of the caller in the TOC save area of its stack
4000 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4001 // 2. Load the address of the function entry point from the function
4003 // 3. Load the TOC of the callee from the function descriptor into r2.
4004 // 4. Load the environment pointer from the function descriptor into
4006 // 5. Branch to the function entry point address.
4007 // 6. On return of the callee, the TOC of the caller needs to be
4008 // restored (this is done in FinishCall()).
4010 // The loads are scheduled at the beginning of the call sequence, and the
4011 // register copies are flagged together to ensure that no other
4012 // operations can be scheduled in between. E.g. without flagging the
4013 // copies together, a TOC access in the caller could be scheduled between
4014 // the assignment of the callee TOC and the branch to the callee, which
4015 // results in the TOC access going through the TOC of the callee instead
4016 // of going through the TOC of the caller, which leads to incorrect code.
4018 // Load the address of the function entry point from the function
4020 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4021 if (LDChain.getValueType() == MVT::Glue)
4022 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4024 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4026 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4027 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4028 false, false, LoadsInv, 8);
4030 // Load environment pointer into r11.
4031 SDValue PtrOff = DAG.getIntPtrConstant(16);
4032 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4033 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4034 MPI.getWithOffset(16), false, false,
4037 SDValue TOCOff = DAG.getIntPtrConstant(8);
4038 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4039 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4040 MPI.getWithOffset(8), false, false,
4043 setUsesTOCBasePtr(DAG);
4044 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4046 Chain = TOCVal.getValue(0);
4047 InFlag = TOCVal.getValue(1);
4049 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4052 Chain = EnvVal.getValue(0);
4053 InFlag = EnvVal.getValue(1);
4055 MTCTROps[0] = Chain;
4056 MTCTROps[1] = LoadFuncPtr;
4057 MTCTROps[2] = InFlag;
4060 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4061 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4062 InFlag = Chain.getValue(1);
4065 NodeTys.push_back(MVT::Other);
4066 NodeTys.push_back(MVT::Glue);
4067 Ops.push_back(Chain);
4068 CallOpc = PPCISD::BCTRL;
4069 Callee.setNode(nullptr);
4070 // Add use of X11 (holding environment pointer)
4071 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4072 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4073 // Add CTR register as callee so a bctr can be emitted later.
4075 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4078 // If this is a direct call, pass the chain and the callee.
4079 if (Callee.getNode()) {
4080 Ops.push_back(Chain);
4081 Ops.push_back(Callee);
4083 // If this is a tail call add stack pointer delta.
4085 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4087 // Add argument registers to the end of the list so that they are known live
4089 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4090 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4091 RegsToPass[i].second.getValueType()));
4093 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4095 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4096 setUsesTOCBasePtr(DAG);
4097 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4104 bool isLocalCall(const SDValue &Callee)
4106 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4107 return !G->getGlobal()->isDeclaration() &&
4108 !G->getGlobal()->isWeakForLinker();
4113 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4114 CallingConv::ID CallConv, bool isVarArg,
4115 const SmallVectorImpl<ISD::InputArg> &Ins,
4116 SDLoc dl, SelectionDAG &DAG,
4117 SmallVectorImpl<SDValue> &InVals) const {
4119 SmallVector<CCValAssign, 16> RVLocs;
4120 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4122 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4124 // Copy all of the result registers out of their specified physreg.
4125 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4126 CCValAssign &VA = RVLocs[i];
4127 assert(VA.isRegLoc() && "Can only return in registers!");
4129 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4130 VA.getLocReg(), VA.getLocVT(), InFlag);
4131 Chain = Val.getValue(1);
4132 InFlag = Val.getValue(2);
4134 switch (VA.getLocInfo()) {
4135 default: llvm_unreachable("Unknown loc info!");
4136 case CCValAssign::Full: break;
4137 case CCValAssign::AExt:
4138 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4140 case CCValAssign::ZExt:
4141 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4142 DAG.getValueType(VA.getValVT()));
4143 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4145 case CCValAssign::SExt:
4146 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4147 DAG.getValueType(VA.getValVT()));
4148 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4152 InVals.push_back(Val);
4159 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4160 bool isTailCall, bool isVarArg, bool IsPatchPoint,
4162 SmallVector<std::pair<unsigned, SDValue>, 8>
4164 SDValue InFlag, SDValue Chain,
4165 SDValue CallSeqStart, SDValue &Callee,
4166 int SPDiff, unsigned NumBytes,
4167 const SmallVectorImpl<ISD::InputArg> &Ins,
4168 SmallVectorImpl<SDValue> &InVals,
4169 ImmutableCallSite *CS) const {
4171 std::vector<EVT> NodeTys;
4172 SmallVector<SDValue, 8> Ops;
4173 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4174 SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4175 Ops, NodeTys, CS, Subtarget);
4177 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4178 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4179 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4181 // When performing tail call optimization the callee pops its arguments off
4182 // the stack. Account for this here so these bytes can be pushed back on in
4183 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4184 int BytesCalleePops =
4185 (CallConv == CallingConv::Fast &&
4186 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4188 // Add a register mask operand representing the call-preserved registers.
4189 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4190 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
4191 assert(Mask && "Missing call preserved mask for calling convention");
4192 Ops.push_back(DAG.getRegisterMask(Mask));
4194 if (InFlag.getNode())
4195 Ops.push_back(InFlag);
4199 assert(((Callee.getOpcode() == ISD::Register &&
4200 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4201 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4202 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4203 isa<ConstantSDNode>(Callee)) &&
4204 "Expecting an global address, external symbol, absolute value or register");
4206 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4209 // Add a NOP immediately after the branch instruction when using the 64-bit
4210 // SVR4 ABI. At link time, if caller and callee are in a different module and
4211 // thus have a different TOC, the call will be replaced with a call to a stub
4212 // function which saves the current TOC, loads the TOC of the callee and
4213 // branches to the callee. The NOP will be replaced with a load instruction
4214 // which restores the TOC of the caller from the TOC save slot of the current
4215 // stack frame. If caller and callee belong to the same module (and have the
4216 // same TOC), the NOP will remain unchanged.
4218 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4220 if (CallOpc == PPCISD::BCTRL) {
4221 // This is a call through a function pointer.
4222 // Restore the caller TOC from the save area into R2.
4223 // See PrepareCall() for more information about calls through function
4224 // pointers in the 64-bit SVR4 ABI.
4225 // We are using a target-specific load with r2 hard coded, because the
4226 // result of a target-independent load would never go directly into r2,
4227 // since r2 is a reserved register (which prevents the register allocator
4228 // from allocating it), resulting in an additional register being
4229 // allocated and an unnecessary move instruction being generated.
4230 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4232 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4233 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4234 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4235 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4236 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4238 // The address needs to go after the chain input but before the flag (or
4239 // any other variadic arguments).
4240 Ops.insert(std::next(Ops.begin()), AddTOC);
4241 } else if ((CallOpc == PPCISD::CALL) &&
4242 (!isLocalCall(Callee) ||
4243 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4244 // Otherwise insert NOP for non-local calls.
4245 CallOpc = PPCISD::CALL_NOP;
4248 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4249 InFlag = Chain.getValue(1);
4251 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4252 DAG.getIntPtrConstant(BytesCalleePops, true),
4255 InFlag = Chain.getValue(1);
4257 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4258 Ins, dl, DAG, InVals);
4262 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4263 SmallVectorImpl<SDValue> &InVals) const {
4264 SelectionDAG &DAG = CLI.DAG;
4266 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4267 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4268 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4269 SDValue Chain = CLI.Chain;
4270 SDValue Callee = CLI.Callee;
4271 bool &isTailCall = CLI.IsTailCall;
4272 CallingConv::ID CallConv = CLI.CallConv;
4273 bool isVarArg = CLI.IsVarArg;
4274 bool IsPatchPoint = CLI.IsPatchPoint;
4275 ImmutableCallSite *CS = CLI.CS;
4278 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4281 if (!isTailCall && CS && CS->isMustTailCall())
4282 report_fatal_error("failed to perform tail call elimination on a call "
4283 "site marked musttail");
4285 if (Subtarget.isSVR4ABI()) {
4286 if (Subtarget.isPPC64())
4287 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4288 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4289 dl, DAG, InVals, CS);
4291 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4292 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4293 dl, DAG, InVals, CS);
4296 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4297 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4298 dl, DAG, InVals, CS);
4302 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4303 CallingConv::ID CallConv, bool isVarArg,
4304 bool isTailCall, bool IsPatchPoint,
4305 const SmallVectorImpl<ISD::OutputArg> &Outs,
4306 const SmallVectorImpl<SDValue> &OutVals,
4307 const SmallVectorImpl<ISD::InputArg> &Ins,
4308 SDLoc dl, SelectionDAG &DAG,
4309 SmallVectorImpl<SDValue> &InVals,
4310 ImmutableCallSite *CS) const {
4311 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4312 // of the 32-bit SVR4 ABI stack frame layout.
4314 assert((CallConv == CallingConv::C ||
4315 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4317 unsigned PtrByteSize = 4;
4319 MachineFunction &MF = DAG.getMachineFunction();
4321 // Mark this function as potentially containing a function that contains a
4322 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4323 // and restoring the callers stack pointer in this functions epilog. This is
4324 // done because by tail calling the called function might overwrite the value
4325 // in this function's (MF) stack pointer stack slot 0(SP).
4326 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4327 CallConv == CallingConv::Fast)
4328 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4330 // Count how many bytes are to be pushed on the stack, including the linkage
4331 // area, parameter list area and the part of the local variable space which
4332 // contains copies of aggregates which are passed by value.
4334 // Assign locations to all of the outgoing arguments.
4335 SmallVector<CCValAssign, 16> ArgLocs;
4336 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4339 // Reserve space for the linkage area on the stack.
4340 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4344 // Handle fixed and variable vector arguments differently.
4345 // Fixed vector arguments go into registers as long as registers are
4346 // available. Variable vector arguments always go into memory.
4347 unsigned NumArgs = Outs.size();
4349 for (unsigned i = 0; i != NumArgs; ++i) {
4350 MVT ArgVT = Outs[i].VT;
4351 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4354 if (Outs[i].IsFixed) {
4355 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4358 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4364 errs() << "Call operand #" << i << " has unhandled type "
4365 << EVT(ArgVT).getEVTString() << "\n";
4367 llvm_unreachable(nullptr);
4371 // All arguments are treated the same.
4372 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4375 // Assign locations to all of the outgoing aggregate by value arguments.
4376 SmallVector<CCValAssign, 16> ByValArgLocs;
4377 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4378 ByValArgLocs, *DAG.getContext());
4380 // Reserve stack space for the allocations in CCInfo.
4381 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4383 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4385 // Size of the linkage area, parameter list area and the part of the local
4386 // space variable where copies of aggregates which are passed by value are
4388 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4390 // Calculate by how many bytes the stack has to be adjusted in case of tail
4391 // call optimization.
4392 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4394 // Adjust the stack pointer for the new arguments...
4395 // These operations are automatically eliminated by the prolog/epilog pass
4396 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4398 SDValue CallSeqStart = Chain;
4400 // Load the return address and frame pointer so it can be moved somewhere else
4403 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4406 // Set up a copy of the stack pointer for use loading and storing any
4407 // arguments that may not fit in the registers available for argument
4409 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4411 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4412 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4413 SmallVector<SDValue, 8> MemOpChains;
4415 bool seenFloatArg = false;
4416 // Walk the register/memloc assignments, inserting copies/loads.
4417 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4420 CCValAssign &VA = ArgLocs[i];
4421 SDValue Arg = OutVals[i];
4422 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4424 if (Flags.isByVal()) {
4425 // Argument is an aggregate which is passed by value, thus we need to
4426 // create a copy of it in the local variable space of the current stack
4427 // frame (which is the stack frame of the caller) and pass the address of
4428 // this copy to the callee.
4429 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4430 CCValAssign &ByValVA = ByValArgLocs[j++];
4431 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4433 // Memory reserved in the local variable space of the callers stack frame.
4434 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4436 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4437 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4439 // Create a copy of the argument in the local area of the current
4441 SDValue MemcpyCall =
4442 CreateCopyOfByValArgument(Arg, PtrOff,
4443 CallSeqStart.getNode()->getOperand(0),
4446 // This must go outside the CALLSEQ_START..END.
4447 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4448 CallSeqStart.getNode()->getOperand(1),
4450 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4451 NewCallSeqStart.getNode());
4452 Chain = CallSeqStart = NewCallSeqStart;
4454 // Pass the address of the aggregate copy on the stack either in a
4455 // physical register or in the parameter list area of the current stack
4456 // frame to the callee.
4460 if (VA.isRegLoc()) {
4461 if (Arg.getValueType() == MVT::i1)
4462 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4464 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4465 // Put argument in a physical register.
4466 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4468 // Put argument in the parameter list area of the current stack frame.
4469 assert(VA.isMemLoc());
4470 unsigned LocMemOffset = VA.getLocMemOffset();
4473 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4474 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4476 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4477 MachinePointerInfo(),
4480 // Calculate and remember argument location.
4481 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4487 if (!MemOpChains.empty())
4488 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4490 // Build a sequence of copy-to-reg nodes chained together with token chain
4491 // and flag operands which copy the outgoing args into the appropriate regs.
4493 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4494 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4495 RegsToPass[i].second, InFlag);
4496 InFlag = Chain.getValue(1);
4499 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4502 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4503 SDValue Ops[] = { Chain, InFlag };
4505 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4506 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4508 InFlag = Chain.getValue(1);
4512 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4513 false, TailCallArguments);
4515 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4516 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4517 NumBytes, Ins, InVals, CS);
4520 // Copy an argument into memory, being careful to do this outside the
4521 // call sequence for the call to which the argument belongs.
4523 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4524 SDValue CallSeqStart,
4525 ISD::ArgFlagsTy Flags,
4528 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4529 CallSeqStart.getNode()->getOperand(0),
4531 // The MEMCPY must go outside the CALLSEQ_START..END.
4532 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4533 CallSeqStart.getNode()->getOperand(1),
4535 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4536 NewCallSeqStart.getNode());
4537 return NewCallSeqStart;
4541 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4542 CallingConv::ID CallConv, bool isVarArg,
4543 bool isTailCall, bool IsPatchPoint,
4544 const SmallVectorImpl<ISD::OutputArg> &Outs,
4545 const SmallVectorImpl<SDValue> &OutVals,
4546 const SmallVectorImpl<ISD::InputArg> &Ins,
4547 SDLoc dl, SelectionDAG &DAG,
4548 SmallVectorImpl<SDValue> &InVals,
4549 ImmutableCallSite *CS) const {
4551 bool isELFv2ABI = Subtarget.isELFv2ABI();
4552 bool isLittleEndian = Subtarget.isLittleEndian();
4553 unsigned NumOps = Outs.size();
4555 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4556 unsigned PtrByteSize = 8;
4558 MachineFunction &MF = DAG.getMachineFunction();
4560 // Mark this function as potentially containing a function that contains a
4561 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4562 // and restoring the callers stack pointer in this functions epilog. This is
4563 // done because by tail calling the called function might overwrite the value
4564 // in this function's (MF) stack pointer stack slot 0(SP).
4565 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4566 CallConv == CallingConv::Fast)
4567 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4569 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4570 "fastcc not supported on varargs functions");
4572 // Count how many bytes are to be pushed on the stack, including the linkage
4573 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4574 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4575 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4576 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4577 unsigned NumBytes = LinkageSize;
4578 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4579 unsigned &QFPR_idx = FPR_idx;
4581 static const MCPhysReg GPR[] = {
4582 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4583 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4585 static const MCPhysReg VR[] = {
4586 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4587 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4589 static const MCPhysReg VSRH[] = {
4590 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4591 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4594 const unsigned NumGPRs = array_lengthof(GPR);
4595 const unsigned NumFPRs = 13;
4596 const unsigned NumVRs = array_lengthof(VR);
4597 const unsigned NumQFPRs = NumFPRs;
4599 // When using the fast calling convention, we don't provide backing for
4600 // arguments that will be in registers.
4601 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4603 // Add up all the space actually used.
4604 for (unsigned i = 0; i != NumOps; ++i) {
4605 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4606 EVT ArgVT = Outs[i].VT;
4607 EVT OrigVT = Outs[i].ArgVT;
4609 if (CallConv == CallingConv::Fast) {
4610 if (Flags.isByVal())
4611 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4613 switch (ArgVT.getSimpleVT().SimpleTy) {
4614 default: llvm_unreachable("Unexpected ValueType for argument!");
4618 if (++NumGPRsUsed <= NumGPRs)
4626 if (++NumVRsUsed <= NumVRs)
4630 // When using QPX, this is handled like a FP register, otherwise, it
4631 // is an Altivec register.
4632 if (Subtarget.hasQPX()) {
4633 if (++NumFPRsUsed <= NumFPRs)
4636 if (++NumVRsUsed <= NumVRs)
4642 case MVT::v4f64: // QPX
4643 case MVT::v4i1: // QPX
4644 if (++NumFPRsUsed <= NumFPRs)
4650 /* Respect alignment of argument on the stack. */
4652 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4653 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4655 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4656 if (Flags.isInConsecutiveRegsLast())
4657 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4660 unsigned NumBytesActuallyUsed = NumBytes;
4662 // The prolog code of the callee may store up to 8 GPR argument registers to
4663 // the stack, allowing va_start to index over them in memory if its varargs.
4664 // Because we cannot tell if this is needed on the caller side, we have to
4665 // conservatively assume that it is needed. As such, make sure we have at
4666 // least enough stack space for the caller to store the 8 GPRs.
4667 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4668 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4670 // Tail call needs the stack to be aligned.
4671 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4672 CallConv == CallingConv::Fast)
4673 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4675 // Calculate by how many bytes the stack has to be adjusted in case of tail
4676 // call optimization.
4677 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4679 // To protect arguments on the stack from being clobbered in a tail call,
4680 // force all the loads to happen before doing any other lowering.
4682 Chain = DAG.getStackArgumentTokenFactor(Chain);
4684 // Adjust the stack pointer for the new arguments...
4685 // These operations are automatically eliminated by the prolog/epilog pass
4686 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4688 SDValue CallSeqStart = Chain;
4690 // Load the return address and frame pointer so it can be move somewhere else
4693 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4696 // Set up a copy of the stack pointer for use loading and storing any
4697 // arguments that may not fit in the registers available for argument
4699 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4701 // Figure out which arguments are going to go in registers, and which in
4702 // memory. Also, if this is a vararg function, floating point operations
4703 // must be stored to our stack, and loaded into integer regs as well, if
4704 // any integer regs are available for argument passing.
4705 unsigned ArgOffset = LinkageSize;
4707 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4708 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4710 SmallVector<SDValue, 8> MemOpChains;
4711 for (unsigned i = 0; i != NumOps; ++i) {
4712 SDValue Arg = OutVals[i];
4713 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4714 EVT ArgVT = Outs[i].VT;
4715 EVT OrigVT = Outs[i].ArgVT;
4717 // PtrOff will be used to store the current argument to the stack if a
4718 // register cannot be found for it.
4721 // We re-align the argument offset for each argument, except when using the
4722 // fast calling convention, when we need to make sure we do that only when
4723 // we'll actually use a stack slot.
4724 auto ComputePtrOff = [&]() {
4725 /* Respect alignment of argument on the stack. */
4727 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4728 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4730 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4732 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4735 if (CallConv != CallingConv::Fast) {
4738 /* Compute GPR index associated with argument offset. */
4739 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4740 GPR_idx = std::min(GPR_idx, NumGPRs);
4743 // Promote integers to 64-bit values.
4744 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4745 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4746 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4747 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4750 // FIXME memcpy is used way more than necessary. Correctness first.
4751 // Note: "by value" is code for passing a structure by value, not
4753 if (Flags.isByVal()) {
4754 // Note: Size includes alignment padding, so
4755 // struct x { short a; char b; }
4756 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4757 // These are the proper values we need for right-justifying the
4758 // aggregate in a parameter register.
4759 unsigned Size = Flags.getByValSize();
4761 // An empty aggregate parameter takes up no storage and no
4766 if (CallConv == CallingConv::Fast)
4769 // All aggregates smaller than 8 bytes must be passed right-justified.
4770 if (Size==1 || Size==2 || Size==4) {
4771 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4772 if (GPR_idx != NumGPRs) {
4773 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4774 MachinePointerInfo(), VT,
4775 false, false, false, 0);
4776 MemOpChains.push_back(Load.getValue(1));
4777 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4779 ArgOffset += PtrByteSize;
4784 if (GPR_idx == NumGPRs && Size < 8) {
4785 SDValue AddPtr = PtrOff;
4786 if (!isLittleEndian) {
4787 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4788 PtrOff.getValueType());
4789 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4791 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4794 ArgOffset += PtrByteSize;
4797 // Copy entire object into memory. There are cases where gcc-generated
4798 // code assumes it is there, even if it could be put entirely into
4799 // registers. (This is not what the doc says.)
4801 // FIXME: The above statement is likely due to a misunderstanding of the
4802 // documents. All arguments must be copied into the parameter area BY
4803 // THE CALLEE in the event that the callee takes the address of any
4804 // formal argument. That has not yet been implemented. However, it is
4805 // reasonable to use the stack area as a staging area for the register
4808 // Skip this for small aggregates, as we will use the same slot for a
4809 // right-justified copy, below.
4811 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4815 // When a register is available, pass a small aggregate right-justified.
4816 if (Size < 8 && GPR_idx != NumGPRs) {
4817 // The easiest way to get this right-justified in a register
4818 // is to copy the structure into the rightmost portion of a
4819 // local variable slot, then load the whole slot into the
4821 // FIXME: The memcpy seems to produce pretty awful code for
4822 // small aggregates, particularly for packed ones.
4823 // FIXME: It would be preferable to use the slot in the
4824 // parameter save area instead of a new local variable.
4825 SDValue AddPtr = PtrOff;
4826 if (!isLittleEndian) {
4827 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4828 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4830 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4834 // Load the slot into the register.
4835 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4836 MachinePointerInfo(),
4837 false, false, false, 0);
4838 MemOpChains.push_back(Load.getValue(1));
4839 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4841 // Done with this argument.
4842 ArgOffset += PtrByteSize;
4846 // For aggregates larger than PtrByteSize, copy the pieces of the
4847 // object that fit into registers from the parameter save area.
4848 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4849 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4850 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4851 if (GPR_idx != NumGPRs) {
4852 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4853 MachinePointerInfo(),
4854 false, false, false, 0);
4855 MemOpChains.push_back(Load.getValue(1));
4856 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4857 ArgOffset += PtrByteSize;
4859 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4866 switch (Arg.getSimpleValueType().SimpleTy) {
4867 default: llvm_unreachable("Unexpected ValueType for argument!");
4871 // These can be scalar arguments or elements of an integer array type
4872 // passed directly. Clang may use those instead of "byval" aggregate
4873 // types to avoid forcing arguments to memory unnecessarily.
4874 if (GPR_idx != NumGPRs) {
4875 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4877 if (CallConv == CallingConv::Fast)
4880 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4881 true, isTailCall, false, MemOpChains,
4882 TailCallArguments, dl);
4883 if (CallConv == CallingConv::Fast)
4884 ArgOffset += PtrByteSize;
4886 if (CallConv != CallingConv::Fast)
4887 ArgOffset += PtrByteSize;
4891 // These can be scalar arguments or elements of a float array type
4892 // passed directly. The latter are used to implement ELFv2 homogenous
4893 // float aggregates.
4895 // Named arguments go into FPRs first, and once they overflow, the
4896 // remaining arguments go into GPRs and then the parameter save area.
4897 // Unnamed arguments for vararg functions always go to GPRs and
4898 // then the parameter save area. For now, put all arguments to vararg
4899 // routines always in both locations (FPR *and* GPR or stack slot).
4900 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4901 bool NeededLoad = false;
4903 // First load the argument into the next available FPR.
4904 if (FPR_idx != NumFPRs)
4905 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4907 // Next, load the argument into GPR or stack slot if needed.
4908 if (!NeedGPROrStack)
4910 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4911 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4912 // once we support fp <-> gpr moves.
4914 // In the non-vararg case, this can only ever happen in the
4915 // presence of f32 array types, since otherwise we never run
4916 // out of FPRs before running out of GPRs.
4919 // Double values are always passed in a single GPR.
4920 if (Arg.getValueType() != MVT::f32) {
4921 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4923 // Non-array float values are extended and passed in a GPR.
4924 } else if (!Flags.isInConsecutiveRegs()) {
4925 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4926 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4928 // If we have an array of floats, we collect every odd element
4929 // together with its predecessor into one GPR.
4930 } else if (ArgOffset % PtrByteSize != 0) {
4932 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4933 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4934 if (!isLittleEndian)
4936 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4938 // The final element, if even, goes into the first half of a GPR.
4939 } else if (Flags.isInConsecutiveRegsLast()) {
4940 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4941 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4942 if (!isLittleEndian)
4943 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4944 DAG.getConstant(32, MVT::i32));
4946 // Non-final even elements are skipped; they will be handled
4947 // together the with subsequent argument on the next go-around.
4951 if (ArgVal.getNode())
4952 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4954 if (CallConv == CallingConv::Fast)
4957 // Single-precision floating-point values are mapped to the
4958 // second (rightmost) word of the stack doubleword.
4959 if (Arg.getValueType() == MVT::f32 &&
4960 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4961 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4962 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4965 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4966 true, isTailCall, false, MemOpChains,
4967 TailCallArguments, dl);
4971 // When passing an array of floats, the array occupies consecutive
4972 // space in the argument area; only round up to the next doubleword
4973 // at the end of the array. Otherwise, each float takes 8 bytes.
4974 if (CallConv != CallingConv::Fast || NeededLoad) {
4975 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4976 Flags.isInConsecutiveRegs()) ? 4 : 8;
4977 if (Flags.isInConsecutiveRegsLast())
4978 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4988 if (!Subtarget.hasQPX()) {
4989 // These can be scalar arguments or elements of a vector array type
4990 // passed directly. The latter are used to implement ELFv2 homogenous
4991 // vector aggregates.
4993 // For a varargs call, named arguments go into VRs or on the stack as
4994 // usual; unnamed arguments always go to the stack or the corresponding
4995 // GPRs when within range. For now, we always put the value in both
4996 // locations (or even all three).
4998 // We could elide this store in the case where the object fits
4999 // entirely in R registers. Maybe later.
5000 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5001 MachinePointerInfo(), false, false, 0);
5002 MemOpChains.push_back(Store);
5003 if (VR_idx != NumVRs) {
5004 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5005 MachinePointerInfo(),
5006 false, false, false, 0);
5007 MemOpChains.push_back(Load.getValue(1));
5009 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5010 Arg.getSimpleValueType() == MVT::v2i64) ?
5011 VSRH[VR_idx] : VR[VR_idx];
5014 RegsToPass.push_back(std::make_pair(VReg, Load));
5017 for (unsigned i=0; i<16; i+=PtrByteSize) {
5018 if (GPR_idx == NumGPRs)
5020 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5021 DAG.getConstant(i, PtrVT));
5022 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5023 false, false, false, 0);
5024 MemOpChains.push_back(Load.getValue(1));
5025 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5030 // Non-varargs Altivec params go into VRs or on the stack.
5031 if (VR_idx != NumVRs) {
5032 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5033 Arg.getSimpleValueType() == MVT::v2i64) ?
5034 VSRH[VR_idx] : VR[VR_idx];
5037 RegsToPass.push_back(std::make_pair(VReg, Arg));
5039 if (CallConv == CallingConv::Fast)
5042 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5043 true, isTailCall, true, MemOpChains,
5044 TailCallArguments, dl);
5045 if (CallConv == CallingConv::Fast)
5049 if (CallConv != CallingConv::Fast)
5054 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5055 "Invalid QPX parameter type");
5060 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5062 // We could elide this store in the case where the object fits
5063 // entirely in R registers. Maybe later.
5064 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5065 MachinePointerInfo(), false, false, 0);
5066 MemOpChains.push_back(Store);
5067 if (QFPR_idx != NumQFPRs) {
5068 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5069 Store, PtrOff, MachinePointerInfo(),
5070 false, false, false, 0);
5071 MemOpChains.push_back(Load.getValue(1));
5072 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5074 ArgOffset += (IsF32 ? 16 : 32);
5075 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5076 if (GPR_idx == NumGPRs)
5078 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5079 DAG.getConstant(i, PtrVT));
5080 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5081 false, false, false, 0);
5082 MemOpChains.push_back(Load.getValue(1));
5083 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5088 // Non-varargs QPX params go into registers or on the stack.
5089 if (QFPR_idx != NumQFPRs) {
5090 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5092 if (CallConv == CallingConv::Fast)
5095 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5096 true, isTailCall, true, MemOpChains,
5097 TailCallArguments, dl);
5098 if (CallConv == CallingConv::Fast)
5099 ArgOffset += (IsF32 ? 16 : 32);
5102 if (CallConv != CallingConv::Fast)
5103 ArgOffset += (IsF32 ? 16 : 32);
5109 assert(NumBytesActuallyUsed == ArgOffset);
5110 (void)NumBytesActuallyUsed;
5112 if (!MemOpChains.empty())
5113 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5115 // Check if this is an indirect call (MTCTR/BCTRL).
5116 // See PrepareCall() for more information about calls through function
5117 // pointers in the 64-bit SVR4 ABI.
5118 if (!isTailCall && !IsPatchPoint &&
5119 !isFunctionGlobalAddress(Callee) &&
5120 !isa<ExternalSymbolSDNode>(Callee)) {
5121 // Load r2 into a virtual register and store it to the TOC save area.
5122 setUsesTOCBasePtr(DAG);
5123 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5124 // TOC save area offset.
5125 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5126 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5127 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5128 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5129 MachinePointerInfo::getStack(TOCSaveOffset),
5131 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5132 // This does not mean the MTCTR instruction must use R12; it's easier
5133 // to model this as an extra parameter, so do that.
5134 if (isELFv2ABI && !IsPatchPoint)
5135 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5138 // Build a sequence of copy-to-reg nodes chained together with token chain
5139 // and flag operands which copy the outgoing args into the appropriate regs.
5141 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5142 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5143 RegsToPass[i].second, InFlag);
5144 InFlag = Chain.getValue(1);
5148 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5149 FPOp, true, TailCallArguments);
5151 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5152 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5153 NumBytes, Ins, InVals, CS);
5157 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5158 CallingConv::ID CallConv, bool isVarArg,
5159 bool isTailCall, bool IsPatchPoint,
5160 const SmallVectorImpl<ISD::OutputArg> &Outs,
5161 const SmallVectorImpl<SDValue> &OutVals,
5162 const SmallVectorImpl<ISD::InputArg> &Ins,
5163 SDLoc dl, SelectionDAG &DAG,
5164 SmallVectorImpl<SDValue> &InVals,
5165 ImmutableCallSite *CS) const {
5167 unsigned NumOps = Outs.size();
5169 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5170 bool isPPC64 = PtrVT == MVT::i64;
5171 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5173 MachineFunction &MF = DAG.getMachineFunction();
5175 // Mark this function as potentially containing a function that contains a
5176 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5177 // and restoring the callers stack pointer in this functions epilog. This is
5178 // done because by tail calling the called function might overwrite the value
5179 // in this function's (MF) stack pointer stack slot 0(SP).
5180 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5181 CallConv == CallingConv::Fast)
5182 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5184 // Count how many bytes are to be pushed on the stack, including the linkage
5185 // area, and parameter passing area. We start with 24/48 bytes, which is
5186 // prereserved space for [SP][CR][LR][3 x unused].
5187 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5188 unsigned NumBytes = LinkageSize;
5190 // Add up all the space actually used.
5191 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5192 // they all go in registers, but we must reserve stack space for them for
5193 // possible use by the caller. In varargs or 64-bit calls, parameters are
5194 // assigned stack space in order, with padding so Altivec parameters are
5196 unsigned nAltivecParamsAtEnd = 0;
5197 for (unsigned i = 0; i != NumOps; ++i) {
5198 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5199 EVT ArgVT = Outs[i].VT;
5200 // Varargs Altivec parameters are padded to a 16 byte boundary.
5201 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5202 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5203 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5204 if (!isVarArg && !isPPC64) {
5205 // Non-varargs Altivec parameters go after all the non-Altivec
5206 // parameters; handle those later so we know how much padding we need.
5207 nAltivecParamsAtEnd++;
5210 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5211 NumBytes = ((NumBytes+15)/16)*16;
5213 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5216 // Allow for Altivec parameters at the end, if needed.
5217 if (nAltivecParamsAtEnd) {
5218 NumBytes = ((NumBytes+15)/16)*16;
5219 NumBytes += 16*nAltivecParamsAtEnd;
5222 // The prolog code of the callee may store up to 8 GPR argument registers to
5223 // the stack, allowing va_start to index over them in memory if its varargs.
5224 // Because we cannot tell if this is needed on the caller side, we have to
5225 // conservatively assume that it is needed. As such, make sure we have at
5226 // least enough stack space for the caller to store the 8 GPRs.
5227 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5229 // Tail call needs the stack to be aligned.
5230 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5231 CallConv == CallingConv::Fast)
5232 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5234 // Calculate by how many bytes the stack has to be adjusted in case of tail
5235 // call optimization.
5236 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5238 // To protect arguments on the stack from being clobbered in a tail call,
5239 // force all the loads to happen before doing any other lowering.
5241 Chain = DAG.getStackArgumentTokenFactor(Chain);
5243 // Adjust the stack pointer for the new arguments...
5244 // These operations are automatically eliminated by the prolog/epilog pass
5245 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5247 SDValue CallSeqStart = Chain;
5249 // Load the return address and frame pointer so it can be move somewhere else
5252 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5255 // Set up a copy of the stack pointer for use loading and storing any
5256 // arguments that may not fit in the registers available for argument
5260 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5262 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5264 // Figure out which arguments are going to go in registers, and which in
5265 // memory. Also, if this is a vararg function, floating point operations
5266 // must be stored to our stack, and loaded into integer regs as well, if
5267 // any integer regs are available for argument passing.
5268 unsigned ArgOffset = LinkageSize;
5269 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5271 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5272 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5273 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5275 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5276 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5277 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5279 static const MCPhysReg VR[] = {
5280 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5281 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5283 const unsigned NumGPRs = array_lengthof(GPR_32);
5284 const unsigned NumFPRs = 13;
5285 const unsigned NumVRs = array_lengthof(VR);
5287 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5289 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5290 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5292 SmallVector<SDValue, 8> MemOpChains;
5293 for (unsigned i = 0; i != NumOps; ++i) {
5294 SDValue Arg = OutVals[i];
5295 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5297 // PtrOff will be used to store the current argument to the stack if a
5298 // register cannot be found for it.
5301 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5303 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5305 // On PPC64, promote integers to 64-bit values.
5306 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5307 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5308 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5309 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5312 // FIXME memcpy is used way more than necessary. Correctness first.
5313 // Note: "by value" is code for passing a structure by value, not
5315 if (Flags.isByVal()) {
5316 unsigned Size = Flags.getByValSize();
5317 // Very small objects are passed right-justified. Everything else is
5318 // passed left-justified.
5319 if (Size==1 || Size==2) {
5320 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5321 if (GPR_idx != NumGPRs) {
5322 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5323 MachinePointerInfo(), VT,
5324 false, false, false, 0);
5325 MemOpChains.push_back(Load.getValue(1));
5326 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5328 ArgOffset += PtrByteSize;
5330 SDValue Const = DAG.getConstant(PtrByteSize - Size,
5331 PtrOff.getValueType());
5332 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5333 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5336 ArgOffset += PtrByteSize;
5340 // Copy entire object into memory. There are cases where gcc-generated
5341 // code assumes it is there, even if it could be put entirely into
5342 // registers. (This is not what the doc says.)
5343 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5347 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5348 // copy the pieces of the object that fit into registers from the
5349 // parameter save area.
5350 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5351 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5352 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5353 if (GPR_idx != NumGPRs) {
5354 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5355 MachinePointerInfo(),
5356 false, false, false, 0);
5357 MemOpChains.push_back(Load.getValue(1));
5358 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5359 ArgOffset += PtrByteSize;
5361 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5368 switch (Arg.getSimpleValueType().SimpleTy) {
5369 default: llvm_unreachable("Unexpected ValueType for argument!");
5373 if (GPR_idx != NumGPRs) {
5374 if (Arg.getValueType() == MVT::i1)
5375 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5377 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5379 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5380 isPPC64, isTailCall, false, MemOpChains,
5381 TailCallArguments, dl);
5383 ArgOffset += PtrByteSize;
5387 if (FPR_idx != NumFPRs) {
5388 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5391 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5392 MachinePointerInfo(), false, false, 0);
5393 MemOpChains.push_back(Store);
5395 // Float varargs are always shadowed in available integer registers
5396 if (GPR_idx != NumGPRs) {
5397 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5398 MachinePointerInfo(), false, false,
5400 MemOpChains.push_back(Load.getValue(1));
5401 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5403 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5404 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5405 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5406 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5407 MachinePointerInfo(),
5408 false, false, false, 0);
5409 MemOpChains.push_back(Load.getValue(1));
5410 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5413 // If we have any FPRs remaining, we may also have GPRs remaining.
5414 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5416 if (GPR_idx != NumGPRs)
5418 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5419 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5423 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5424 isPPC64, isTailCall, false, MemOpChains,
5425 TailCallArguments, dl);
5429 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5436 // These go aligned on the stack, or in the corresponding R registers
5437 // when within range. The Darwin PPC ABI doc claims they also go in
5438 // V registers; in fact gcc does this only for arguments that are
5439 // prototyped, not for those that match the ... We do it for all
5440 // arguments, seems to work.
5441 while (ArgOffset % 16 !=0) {
5442 ArgOffset += PtrByteSize;
5443 if (GPR_idx != NumGPRs)
5446 // We could elide this store in the case where the object fits
5447 // entirely in R registers. Maybe later.
5448 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5449 DAG.getConstant(ArgOffset, PtrVT));
5450 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5451 MachinePointerInfo(), false, false, 0);
5452 MemOpChains.push_back(Store);
5453 if (VR_idx != NumVRs) {
5454 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5455 MachinePointerInfo(),
5456 false, false, false, 0);
5457 MemOpChains.push_back(Load.getValue(1));
5458 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5461 for (unsigned i=0; i<16; i+=PtrByteSize) {
5462 if (GPR_idx == NumGPRs)
5464 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5465 DAG.getConstant(i, PtrVT));
5466 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5467 false, false, false, 0);
5468 MemOpChains.push_back(Load.getValue(1));
5469 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5474 // Non-varargs Altivec params generally go in registers, but have
5475 // stack space allocated at the end.
5476 if (VR_idx != NumVRs) {
5477 // Doesn't have GPR space allocated.
5478 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5479 } else if (nAltivecParamsAtEnd==0) {
5480 // We are emitting Altivec params in order.
5481 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5482 isPPC64, isTailCall, true, MemOpChains,
5483 TailCallArguments, dl);
5489 // If all Altivec parameters fit in registers, as they usually do,
5490 // they get stack space following the non-Altivec parameters. We
5491 // don't track this here because nobody below needs it.
5492 // If there are more Altivec parameters than fit in registers emit
5494 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5496 // Offset is aligned; skip 1st 12 params which go in V registers.
5497 ArgOffset = ((ArgOffset+15)/16)*16;
5499 for (unsigned i = 0; i != NumOps; ++i) {
5500 SDValue Arg = OutVals[i];
5501 EVT ArgType = Outs[i].VT;
5502 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5503 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5506 // We are emitting Altivec params in order.
5507 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5508 isPPC64, isTailCall, true, MemOpChains,
5509 TailCallArguments, dl);
5516 if (!MemOpChains.empty())
5517 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5519 // On Darwin, R12 must contain the address of an indirect callee. This does
5520 // not mean the MTCTR instruction must use R12; it's easier to model this as
5521 // an extra parameter, so do that.
5523 !isFunctionGlobalAddress(Callee) &&
5524 !isa<ExternalSymbolSDNode>(Callee) &&
5525 !isBLACompatibleAddress(Callee, DAG))
5526 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5527 PPC::R12), Callee));
5529 // Build a sequence of copy-to-reg nodes chained together with token chain
5530 // and flag operands which copy the outgoing args into the appropriate regs.
5532 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5533 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5534 RegsToPass[i].second, InFlag);
5535 InFlag = Chain.getValue(1);
5539 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5540 FPOp, true, TailCallArguments);
5542 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5543 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5544 NumBytes, Ins, InVals, CS);
5548 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5549 MachineFunction &MF, bool isVarArg,
5550 const SmallVectorImpl<ISD::OutputArg> &Outs,
5551 LLVMContext &Context) const {
5552 SmallVector<CCValAssign, 16> RVLocs;
5553 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5554 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5558 PPCTargetLowering::LowerReturn(SDValue Chain,
5559 CallingConv::ID CallConv, bool isVarArg,
5560 const SmallVectorImpl<ISD::OutputArg> &Outs,
5561 const SmallVectorImpl<SDValue> &OutVals,
5562 SDLoc dl, SelectionDAG &DAG) const {
5564 SmallVector<CCValAssign, 16> RVLocs;
5565 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5567 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5570 SmallVector<SDValue, 4> RetOps(1, Chain);
5572 // Copy the result values into the output registers.
5573 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5574 CCValAssign &VA = RVLocs[i];
5575 assert(VA.isRegLoc() && "Can only return in registers!");
5577 SDValue Arg = OutVals[i];
5579 switch (VA.getLocInfo()) {
5580 default: llvm_unreachable("Unknown loc info!");
5581 case CCValAssign::Full: break;
5582 case CCValAssign::AExt:
5583 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5585 case CCValAssign::ZExt:
5586 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5588 case CCValAssign::SExt:
5589 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5593 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5594 Flag = Chain.getValue(1);
5595 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5598 RetOps[0] = Chain; // Update chain.
5600 // Add the flag if we have it.
5602 RetOps.push_back(Flag);
5604 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5607 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5608 const PPCSubtarget &Subtarget) const {
5609 // When we pop the dynamic allocation we need to restore the SP link.
5612 // Get the corect type for pointers.
5613 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5615 // Construct the stack pointer operand.
5616 bool isPPC64 = Subtarget.isPPC64();
5617 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5618 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5620 // Get the operands for the STACKRESTORE.
5621 SDValue Chain = Op.getOperand(0);
5622 SDValue SaveSP = Op.getOperand(1);
5624 // Load the old link SP.
5625 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5626 MachinePointerInfo(),
5627 false, false, false, 0);
5629 // Restore the stack pointer.
5630 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5632 // Store the old link SP.
5633 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5640 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5641 MachineFunction &MF = DAG.getMachineFunction();
5642 bool isPPC64 = Subtarget.isPPC64();
5643 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5645 // Get current frame pointer save index. The users of this index will be
5646 // primarily DYNALLOC instructions.
5647 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5648 int RASI = FI->getReturnAddrSaveIndex();
5650 // If the frame pointer save index hasn't been defined yet.
5652 // Find out what the fix offset of the frame pointer save area.
5653 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5654 // Allocate the frame index for frame pointer save area.
5655 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5657 FI->setReturnAddrSaveIndex(RASI);
5659 return DAG.getFrameIndex(RASI, PtrVT);
5663 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5664 MachineFunction &MF = DAG.getMachineFunction();
5665 bool isPPC64 = Subtarget.isPPC64();
5666 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5668 // Get current frame pointer save index. The users of this index will be
5669 // primarily DYNALLOC instructions.
5670 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5671 int FPSI = FI->getFramePointerSaveIndex();
5673 // If the frame pointer save index hasn't been defined yet.
5675 // Find out what the fix offset of the frame pointer save area.
5676 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5677 // Allocate the frame index for frame pointer save area.
5678 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5680 FI->setFramePointerSaveIndex(FPSI);
5682 return DAG.getFrameIndex(FPSI, PtrVT);
5685 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5687 const PPCSubtarget &Subtarget) const {
5689 SDValue Chain = Op.getOperand(0);
5690 SDValue Size = Op.getOperand(1);
5693 // Get the corect type for pointers.
5694 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5696 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5697 DAG.getConstant(0, PtrVT), Size);
5698 // Construct a node for the frame pointer save index.
5699 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5700 // Build a DYNALLOC node.
5701 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5702 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5703 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5706 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5707 SelectionDAG &DAG) const {
5709 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5710 DAG.getVTList(MVT::i32, MVT::Other),
5711 Op.getOperand(0), Op.getOperand(1));
5714 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5715 SelectionDAG &DAG) const {
5717 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5718 Op.getOperand(0), Op.getOperand(1));
5721 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5722 if (Op.getValueType().isVector())
5723 return LowerVectorLoad(Op, DAG);
5725 assert(Op.getValueType() == MVT::i1 &&
5726 "Custom lowering only for i1 loads");
5728 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5731 LoadSDNode *LD = cast<LoadSDNode>(Op);
5733 SDValue Chain = LD->getChain();
5734 SDValue BasePtr = LD->getBasePtr();
5735 MachineMemOperand *MMO = LD->getMemOperand();
5737 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5738 BasePtr, MVT::i8, MMO);
5739 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5741 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5742 return DAG.getMergeValues(Ops, dl);
5745 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5746 if (Op.getOperand(1).getValueType().isVector())
5747 return LowerVectorStore(Op, DAG);
5749 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5750 "Custom lowering only for i1 stores");
5752 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5755 StoreSDNode *ST = cast<StoreSDNode>(Op);
5757 SDValue Chain = ST->getChain();
5758 SDValue BasePtr = ST->getBasePtr();
5759 SDValue Value = ST->getValue();
5760 MachineMemOperand *MMO = ST->getMemOperand();
5762 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5763 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5766 // FIXME: Remove this once the ANDI glue bug is fixed:
5767 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5768 assert(Op.getValueType() == MVT::i1 &&
5769 "Custom lowering only for i1 results");
5772 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5776 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5778 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5779 // Not FP? Not a fsel.
5780 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5781 !Op.getOperand(2).getValueType().isFloatingPoint())
5784 // We might be able to do better than this under some circumstances, but in
5785 // general, fsel-based lowering of select is a finite-math-only optimization.
5786 // For more information, see section F.3 of the 2.06 ISA specification.
5787 if (!DAG.getTarget().Options.NoInfsFPMath ||
5788 !DAG.getTarget().Options.NoNaNsFPMath)
5791 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5793 EVT ResVT = Op.getValueType();
5794 EVT CmpVT = Op.getOperand(0).getValueType();
5795 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5796 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5799 // If the RHS of the comparison is a 0.0, we don't need to do the
5800 // subtraction at all.
5802 if (isFloatingPointZero(RHS))
5804 default: break; // SETUO etc aren't handled by fsel.
5808 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5809 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5810 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5811 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5812 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5813 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5814 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5817 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5820 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5821 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5822 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5825 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5828 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5829 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5830 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5831 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5836 default: break; // SETUO etc aren't handled by fsel.
5840 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5841 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5842 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5843 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5844 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5845 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5846 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5847 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5850 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5851 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5852 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5853 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5856 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5857 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5858 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5859 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5862 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5863 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5864 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5865 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5868 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5869 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5870 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5871 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5876 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5879 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5880 SDValue Src = Op.getOperand(0);
5881 if (Src.getValueType() == MVT::f32)
5882 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5885 switch (Op.getSimpleValueType().SimpleTy) {
5886 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5889 Op.getOpcode() == ISD::FP_TO_SINT
5891 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5895 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5896 "i64 FP_TO_UINT is supported only with FPCVT");
5897 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5903 // Convert the FP value to an int value through memory.
5904 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5905 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5906 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5907 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5908 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5910 // Emit a store to the stack slot.
5913 MachineFunction &MF = DAG.getMachineFunction();
5914 MachineMemOperand *MMO =
5915 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5916 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5917 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5918 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5920 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5921 MPI, false, false, 0);
5923 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5925 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5926 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5927 DAG.getConstant(4, FIPtr.getValueType()));
5928 MPI = MPI.getWithOffset(4);
5936 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5939 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5941 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5942 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5946 // We're trying to insert a regular store, S, and then a load, L. If the
5947 // incoming value, O, is a load, we might just be able to have our load use the
5948 // address used by O. However, we don't know if anything else will store to
5949 // that address before we can load from it. To prevent this situation, we need
5950 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5951 // the same chain operand as O, we create a token factor from the chain results
5952 // of O and L, and we replace all uses of O's chain result with that token
5953 // factor (see spliceIntoChain below for this last part).
5954 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5957 ISD::LoadExtType ET) const {
5959 if (ET == ISD::NON_EXTLOAD &&
5960 (Op.getOpcode() == ISD::FP_TO_UINT ||
5961 Op.getOpcode() == ISD::FP_TO_SINT) &&
5962 isOperationLegalOrCustom(Op.getOpcode(),
5963 Op.getOperand(0).getValueType())) {
5965 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5969 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5970 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5971 LD->isNonTemporal())
5973 if (LD->getMemoryVT() != MemVT)
5976 RLI.Ptr = LD->getBasePtr();
5977 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5978 assert(LD->getAddressingMode() == ISD::PRE_INC &&
5979 "Non-pre-inc AM on PPC?");
5980 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5984 RLI.Chain = LD->getChain();
5985 RLI.MPI = LD->getPointerInfo();
5986 RLI.IsInvariant = LD->isInvariant();
5987 RLI.Alignment = LD->getAlignment();
5988 RLI.AAInfo = LD->getAAInfo();
5989 RLI.Ranges = LD->getRanges();
5991 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5995 // Given the head of the old chain, ResChain, insert a token factor containing
5996 // it and NewResChain, and make users of ResChain now be users of that token
5998 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5999 SDValue NewResChain,
6000 SelectionDAG &DAG) const {
6004 SDLoc dl(NewResChain);
6006 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6007 NewResChain, DAG.getUNDEF(MVT::Other));
6008 assert(TF.getNode() != NewResChain.getNode() &&
6009 "A new TF really is required here");
6011 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6012 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6015 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6016 SelectionDAG &DAG) const {
6019 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6020 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6023 SDValue Value = Op.getOperand(0);
6024 // The values are now known to be -1 (false) or 1 (true). To convert this
6025 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6026 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6027 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6029 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6030 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6031 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6033 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6035 if (Op.getValueType() != MVT::v4f64)
6036 Value = DAG.getNode(ISD::FP_ROUND, dl,
6037 Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6041 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6042 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6045 if (Op.getOperand(0).getValueType() == MVT::i1)
6046 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6047 DAG.getConstantFP(1.0, Op.getValueType()),
6048 DAG.getConstantFP(0.0, Op.getValueType()));
6050 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6051 "UINT_TO_FP is supported only with FPCVT");
6053 // If we have FCFIDS, then use it when converting to single-precision.
6054 // Otherwise, convert to double-precision and then round.
6055 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6056 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6058 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6060 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6064 if (Op.getOperand(0).getValueType() == MVT::i64) {
6065 SDValue SINT = Op.getOperand(0);
6066 // When converting to single-precision, we actually need to convert
6067 // to double-precision first and then round to single-precision.
6068 // To avoid double-rounding effects during that operation, we have
6069 // to prepare the input operand. Bits that might be truncated when
6070 // converting to double-precision are replaced by a bit that won't
6071 // be lost at this stage, but is below the single-precision rounding
6074 // However, if -enable-unsafe-fp-math is in effect, accept double
6075 // rounding to avoid the extra overhead.
6076 if (Op.getValueType() == MVT::f32 &&
6077 !Subtarget.hasFPCVT() &&
6078 !DAG.getTarget().Options.UnsafeFPMath) {
6080 // Twiddle input to make sure the low 11 bits are zero. (If this
6081 // is the case, we are guaranteed the value will fit into the 53 bit
6082 // mantissa of an IEEE double-precision value without rounding.)
6083 // If any of those low 11 bits were not zero originally, make sure
6084 // bit 12 (value 2048) is set instead, so that the final rounding
6085 // to single-precision gets the correct result.
6086 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6087 SINT, DAG.getConstant(2047, MVT::i64));
6088 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6089 Round, DAG.getConstant(2047, MVT::i64));
6090 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6091 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6092 Round, DAG.getConstant(-2048, MVT::i64));
6094 // However, we cannot use that value unconditionally: if the magnitude
6095 // of the input value is small, the bit-twiddling we did above might
6096 // end up visibly changing the output. Fortunately, in that case, we
6097 // don't need to twiddle bits since the original input will convert
6098 // exactly to double-precision floating-point already. Therefore,
6099 // construct a conditional to use the original value if the top 11
6100 // bits are all sign-bit copies, and use the rounded value computed
6102 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6103 SINT, DAG.getConstant(53, MVT::i32));
6104 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6105 Cond, DAG.getConstant(1, MVT::i64));
6106 Cond = DAG.getSetCC(dl, MVT::i32,
6107 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6109 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6115 MachineFunction &MF = DAG.getMachineFunction();
6116 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6117 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6118 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6120 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6121 } else if (Subtarget.hasLFIWAX() &&
6122 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6123 MachineMemOperand *MMO =
6124 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6125 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6126 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6127 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6128 DAG.getVTList(MVT::f64, MVT::Other),
6129 Ops, MVT::i32, MMO);
6130 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6131 } else if (Subtarget.hasFPCVT() &&
6132 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6133 MachineMemOperand *MMO =
6134 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6135 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6136 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6137 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6138 DAG.getVTList(MVT::f64, MVT::Other),
6139 Ops, MVT::i32, MMO);
6140 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6141 } else if (((Subtarget.hasLFIWAX() &&
6142 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6143 (Subtarget.hasFPCVT() &&
6144 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6145 SINT.getOperand(0).getValueType() == MVT::i32) {
6146 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6147 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6149 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6150 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6153 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6154 MachinePointerInfo::getFixedStack(FrameIdx),
6157 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6158 "Expected an i32 store");
6162 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6165 MachineMemOperand *MMO =
6166 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6167 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6168 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6169 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6170 PPCISD::LFIWZX : PPCISD::LFIWAX,
6171 dl, DAG.getVTList(MVT::f64, MVT::Other),
6172 Ops, MVT::i32, MMO);
6174 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6176 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6178 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6179 FP = DAG.getNode(ISD::FP_ROUND, dl,
6180 MVT::f32, FP, DAG.getIntPtrConstant(0));
6184 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6185 "Unhandled INT_TO_FP type in custom expander!");
6186 // Since we only generate this in 64-bit mode, we can take advantage of
6187 // 64-bit registers. In particular, sign extend the input value into the
6188 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6189 // then lfd it and fcfid it.
6190 MachineFunction &MF = DAG.getMachineFunction();
6191 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6192 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6195 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6198 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6200 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6201 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6203 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6204 MachinePointerInfo::getFixedStack(FrameIdx),
6207 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6208 "Expected an i32 store");
6212 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6216 MachineMemOperand *MMO =
6217 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6218 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6219 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6220 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6221 PPCISD::LFIWZX : PPCISD::LFIWAX,
6222 dl, DAG.getVTList(MVT::f64, MVT::Other),
6223 Ops, MVT::i32, MMO);
6225 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6227 assert(Subtarget.isPPC64() &&
6228 "i32->FP without LFIWAX supported only on PPC64");
6230 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6231 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6233 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6236 // STD the extended value into the stack slot.
6237 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6238 MachinePointerInfo::getFixedStack(FrameIdx),
6241 // Load the value as a double.
6242 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6243 MachinePointerInfo::getFixedStack(FrameIdx),
6244 false, false, false, 0);
6247 // FCFID it and return it.
6248 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6249 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6250 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6254 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6255 SelectionDAG &DAG) const {
6258 The rounding mode is in bits 30:31 of FPSR, and has the following
6265 FLT_ROUNDS, on the other hand, expects the following:
6272 To perform the conversion, we do:
6273 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6276 MachineFunction &MF = DAG.getMachineFunction();
6277 EVT VT = Op.getValueType();
6278 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6280 // Save FP Control Word to register
6282 MVT::f64, // return register
6283 MVT::Glue // unused in this context
6285 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6287 // Save FP register to stack slot
6288 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6289 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6290 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6291 StackSlot, MachinePointerInfo(), false, false,0);
6293 // Load FP Control Word from low 32 bits of stack slot.
6294 SDValue Four = DAG.getConstant(4, PtrVT);
6295 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6296 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6297 false, false, false, 0);
6299 // Transform as necessary
6301 DAG.getNode(ISD::AND, dl, MVT::i32,
6302 CWD, DAG.getConstant(3, MVT::i32));
6304 DAG.getNode(ISD::SRL, dl, MVT::i32,
6305 DAG.getNode(ISD::AND, dl, MVT::i32,
6306 DAG.getNode(ISD::XOR, dl, MVT::i32,
6307 CWD, DAG.getConstant(3, MVT::i32)),
6308 DAG.getConstant(3, MVT::i32)),
6309 DAG.getConstant(1, MVT::i32));
6312 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6314 return DAG.getNode((VT.getSizeInBits() < 16 ?
6315 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6318 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6319 EVT VT = Op.getValueType();
6320 unsigned BitWidth = VT.getSizeInBits();
6322 assert(Op.getNumOperands() == 3 &&
6323 VT == Op.getOperand(1).getValueType() &&
6326 // Expand into a bunch of logical ops. Note that these ops
6327 // depend on the PPC behavior for oversized shift amounts.
6328 SDValue Lo = Op.getOperand(0);
6329 SDValue Hi = Op.getOperand(1);
6330 SDValue Amt = Op.getOperand(2);
6331 EVT AmtVT = Amt.getValueType();
6333 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6334 DAG.getConstant(BitWidth, AmtVT), Amt);
6335 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6336 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6337 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6338 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6339 DAG.getConstant(-BitWidth, AmtVT));
6340 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6341 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6342 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6343 SDValue OutOps[] = { OutLo, OutHi };
6344 return DAG.getMergeValues(OutOps, dl);
6347 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6348 EVT VT = Op.getValueType();
6350 unsigned BitWidth = VT.getSizeInBits();
6351 assert(Op.getNumOperands() == 3 &&
6352 VT == Op.getOperand(1).getValueType() &&
6355 // Expand into a bunch of logical ops. Note that these ops
6356 // depend on the PPC behavior for oversized shift amounts.
6357 SDValue Lo = Op.getOperand(0);
6358 SDValue Hi = Op.getOperand(1);
6359 SDValue Amt = Op.getOperand(2);
6360 EVT AmtVT = Amt.getValueType();
6362 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6363 DAG.getConstant(BitWidth, AmtVT), Amt);
6364 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6365 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6366 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6367 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6368 DAG.getConstant(-BitWidth, AmtVT));
6369 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6370 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6371 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6372 SDValue OutOps[] = { OutLo, OutHi };
6373 return DAG.getMergeValues(OutOps, dl);
6376 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6378 EVT VT = Op.getValueType();
6379 unsigned BitWidth = VT.getSizeInBits();
6380 assert(Op.getNumOperands() == 3 &&
6381 VT == Op.getOperand(1).getValueType() &&
6384 // Expand into a bunch of logical ops, followed by a select_cc.
6385 SDValue Lo = Op.getOperand(0);
6386 SDValue Hi = Op.getOperand(1);
6387 SDValue Amt = Op.getOperand(2);
6388 EVT AmtVT = Amt.getValueType();
6390 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6391 DAG.getConstant(BitWidth, AmtVT), Amt);
6392 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6393 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6394 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6395 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6396 DAG.getConstant(-BitWidth, AmtVT));
6397 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6398 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6399 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6400 Tmp4, Tmp6, ISD::SETLE);
6401 SDValue OutOps[] = { OutLo, OutHi };
6402 return DAG.getMergeValues(OutOps, dl);
6405 //===----------------------------------------------------------------------===//
6406 // Vector related lowering.
6409 /// BuildSplatI - Build a canonical splati of Val with an element size of
6410 /// SplatSize. Cast the result to VT.
6411 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6412 SelectionDAG &DAG, SDLoc dl) {
6413 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6415 static const MVT VTys[] = { // canonical VT to use for each size.
6416 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6419 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6421 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6425 EVT CanonicalVT = VTys[SplatSize-1];
6427 // Build a canonical splat for this value.
6428 SDValue Elt = DAG.getConstant(Val, MVT::i32);
6429 SmallVector<SDValue, 8> Ops;
6430 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6431 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6432 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6435 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6436 /// specified intrinsic ID.
6437 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6438 SelectionDAG &DAG, SDLoc dl,
6439 EVT DestVT = MVT::Other) {
6440 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6441 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6442 DAG.getConstant(IID, MVT::i32), Op);
6445 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6446 /// specified intrinsic ID.
6447 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6448 SelectionDAG &DAG, SDLoc dl,
6449 EVT DestVT = MVT::Other) {
6450 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6451 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6452 DAG.getConstant(IID, MVT::i32), LHS, RHS);
6455 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6456 /// specified intrinsic ID.
6457 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6458 SDValue Op2, SelectionDAG &DAG,
6459 SDLoc dl, EVT DestVT = MVT::Other) {
6460 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6461 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6462 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6466 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6467 /// amount. The result has the specified value type.
6468 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6469 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6470 // Force LHS/RHS to be the right type.
6471 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6472 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6475 for (unsigned i = 0; i != 16; ++i)
6477 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6478 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6481 // If this is a case we can't handle, return null and let the default
6482 // expansion code take care of it. If we CAN select this case, and if it
6483 // selects to a single instruction, return Op. Otherwise, if we can codegen
6484 // this case more efficiently than a constant pool load, lower it to the
6485 // sequence of ops that should be used.
6486 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6487 SelectionDAG &DAG) const {
6489 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6490 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6492 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6493 // We first build an i32 vector, load it into a QPX register,
6494 // then convert it to a floating-point vector and compare it
6495 // to a zero vector to get the boolean result.
6496 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6497 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6498 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6499 EVT PtrVT = getPointerTy();
6500 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6502 assert(BVN->getNumOperands() == 4 &&
6503 "BUILD_VECTOR for v4i1 does not have 4 operands");
6505 bool IsConst = true;
6506 for (unsigned i = 0; i < 4; ++i) {
6507 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6508 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6516 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6518 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6520 SmallVector<Constant*, 4> CV(4, NegOne);
6521 for (unsigned i = 0; i < 4; ++i) {
6522 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6523 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6524 else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6525 getConstantIntValue()->isZero())
6531 Constant *CP = ConstantVector::get(CV);
6532 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6533 16 /* alignment */);
6535 SmallVector<SDValue, 2> Ops;
6536 Ops.push_back(DAG.getEntryNode());
6537 Ops.push_back(CPIdx);
6539 SmallVector<EVT, 2> ValueVTs;
6540 ValueVTs.push_back(MVT::v4i1);
6541 ValueVTs.push_back(MVT::Other); // chain
6542 SDVTList VTs = DAG.getVTList(ValueVTs);
6544 return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6545 dl, VTs, Ops, MVT::v4f32,
6546 MachinePointerInfo::getConstantPool());
6549 SmallVector<SDValue, 4> Stores;
6550 for (unsigned i = 0; i < 4; ++i) {
6551 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6553 unsigned Offset = 4*i;
6554 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6555 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6557 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6558 if (StoreSize > 4) {
6559 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6560 BVN->getOperand(i), Idx,
6561 PtrInfo.getWithOffset(Offset),
6562 MVT::i32, false, false, 0));
6564 SDValue StoreValue = BVN->getOperand(i);
6566 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6568 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6570 PtrInfo.getWithOffset(Offset),
6576 if (!Stores.empty())
6577 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6579 StoreChain = DAG.getEntryNode();
6581 // Now load from v4i32 into the QPX register; this will extend it to
6582 // v4i64 but not yet convert it to a floating point. Nevertheless, this
6583 // is typed as v4f64 because the QPX register integer states are not
6584 // explicitly represented.
6586 SmallVector<SDValue, 2> Ops;
6587 Ops.push_back(StoreChain);
6588 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6589 Ops.push_back(FIdx);
6591 SmallVector<EVT, 2> ValueVTs;
6592 ValueVTs.push_back(MVT::v4f64);
6593 ValueVTs.push_back(MVT::Other); // chain
6594 SDVTList VTs = DAG.getVTList(ValueVTs);
6596 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6597 dl, VTs, Ops, MVT::v4i32, PtrInfo);
6598 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6599 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6602 SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6603 FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6604 FPZeros, FPZeros, FPZeros, FPZeros);
6606 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6609 // All other QPX vectors are handled by generic code.
6610 if (Subtarget.hasQPX())
6613 // Check if this is a splat of a constant value.
6614 APInt APSplatBits, APSplatUndef;
6615 unsigned SplatBitSize;
6617 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6618 HasAnyUndefs, 0, true) || SplatBitSize > 32)
6621 unsigned SplatBits = APSplatBits.getZExtValue();
6622 unsigned SplatUndef = APSplatUndef.getZExtValue();
6623 unsigned SplatSize = SplatBitSize / 8;
6625 // First, handle single instruction cases.
6628 if (SplatBits == 0) {
6629 // Canonicalize all zero vectors to be v4i32.
6630 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6631 SDValue Z = DAG.getConstant(0, MVT::i32);
6632 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6633 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6638 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6639 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6641 if (SextVal >= -16 && SextVal <= 15)
6642 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6645 // Two instruction sequences.
6647 // If this value is in the range [-32,30] and is even, use:
6648 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6649 // If this value is in the range [17,31] and is odd, use:
6650 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6651 // If this value is in the range [-31,-17] and is odd, use:
6652 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6653 // Note the last two are three-instruction sequences.
6654 if (SextVal >= -32 && SextVal <= 31) {
6655 // To avoid having these optimizations undone by constant folding,
6656 // we convert to a pseudo that will be expanded later into one of
6658 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6659 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6660 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6661 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6662 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6663 if (VT == Op.getValueType())
6666 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6669 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6670 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6672 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6673 // Make -1 and vspltisw -1:
6674 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6676 // Make the VSLW intrinsic, computing 0x8000_0000.
6677 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6680 // xor by OnesV to invert it.
6681 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6682 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6685 // The remaining cases assume either big endian element order or
6686 // a splat-size that equates to the element size of the vector
6687 // to be built. An example that doesn't work for little endian is
6688 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6689 // and a vector element size of 16 bits. The code below will
6690 // produce the vector in big endian element order, which for little
6691 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6693 // For now, just avoid these optimizations in that case.
6694 // FIXME: Develop correct optimizations for LE with mismatched
6695 // splat and element sizes.
6697 if (Subtarget.isLittleEndian() &&
6698 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6701 // Check to see if this is a wide variety of vsplti*, binop self cases.
6702 static const signed char SplatCsts[] = {
6703 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6704 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6707 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6708 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6709 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6710 int i = SplatCsts[idx];
6712 // Figure out what shift amount will be used by altivec if shifted by i in
6714 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6716 // vsplti + shl self.
6717 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6718 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6719 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6720 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6721 Intrinsic::ppc_altivec_vslw
6723 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6724 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6727 // vsplti + srl self.
6728 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6729 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6730 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6731 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6732 Intrinsic::ppc_altivec_vsrw
6734 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6735 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6738 // vsplti + sra self.
6739 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6740 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6741 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6742 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6743 Intrinsic::ppc_altivec_vsraw
6745 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6746 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6749 // vsplti + rol self.
6750 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6751 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6752 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6753 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6754 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6755 Intrinsic::ppc_altivec_vrlw
6757 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6758 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6761 // t = vsplti c, result = vsldoi t, t, 1
6762 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6763 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6764 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6766 // t = vsplti c, result = vsldoi t, t, 2
6767 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6768 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6769 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6771 // t = vsplti c, result = vsldoi t, t, 3
6772 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6773 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6774 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6781 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6782 /// the specified operations to build the shuffle.
6783 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6784 SDValue RHS, SelectionDAG &DAG,
6786 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6787 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6788 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6791 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6803 if (OpNum == OP_COPY) {
6804 if (LHSID == (1*9+2)*9+3) return LHS;
6805 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6809 SDValue OpLHS, OpRHS;
6810 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6811 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6815 default: llvm_unreachable("Unknown i32 permute!");
6817 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6818 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6819 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6820 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6823 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6824 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6825 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6826 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6829 for (unsigned i = 0; i != 16; ++i)
6830 ShufIdxs[i] = (i&3)+0;
6833 for (unsigned i = 0; i != 16; ++i)
6834 ShufIdxs[i] = (i&3)+4;
6837 for (unsigned i = 0; i != 16; ++i)
6838 ShufIdxs[i] = (i&3)+8;
6841 for (unsigned i = 0; i != 16; ++i)
6842 ShufIdxs[i] = (i&3)+12;
6845 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6847 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6849 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6851 EVT VT = OpLHS.getValueType();
6852 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6853 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6854 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6855 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6858 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6859 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6860 /// return the code it can be lowered into. Worst case, it can always be
6861 /// lowered into a vperm.
6862 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6863 SelectionDAG &DAG) const {
6865 SDValue V1 = Op.getOperand(0);
6866 SDValue V2 = Op.getOperand(1);
6867 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6868 EVT VT = Op.getValueType();
6869 bool isLittleEndian = Subtarget.isLittleEndian();
6871 if (Subtarget.hasQPX()) {
6872 if (VT.getVectorNumElements() != 4)
6875 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6877 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6878 if (AlignIdx != -1) {
6879 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6880 DAG.getConstant(AlignIdx, MVT::i32));
6881 } else if (SVOp->isSplat()) {
6882 int SplatIdx = SVOp->getSplatIndex();
6883 if (SplatIdx >= 4) {
6888 // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6891 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6892 DAG.getConstant(SplatIdx, MVT::i32));
6895 // Lower this into a qvgpci/qvfperm pair.
6897 // Compute the qvgpci literal
6899 for (unsigned i = 0; i < 4; ++i) {
6900 int m = SVOp->getMaskElt(i);
6901 unsigned mm = m >= 0 ? (unsigned) m : i;
6902 idx |= mm << (3-i)*3;
6905 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6906 DAG.getConstant(idx, MVT::i32));
6907 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6910 // Cases that are handled by instructions that take permute immediates
6911 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6912 // selected by the instruction selector.
6913 if (V2.getOpcode() == ISD::UNDEF) {
6914 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6915 PPC::isSplatShuffleMask(SVOp, 2) ||
6916 PPC::isSplatShuffleMask(SVOp, 4) ||
6917 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6918 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6919 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6920 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6921 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6922 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6923 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6924 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6925 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6930 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6931 // and produce a fixed permutation. If any of these match, do not lower to
6933 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6934 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6935 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6936 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6937 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6938 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6939 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6940 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6941 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6942 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6945 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6946 // perfect shuffle table to emit an optimal matching sequence.
6947 ArrayRef<int> PermMask = SVOp->getMask();
6949 unsigned PFIndexes[4];
6950 bool isFourElementShuffle = true;
6951 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6952 unsigned EltNo = 8; // Start out undef.
6953 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6954 if (PermMask[i*4+j] < 0)
6955 continue; // Undef, ignore it.
6957 unsigned ByteSource = PermMask[i*4+j];
6958 if ((ByteSource & 3) != j) {
6959 isFourElementShuffle = false;
6964 EltNo = ByteSource/4;
6965 } else if (EltNo != ByteSource/4) {
6966 isFourElementShuffle = false;
6970 PFIndexes[i] = EltNo;
6973 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6974 // perfect shuffle vector to determine if it is cost effective to do this as
6975 // discrete instructions, or whether we should use a vperm.
6976 // For now, we skip this for little endian until such time as we have a
6977 // little-endian perfect shuffle table.
6978 if (isFourElementShuffle && !isLittleEndian) {
6979 // Compute the index in the perfect shuffle table.
6980 unsigned PFTableIndex =
6981 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6983 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6984 unsigned Cost = (PFEntry >> 30);
6986 // Determining when to avoid vperm is tricky. Many things affect the cost
6987 // of vperm, particularly how many times the perm mask needs to be computed.
6988 // For example, if the perm mask can be hoisted out of a loop or is already
6989 // used (perhaps because there are multiple permutes with the same shuffle
6990 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6991 // the loop requires an extra register.
6993 // As a compromise, we only emit discrete instructions if the shuffle can be
6994 // generated in 3 or fewer operations. When we have loop information
6995 // available, if this block is within a loop, we should avoid using vperm
6996 // for 3-operation perms and use a constant pool load instead.
6998 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7001 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7002 // vector that will get spilled to the constant pool.
7003 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7005 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7006 // that it is in input element units, not in bytes. Convert now.
7008 // For little endian, the order of the input vectors is reversed, and
7009 // the permutation mask is complemented with respect to 31. This is
7010 // necessary to produce proper semantics with the big-endian-biased vperm
7012 EVT EltVT = V1.getValueType().getVectorElementType();
7013 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7015 SmallVector<SDValue, 16> ResultMask;
7016 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7017 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7019 for (unsigned j = 0; j != BytesPerElement; ++j)
7021 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
7024 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
7028 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7031 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7034 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7038 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7039 /// altivec comparison. If it is, return true and fill in Opc/isDot with
7040 /// information about the intrinsic.
7041 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7042 bool &isDot, const PPCSubtarget &Subtarget) {
7043 unsigned IntrinsicID =
7044 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7047 switch (IntrinsicID) {
7048 default: return false;
7049 // Comparison predicates.
7050 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
7051 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7052 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
7053 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
7054 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7055 case Intrinsic::ppc_altivec_vcmpequd_p:
7056 if (Subtarget.hasP8Altivec()) {
7064 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7065 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7066 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7067 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7068 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7069 case Intrinsic::ppc_altivec_vcmpgtsd_p:
7070 if (Subtarget.hasP8Altivec()) {
7078 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7079 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7080 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7081 case Intrinsic::ppc_altivec_vcmpgtud_p:
7082 if (Subtarget.hasP8Altivec()) {
7091 // Normal Comparisons.
7092 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
7093 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
7094 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
7095 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
7096 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
7097 case Intrinsic::ppc_altivec_vcmpequd:
7098 if (Subtarget.hasP8Altivec()) {
7106 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
7107 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
7108 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
7109 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
7110 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
7111 case Intrinsic::ppc_altivec_vcmpgtsd:
7112 if (Subtarget.hasP8Altivec()) {
7120 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
7121 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
7122 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
7123 case Intrinsic::ppc_altivec_vcmpgtud:
7124 if (Subtarget.hasP8Altivec()) {
7136 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7137 /// lower, do it, otherwise return null.
7138 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7139 SelectionDAG &DAG) const {
7140 // If this is a lowered altivec predicate compare, CompareOpc is set to the
7141 // opcode number of the comparison.
7145 if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7146 return SDValue(); // Don't custom lower most intrinsics.
7148 // If this is a non-dot comparison, make the VCMP node and we are done.
7150 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7151 Op.getOperand(1), Op.getOperand(2),
7152 DAG.getConstant(CompareOpc, MVT::i32));
7153 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7156 // Create the PPCISD altivec 'dot' comparison node.
7158 Op.getOperand(2), // LHS
7159 Op.getOperand(3), // RHS
7160 DAG.getConstant(CompareOpc, MVT::i32)
7162 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7163 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7165 // Now that we have the comparison, emit a copy from the CR to a GPR.
7166 // This is flagged to the above dot comparison.
7167 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7168 DAG.getRegister(PPC::CR6, MVT::i32),
7169 CompNode.getValue(1));
7171 // Unpack the result based on how the target uses it.
7172 unsigned BitNo; // Bit # of CR6.
7173 bool InvertBit; // Invert result?
7174 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7175 default: // Can't happen, don't crash on invalid number though.
7176 case 0: // Return the value of the EQ bit of CR6.
7177 BitNo = 0; InvertBit = false;
7179 case 1: // Return the inverted value of the EQ bit of CR6.
7180 BitNo = 0; InvertBit = true;
7182 case 2: // Return the value of the LT bit of CR6.
7183 BitNo = 2; InvertBit = false;
7185 case 3: // Return the inverted value of the LT bit of CR6.
7186 BitNo = 2; InvertBit = true;
7190 // Shift the bit into the low position.
7191 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7192 DAG.getConstant(8-(3-BitNo), MVT::i32));
7194 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7195 DAG.getConstant(1, MVT::i32));
7197 // If we are supposed to, toggle the bit.
7199 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7200 DAG.getConstant(1, MVT::i32));
7204 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7205 SelectionDAG &DAG) const {
7207 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7208 // instructions), but for smaller types, we need to first extend up to v2i32
7209 // before doing going farther.
7210 if (Op.getValueType() == MVT::v2i64) {
7211 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7212 if (ExtVT != MVT::v2i32) {
7213 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7214 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7215 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7216 ExtVT.getVectorElementType(), 4)));
7217 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7218 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7219 DAG.getValueType(MVT::v2i32));
7228 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7229 SelectionDAG &DAG) const {
7231 // Create a stack slot that is 16-byte aligned.
7232 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7233 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7234 EVT PtrVT = getPointerTy();
7235 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7237 // Store the input value into Value#0 of the stack slot.
7238 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7239 Op.getOperand(0), FIdx, MachinePointerInfo(),
7242 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7243 false, false, false, 0);
7246 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7247 SelectionDAG &DAG) const {
7249 SDNode *N = Op.getNode();
7251 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7252 "Unknown extract_vector_elt type");
7254 SDValue Value = N->getOperand(0);
7256 // The first part of this is like the store lowering except that we don't
7257 // need to track the chain.
7259 // The values are now known to be -1 (false) or 1 (true). To convert this
7260 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7261 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7262 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7264 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7265 // understand how to form the extending load.
7266 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7267 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7268 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7270 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7272 // Now convert to an integer and store.
7273 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7274 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7277 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7278 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7279 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7280 EVT PtrVT = getPointerTy();
7281 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7283 SDValue StoreChain = DAG.getEntryNode();
7284 SmallVector<SDValue, 2> Ops;
7285 Ops.push_back(StoreChain);
7286 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7287 Ops.push_back(Value);
7288 Ops.push_back(FIdx);
7290 SmallVector<EVT, 2> ValueVTs;
7291 ValueVTs.push_back(MVT::Other); // chain
7292 SDVTList VTs = DAG.getVTList(ValueVTs);
7294 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7295 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7297 // Extract the value requested.
7298 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7299 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7300 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7302 SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7303 PtrInfo.getWithOffset(Offset),
7304 false, false, false, 0);
7306 if (!Subtarget.useCRBits())
7309 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7312 /// Lowering for QPX v4i1 loads
7313 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7314 SelectionDAG &DAG) const {
7316 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7317 SDValue LoadChain = LN->getChain();
7318 SDValue BasePtr = LN->getBasePtr();
7320 if (Op.getValueType() == MVT::v4f64 ||
7321 Op.getValueType() == MVT::v4f32) {
7322 EVT MemVT = LN->getMemoryVT();
7323 unsigned Alignment = LN->getAlignment();
7325 // If this load is properly aligned, then it is legal.
7326 if (Alignment >= MemVT.getStoreSize())
7329 EVT ScalarVT = Op.getValueType().getScalarType(),
7330 ScalarMemVT = MemVT.getScalarType();
7331 unsigned Stride = ScalarMemVT.getStoreSize();
7333 SmallVector<SDValue, 8> Vals, LoadChains;
7334 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7336 if (ScalarVT != ScalarMemVT)
7338 DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7340 LN->getPointerInfo().getWithOffset(Idx*Stride),
7341 ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7342 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7346 DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7347 LN->getPointerInfo().getWithOffset(Idx*Stride),
7348 LN->isVolatile(), LN->isNonTemporal(),
7349 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7352 if (Idx == 0 && LN->isIndexed()) {
7353 assert(LN->getAddressingMode() == ISD::PRE_INC &&
7354 "Unknown addressing mode on vector load");
7355 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7356 LN->getAddressingMode());
7359 Vals.push_back(Load);
7360 LoadChains.push_back(Load.getValue(1));
7362 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7363 DAG.getConstant(Stride, BasePtr.getValueType()));
7366 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7367 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7368 Op.getValueType(), Vals);
7370 if (LN->isIndexed()) {
7371 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7372 return DAG.getMergeValues(RetOps, dl);
7375 SDValue RetOps[] = { Value, TF };
7376 return DAG.getMergeValues(RetOps, dl);
7379 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7380 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7382 // To lower v4i1 from a byte array, we load the byte elements of the
7383 // vector and then reuse the BUILD_VECTOR logic.
7385 SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7386 for (unsigned i = 0; i < 4; ++i) {
7387 SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7388 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7390 VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7391 dl, MVT::i32, LoadChain, Idx,
7392 LN->getPointerInfo().getWithOffset(i),
7393 MVT::i8 /* memory type */,
7394 LN->isVolatile(), LN->isNonTemporal(),
7396 1 /* alignment */, LN->getAAInfo()));
7397 VectElmtChains.push_back(VectElmts[i].getValue(1));
7400 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7401 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7403 SDValue RVals[] = { Value, LoadChain };
7404 return DAG.getMergeValues(RVals, dl);
7407 /// Lowering for QPX v4i1 stores
7408 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7409 SelectionDAG &DAG) const {
7411 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7412 SDValue StoreChain = SN->getChain();
7413 SDValue BasePtr = SN->getBasePtr();
7414 SDValue Value = SN->getValue();
7416 if (Value.getValueType() == MVT::v4f64 ||
7417 Value.getValueType() == MVT::v4f32) {
7418 EVT MemVT = SN->getMemoryVT();
7419 unsigned Alignment = SN->getAlignment();
7421 // If this store is properly aligned, then it is legal.
7422 if (Alignment >= MemVT.getStoreSize())
7425 EVT ScalarVT = Value.getValueType().getScalarType(),
7426 ScalarMemVT = MemVT.getScalarType();
7427 unsigned Stride = ScalarMemVT.getStoreSize();
7429 SmallVector<SDValue, 8> Stores;
7430 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7432 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7433 DAG.getConstant(Idx, getVectorIdxTy()));
7435 if (ScalarVT != ScalarMemVT)
7437 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7438 SN->getPointerInfo().getWithOffset(Idx*Stride),
7439 ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7440 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7443 DAG.getStore(StoreChain, dl, Ex, BasePtr,
7444 SN->getPointerInfo().getWithOffset(Idx*Stride),
7445 SN->isVolatile(), SN->isNonTemporal(),
7446 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7448 if (Idx == 0 && SN->isIndexed()) {
7449 assert(SN->getAddressingMode() == ISD::PRE_INC &&
7450 "Unknown addressing mode on vector store");
7451 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7452 SN->getAddressingMode());
7455 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7456 DAG.getConstant(Stride, BasePtr.getValueType()));
7457 Stores.push_back(Store);
7460 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7462 if (SN->isIndexed()) {
7463 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7464 return DAG.getMergeValues(RetOps, dl);
7470 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7471 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7473 // The values are now known to be -1 (false) or 1 (true). To convert this
7474 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7475 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7476 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7478 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7479 // understand how to form the extending load.
7480 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7481 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7482 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7484 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7486 // Now convert to an integer and store.
7487 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7488 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7491 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7492 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7493 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7494 EVT PtrVT = getPointerTy();
7495 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7497 SmallVector<SDValue, 2> Ops;
7498 Ops.push_back(StoreChain);
7499 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7500 Ops.push_back(Value);
7501 Ops.push_back(FIdx);
7503 SmallVector<EVT, 2> ValueVTs;
7504 ValueVTs.push_back(MVT::Other); // chain
7505 SDVTList VTs = DAG.getVTList(ValueVTs);
7507 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7508 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7510 // Move data into the byte array.
7511 SmallVector<SDValue, 4> Loads, LoadChains;
7512 for (unsigned i = 0; i < 4; ++i) {
7513 unsigned Offset = 4*i;
7514 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7515 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7517 Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7518 PtrInfo.getWithOffset(Offset),
7519 false, false, false, 0));
7520 LoadChains.push_back(Loads[i].getValue(1));
7523 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7525 SmallVector<SDValue, 4> Stores;
7526 for (unsigned i = 0; i < 4; ++i) {
7527 SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7528 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7530 Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7531 SN->getPointerInfo().getWithOffset(i),
7532 MVT::i8 /* memory type */,
7533 SN->isNonTemporal(), SN->isVolatile(),
7534 1 /* alignment */, SN->getAAInfo()));
7537 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7542 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7544 if (Op.getValueType() == MVT::v4i32) {
7545 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7547 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
7548 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7550 SDValue RHSSwap = // = vrlw RHS, 16
7551 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7553 // Shrinkify inputs to v8i16.
7554 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7555 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7556 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7558 // Low parts multiplied together, generating 32-bit results (we ignore the
7560 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7561 LHS, RHS, DAG, dl, MVT::v4i32);
7563 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7564 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7565 // Shift the high parts up 16 bits.
7566 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7568 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7569 } else if (Op.getValueType() == MVT::v8i16) {
7570 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7572 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7574 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7575 LHS, RHS, Zero, DAG, dl);
7576 } else if (Op.getValueType() == MVT::v16i8) {
7577 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7578 bool isLittleEndian = Subtarget.isLittleEndian();
7580 // Multiply the even 8-bit parts, producing 16-bit sums.
7581 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7582 LHS, RHS, DAG, dl, MVT::v8i16);
7583 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7585 // Multiply the odd 8-bit parts, producing 16-bit sums.
7586 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7587 LHS, RHS, DAG, dl, MVT::v8i16);
7588 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7590 // Merge the results together. Because vmuleub and vmuloub are
7591 // instructions with a big-endian bias, we must reverse the
7592 // element numbering and reverse the meaning of "odd" and "even"
7593 // when generating little endian code.
7595 for (unsigned i = 0; i != 8; ++i) {
7596 if (isLittleEndian) {
7598 Ops[i*2+1] = 2*i+16;
7601 Ops[i*2+1] = 2*i+1+16;
7605 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7607 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7609 llvm_unreachable("Unknown mul to lower!");
7613 /// LowerOperation - Provide custom lowering hooks for some operations.
7615 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7616 switch (Op.getOpcode()) {
7617 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7618 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7619 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7620 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7621 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7622 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7623 case ISD::SETCC: return LowerSETCC(Op, DAG);
7624 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
7625 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
7627 return LowerVASTART(Op, DAG, Subtarget);
7630 return LowerVAARG(Op, DAG, Subtarget);
7633 return LowerVACOPY(Op, DAG, Subtarget);
7635 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
7636 case ISD::DYNAMIC_STACKALLOC:
7637 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7639 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
7640 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
7642 case ISD::LOAD: return LowerLOAD(Op, DAG);
7643 case ISD::STORE: return LowerSTORE(Op, DAG);
7644 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
7645 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7646 case ISD::FP_TO_UINT:
7647 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
7649 case ISD::UINT_TO_FP:
7650 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7651 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7653 // Lower 64-bit shifts.
7654 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
7655 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
7656 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
7658 // Vector-related lowering.
7659 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7660 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7661 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7662 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7663 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
7664 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7665 case ISD::MUL: return LowerMUL(Op, DAG);
7667 // For counter-based loop handling.
7668 case ISD::INTRINSIC_W_CHAIN: return SDValue();
7670 // Frame & Return address.
7671 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7672 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7676 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7677 SmallVectorImpl<SDValue>&Results,
7678 SelectionDAG &DAG) const {
7680 switch (N->getOpcode()) {
7682 llvm_unreachable("Do not know how to custom type legalize this operation!");
7683 case ISD::READCYCLECOUNTER: {
7684 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7685 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7687 Results.push_back(RTB);
7688 Results.push_back(RTB.getValue(1));
7689 Results.push_back(RTB.getValue(2));
7692 case ISD::INTRINSIC_W_CHAIN: {
7693 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7694 Intrinsic::ppc_is_decremented_ctr_nonzero)
7697 assert(N->getValueType(0) == MVT::i1 &&
7698 "Unexpected result type for CTR decrement intrinsic");
7699 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7700 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7701 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7704 Results.push_back(NewInt);
7705 Results.push_back(NewInt.getValue(1));
7709 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7712 EVT VT = N->getValueType(0);
7714 if (VT == MVT::i64) {
7715 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7717 Results.push_back(NewNode);
7718 Results.push_back(NewNode.getValue(1));
7722 case ISD::FP_ROUND_INREG: {
7723 assert(N->getValueType(0) == MVT::ppcf128);
7724 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7725 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7726 MVT::f64, N->getOperand(0),
7727 DAG.getIntPtrConstant(0));
7728 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7729 MVT::f64, N->getOperand(0),
7730 DAG.getIntPtrConstant(1));
7732 // Add the two halves of the long double in round-to-zero mode.
7733 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7735 // We know the low half is about to be thrown away, so just use something
7737 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7741 case ISD::FP_TO_SINT:
7742 // LowerFP_TO_INT() can only handle f32 and f64.
7743 if (N->getOperand(0).getValueType() == MVT::ppcf128)
7745 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7751 //===----------------------------------------------------------------------===//
7752 // Other Lowering Code
7753 //===----------------------------------------------------------------------===//
7755 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7756 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7757 Function *Func = Intrinsic::getDeclaration(M, Id);
7758 return Builder.CreateCall(Func);
7761 // The mappings for emitLeading/TrailingFence is taken from
7762 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7763 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7764 AtomicOrdering Ord, bool IsStore,
7765 bool IsLoad) const {
7766 if (Ord == SequentiallyConsistent)
7767 return callIntrinsic(Builder, Intrinsic::ppc_sync);
7768 else if (isAtLeastRelease(Ord))
7769 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7774 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7775 AtomicOrdering Ord, bool IsStore,
7776 bool IsLoad) const {
7777 if (IsLoad && isAtLeastAcquire(Ord))
7778 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7779 // FIXME: this is too conservative, a dependent branch + isync is enough.
7780 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7781 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7782 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7788 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7789 unsigned AtomicSize,
7790 unsigned BinOpcode) const {
7791 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7792 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7794 auto LoadMnemonic = PPC::LDARX;
7795 auto StoreMnemonic = PPC::STDCX;
7796 switch (AtomicSize) {
7798 llvm_unreachable("Unexpected size of atomic entity");
7800 LoadMnemonic = PPC::LBARX;
7801 StoreMnemonic = PPC::STBCX;
7802 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7805 LoadMnemonic = PPC::LHARX;
7806 StoreMnemonic = PPC::STHCX;
7807 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7810 LoadMnemonic = PPC::LWARX;
7811 StoreMnemonic = PPC::STWCX;
7814 LoadMnemonic = PPC::LDARX;
7815 StoreMnemonic = PPC::STDCX;
7819 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7820 MachineFunction *F = BB->getParent();
7821 MachineFunction::iterator It = BB;
7824 unsigned dest = MI->getOperand(0).getReg();
7825 unsigned ptrA = MI->getOperand(1).getReg();
7826 unsigned ptrB = MI->getOperand(2).getReg();
7827 unsigned incr = MI->getOperand(3).getReg();
7828 DebugLoc dl = MI->getDebugLoc();
7830 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7831 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7832 F->insert(It, loopMBB);
7833 F->insert(It, exitMBB);
7834 exitMBB->splice(exitMBB->begin(), BB,
7835 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7836 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7838 MachineRegisterInfo &RegInfo = F->getRegInfo();
7839 unsigned TmpReg = (!BinOpcode) ? incr :
7840 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7841 : &PPC::GPRCRegClass);
7845 // fallthrough --> loopMBB
7846 BB->addSuccessor(loopMBB);
7849 // l[wd]arx dest, ptr
7850 // add r0, dest, incr
7851 // st[wd]cx. r0, ptr
7853 // fallthrough --> exitMBB
7855 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7856 .addReg(ptrA).addReg(ptrB);
7858 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7859 BuildMI(BB, dl, TII->get(StoreMnemonic))
7860 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7861 BuildMI(BB, dl, TII->get(PPC::BCC))
7862 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7863 BB->addSuccessor(loopMBB);
7864 BB->addSuccessor(exitMBB);
7873 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7874 MachineBasicBlock *BB,
7875 bool is8bit, // operation
7876 unsigned BinOpcode) const {
7877 // If we support part-word atomic mnemonics, just use them
7878 if (Subtarget.hasPartwordAtomics())
7879 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
7881 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7882 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7883 // In 64 bit mode we have to use 64 bits for addresses, even though the
7884 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
7885 // registers without caring whether they're 32 or 64, but here we're
7886 // doing actual arithmetic on the addresses.
7887 bool is64bit = Subtarget.isPPC64();
7888 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7890 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7891 MachineFunction *F = BB->getParent();
7892 MachineFunction::iterator It = BB;
7895 unsigned dest = MI->getOperand(0).getReg();
7896 unsigned ptrA = MI->getOperand(1).getReg();
7897 unsigned ptrB = MI->getOperand(2).getReg();
7898 unsigned incr = MI->getOperand(3).getReg();
7899 DebugLoc dl = MI->getDebugLoc();
7901 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7902 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7903 F->insert(It, loopMBB);
7904 F->insert(It, exitMBB);
7905 exitMBB->splice(exitMBB->begin(), BB,
7906 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7907 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7909 MachineRegisterInfo &RegInfo = F->getRegInfo();
7910 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7911 : &PPC::GPRCRegClass;
7912 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7913 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7914 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7915 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7916 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7917 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7918 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7919 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7920 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7921 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7922 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7924 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7928 // fallthrough --> loopMBB
7929 BB->addSuccessor(loopMBB);
7931 // The 4-byte load must be aligned, while a char or short may be
7932 // anywhere in the word. Hence all this nasty bookkeeping code.
7933 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7934 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7935 // xori shift, shift1, 24 [16]
7936 // rlwinm ptr, ptr1, 0, 0, 29
7937 // slw incr2, incr, shift
7938 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7939 // slw mask, mask2, shift
7941 // lwarx tmpDest, ptr
7942 // add tmp, tmpDest, incr2
7943 // andc tmp2, tmpDest, mask
7944 // and tmp3, tmp, mask
7945 // or tmp4, tmp3, tmp2
7948 // fallthrough --> exitMBB
7949 // srw dest, tmpDest, shift
7950 if (ptrA != ZeroReg) {
7951 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7952 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7953 .addReg(ptrA).addReg(ptrB);
7957 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7958 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7959 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7960 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7962 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7963 .addReg(Ptr1Reg).addImm(0).addImm(61);
7965 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7966 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7967 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7968 .addReg(incr).addReg(ShiftReg);
7970 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7972 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7973 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7975 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7976 .addReg(Mask2Reg).addReg(ShiftReg);
7979 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7980 .addReg(ZeroReg).addReg(PtrReg);
7982 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7983 .addReg(Incr2Reg).addReg(TmpDestReg);
7984 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7985 .addReg(TmpDestReg).addReg(MaskReg);
7986 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7987 .addReg(TmpReg).addReg(MaskReg);
7988 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7989 .addReg(Tmp3Reg).addReg(Tmp2Reg);
7990 BuildMI(BB, dl, TII->get(PPC::STWCX))
7991 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7992 BuildMI(BB, dl, TII->get(PPC::BCC))
7993 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7994 BB->addSuccessor(loopMBB);
7995 BB->addSuccessor(exitMBB);
8000 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8005 llvm::MachineBasicBlock*
8006 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8007 MachineBasicBlock *MBB) const {
8008 DebugLoc DL = MI->getDebugLoc();
8009 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8011 MachineFunction *MF = MBB->getParent();
8012 MachineRegisterInfo &MRI = MF->getRegInfo();
8014 const BasicBlock *BB = MBB->getBasicBlock();
8015 MachineFunction::iterator I = MBB;
8019 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8020 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8022 unsigned DstReg = MI->getOperand(0).getReg();
8023 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8024 assert(RC->hasType(MVT::i32) && "Invalid destination!");
8025 unsigned mainDstReg = MRI.createVirtualRegister(RC);
8026 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8028 MVT PVT = getPointerTy();
8029 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8030 "Invalid Pointer Size!");
8031 // For v = setjmp(buf), we generate
8034 // SjLjSetup mainMBB
8040 // buf[LabelOffset] = LR
8044 // v = phi(main, restore)
8047 MachineBasicBlock *thisMBB = MBB;
8048 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8049 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8050 MF->insert(I, mainMBB);
8051 MF->insert(I, sinkMBB);
8053 MachineInstrBuilder MIB;
8055 // Transfer the remainder of BB and its successor edges to sinkMBB.
8056 sinkMBB->splice(sinkMBB->begin(), MBB,
8057 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8058 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8060 // Note that the structure of the jmp_buf used here is not compatible
8061 // with that used by libc, and is not designed to be. Specifically, it
8062 // stores only those 'reserved' registers that LLVM does not otherwise
8063 // understand how to spill. Also, by convention, by the time this
8064 // intrinsic is called, Clang has already stored the frame address in the
8065 // first slot of the buffer and stack address in the third. Following the
8066 // X86 target code, we'll store the jump address in the second slot. We also
8067 // need to save the TOC pointer (R2) to handle jumps between shared
8068 // libraries, and that will be stored in the fourth slot. The thread
8069 // identifier (R13) is not affected.
8072 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8073 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8074 const int64_t BPOffset = 4 * PVT.getStoreSize();
8076 // Prepare IP either in reg.
8077 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8078 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8079 unsigned BufReg = MI->getOperand(1).getReg();
8081 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8082 setUsesTOCBasePtr(*MBB->getParent());
8083 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8087 MIB.setMemRefs(MMOBegin, MMOEnd);
8090 // Naked functions never have a base pointer, and so we use r1. For all
8091 // other functions, this decision must be delayed until during PEI.
8093 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8094 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8096 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8098 MIB = BuildMI(*thisMBB, MI, DL,
8099 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8103 MIB.setMemRefs(MMOBegin, MMOEnd);
8106 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8107 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8108 MIB.addRegMask(TRI->getNoPreservedMask());
8110 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8112 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8114 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8116 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8117 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8122 BuildMI(mainMBB, DL,
8123 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8126 if (Subtarget.isPPC64()) {
8127 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8129 .addImm(LabelOffset)
8132 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8134 .addImm(LabelOffset)
8138 MIB.setMemRefs(MMOBegin, MMOEnd);
8140 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8141 mainMBB->addSuccessor(sinkMBB);
8144 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8145 TII->get(PPC::PHI), DstReg)
8146 .addReg(mainDstReg).addMBB(mainMBB)
8147 .addReg(restoreDstReg).addMBB(thisMBB);
8149 MI->eraseFromParent();
8154 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8155 MachineBasicBlock *MBB) const {
8156 DebugLoc DL = MI->getDebugLoc();
8157 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8159 MachineFunction *MF = MBB->getParent();
8160 MachineRegisterInfo &MRI = MF->getRegInfo();
8163 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8164 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8166 MVT PVT = getPointerTy();
8167 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8168 "Invalid Pointer Size!");
8170 const TargetRegisterClass *RC =
8171 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8172 unsigned Tmp = MRI.createVirtualRegister(RC);
8173 // Since FP is only updated here but NOT referenced, it's treated as GPR.
8174 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8175 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8179 : (Subtarget.isSVR4ABI() &&
8180 MF->getTarget().getRelocationModel() == Reloc::PIC_
8184 MachineInstrBuilder MIB;
8186 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8187 const int64_t SPOffset = 2 * PVT.getStoreSize();
8188 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8189 const int64_t BPOffset = 4 * PVT.getStoreSize();
8191 unsigned BufReg = MI->getOperand(0).getReg();
8193 // Reload FP (the jumped-to function may not have had a
8194 // frame pointer, and if so, then its r31 will be restored
8196 if (PVT == MVT::i64) {
8197 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8201 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8205 MIB.setMemRefs(MMOBegin, MMOEnd);
8208 if (PVT == MVT::i64) {
8209 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8210 .addImm(LabelOffset)
8213 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8214 .addImm(LabelOffset)
8217 MIB.setMemRefs(MMOBegin, MMOEnd);
8220 if (PVT == MVT::i64) {
8221 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8225 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8229 MIB.setMemRefs(MMOBegin, MMOEnd);
8232 if (PVT == MVT::i64) {
8233 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8237 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8241 MIB.setMemRefs(MMOBegin, MMOEnd);
8244 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8245 setUsesTOCBasePtr(*MBB->getParent());
8246 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8250 MIB.setMemRefs(MMOBegin, MMOEnd);
8254 BuildMI(*MBB, MI, DL,
8255 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8256 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8258 MI->eraseFromParent();
8263 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8264 MachineBasicBlock *BB) const {
8265 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8266 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8267 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8268 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8269 // Call lowering should have added an r2 operand to indicate a dependence
8270 // on the TOC base pointer value. It can't however, because there is no
8271 // way to mark the dependence as implicit there, and so the stackmap code
8272 // will confuse it with a regular operand. Instead, add the dependence
8274 setUsesTOCBasePtr(*BB->getParent());
8275 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8278 return emitPatchPoint(MI, BB);
8281 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8282 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8283 return emitEHSjLjSetJmp(MI, BB);
8284 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8285 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8286 return emitEHSjLjLongJmp(MI, BB);
8289 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8291 // To "insert" these instructions we actually have to insert their
8292 // control-flow patterns.
8293 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8294 MachineFunction::iterator It = BB;
8297 MachineFunction *F = BB->getParent();
8299 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8300 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8301 MI->getOpcode() == PPC::SELECT_I4 ||
8302 MI->getOpcode() == PPC::SELECT_I8)) {
8303 SmallVector<MachineOperand, 2> Cond;
8304 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8305 MI->getOpcode() == PPC::SELECT_CC_I8)
8306 Cond.push_back(MI->getOperand(4));
8308 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8309 Cond.push_back(MI->getOperand(1));
8311 DebugLoc dl = MI->getDebugLoc();
8312 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8313 Cond, MI->getOperand(2).getReg(),
8314 MI->getOperand(3).getReg());
8315 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8316 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8317 MI->getOpcode() == PPC::SELECT_CC_F4 ||
8318 MI->getOpcode() == PPC::SELECT_CC_F8 ||
8319 MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8320 MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8321 MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8322 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8323 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8324 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8325 MI->getOpcode() == PPC::SELECT_I4 ||
8326 MI->getOpcode() == PPC::SELECT_I8 ||
8327 MI->getOpcode() == PPC::SELECT_F4 ||
8328 MI->getOpcode() == PPC::SELECT_F8 ||
8329 MI->getOpcode() == PPC::SELECT_QFRC ||
8330 MI->getOpcode() == PPC::SELECT_QSRC ||
8331 MI->getOpcode() == PPC::SELECT_QBRC ||
8332 MI->getOpcode() == PPC::SELECT_VRRC ||
8333 MI->getOpcode() == PPC::SELECT_VSFRC ||
8334 MI->getOpcode() == PPC::SELECT_VSRC) {
8335 // The incoming instruction knows the destination vreg to set, the
8336 // condition code register to branch on, the true/false values to
8337 // select between, and a branch opcode to use.
8342 // cmpTY ccX, r1, r2
8344 // fallthrough --> copy0MBB
8345 MachineBasicBlock *thisMBB = BB;
8346 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8347 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8348 DebugLoc dl = MI->getDebugLoc();
8349 F->insert(It, copy0MBB);
8350 F->insert(It, sinkMBB);
8352 // Transfer the remainder of BB and its successor edges to sinkMBB.
8353 sinkMBB->splice(sinkMBB->begin(), BB,
8354 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8355 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8357 // Next, add the true and fallthrough blocks as its successors.
8358 BB->addSuccessor(copy0MBB);
8359 BB->addSuccessor(sinkMBB);
8361 if (MI->getOpcode() == PPC::SELECT_I4 ||
8362 MI->getOpcode() == PPC::SELECT_I8 ||
8363 MI->getOpcode() == PPC::SELECT_F4 ||
8364 MI->getOpcode() == PPC::SELECT_F8 ||
8365 MI->getOpcode() == PPC::SELECT_QFRC ||
8366 MI->getOpcode() == PPC::SELECT_QSRC ||
8367 MI->getOpcode() == PPC::SELECT_QBRC ||
8368 MI->getOpcode() == PPC::SELECT_VRRC ||
8369 MI->getOpcode() == PPC::SELECT_VSFRC ||
8370 MI->getOpcode() == PPC::SELECT_VSRC) {
8371 BuildMI(BB, dl, TII->get(PPC::BC))
8372 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8374 unsigned SelectPred = MI->getOperand(4).getImm();
8375 BuildMI(BB, dl, TII->get(PPC::BCC))
8376 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8380 // %FalseValue = ...
8381 // # fallthrough to sinkMBB
8384 // Update machine-CFG edges
8385 BB->addSuccessor(sinkMBB);
8388 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8391 BuildMI(*BB, BB->begin(), dl,
8392 TII->get(PPC::PHI), MI->getOperand(0).getReg())
8393 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8394 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8395 } else if (MI->getOpcode() == PPC::ReadTB) {
8396 // To read the 64-bit time-base register on a 32-bit target, we read the
8397 // two halves. Should the counter have wrapped while it was being read, we
8398 // need to try again.
8401 // mfspr Rx,TBU # load from TBU
8402 // mfspr Ry,TB # load from TB
8403 // mfspr Rz,TBU # load from TBU
8404 // cmpw crX,Rx,Rz # check if ‘old’=’new’
8405 // bne readLoop # branch if they're not equal
8408 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8409 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8410 DebugLoc dl = MI->getDebugLoc();
8411 F->insert(It, readMBB);
8412 F->insert(It, sinkMBB);
8414 // Transfer the remainder of BB and its successor edges to sinkMBB.
8415 sinkMBB->splice(sinkMBB->begin(), BB,
8416 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8417 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8419 BB->addSuccessor(readMBB);
8422 MachineRegisterInfo &RegInfo = F->getRegInfo();
8423 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8424 unsigned LoReg = MI->getOperand(0).getReg();
8425 unsigned HiReg = MI->getOperand(1).getReg();
8427 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8428 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8429 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8431 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8433 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8434 .addReg(HiReg).addReg(ReadAgainReg);
8435 BuildMI(BB, dl, TII->get(PPC::BCC))
8436 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8438 BB->addSuccessor(readMBB);
8439 BB->addSuccessor(sinkMBB);
8441 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8442 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8443 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8444 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8445 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8446 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8447 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8448 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8450 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8451 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8452 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8453 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8454 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8455 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8456 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8457 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8459 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8460 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8461 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8462 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8463 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8464 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8465 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8466 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8468 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8469 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8470 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8471 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8472 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8473 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8474 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8475 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8477 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8478 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8479 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8480 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8481 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8482 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8483 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8484 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8486 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8487 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8488 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8489 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8490 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8491 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8492 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8493 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8495 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8496 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8497 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8498 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8499 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8500 BB = EmitAtomicBinary(MI, BB, 4, 0);
8501 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8502 BB = EmitAtomicBinary(MI, BB, 8, 0);
8504 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8505 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8506 (Subtarget.hasPartwordAtomics() &&
8507 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8508 (Subtarget.hasPartwordAtomics() &&
8509 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8510 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8512 auto LoadMnemonic = PPC::LDARX;
8513 auto StoreMnemonic = PPC::STDCX;
8514 switch(MI->getOpcode()) {
8516 llvm_unreachable("Compare and swap of unknown size");
8517 case PPC::ATOMIC_CMP_SWAP_I8:
8518 LoadMnemonic = PPC::LBARX;
8519 StoreMnemonic = PPC::STBCX;
8520 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8522 case PPC::ATOMIC_CMP_SWAP_I16:
8523 LoadMnemonic = PPC::LHARX;
8524 StoreMnemonic = PPC::STHCX;
8525 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8527 case PPC::ATOMIC_CMP_SWAP_I32:
8528 LoadMnemonic = PPC::LWARX;
8529 StoreMnemonic = PPC::STWCX;
8531 case PPC::ATOMIC_CMP_SWAP_I64:
8532 LoadMnemonic = PPC::LDARX;
8533 StoreMnemonic = PPC::STDCX;
8536 unsigned dest = MI->getOperand(0).getReg();
8537 unsigned ptrA = MI->getOperand(1).getReg();
8538 unsigned ptrB = MI->getOperand(2).getReg();
8539 unsigned oldval = MI->getOperand(3).getReg();
8540 unsigned newval = MI->getOperand(4).getReg();
8541 DebugLoc dl = MI->getDebugLoc();
8543 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8544 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8545 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8546 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8547 F->insert(It, loop1MBB);
8548 F->insert(It, loop2MBB);
8549 F->insert(It, midMBB);
8550 F->insert(It, exitMBB);
8551 exitMBB->splice(exitMBB->begin(), BB,
8552 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8553 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8557 // fallthrough --> loopMBB
8558 BB->addSuccessor(loop1MBB);
8561 // l[bhwd]arx dest, ptr
8562 // cmp[wd] dest, oldval
8565 // st[bhwd]cx. newval, ptr
8569 // st[bhwd]cx. dest, ptr
8572 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8573 .addReg(ptrA).addReg(ptrB);
8574 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8575 .addReg(oldval).addReg(dest);
8576 BuildMI(BB, dl, TII->get(PPC::BCC))
8577 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8578 BB->addSuccessor(loop2MBB);
8579 BB->addSuccessor(midMBB);
8582 BuildMI(BB, dl, TII->get(StoreMnemonic))
8583 .addReg(newval).addReg(ptrA).addReg(ptrB);
8584 BuildMI(BB, dl, TII->get(PPC::BCC))
8585 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8586 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8587 BB->addSuccessor(loop1MBB);
8588 BB->addSuccessor(exitMBB);
8591 BuildMI(BB, dl, TII->get(StoreMnemonic))
8592 .addReg(dest).addReg(ptrA).addReg(ptrB);
8593 BB->addSuccessor(exitMBB);
8598 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8599 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8600 // We must use 64-bit registers for addresses when targeting 64-bit,
8601 // since we're actually doing arithmetic on them. Other registers
8603 bool is64bit = Subtarget.isPPC64();
8604 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8606 unsigned dest = MI->getOperand(0).getReg();
8607 unsigned ptrA = MI->getOperand(1).getReg();
8608 unsigned ptrB = MI->getOperand(2).getReg();
8609 unsigned oldval = MI->getOperand(3).getReg();
8610 unsigned newval = MI->getOperand(4).getReg();
8611 DebugLoc dl = MI->getDebugLoc();
8613 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8614 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8615 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8616 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8617 F->insert(It, loop1MBB);
8618 F->insert(It, loop2MBB);
8619 F->insert(It, midMBB);
8620 F->insert(It, exitMBB);
8621 exitMBB->splice(exitMBB->begin(), BB,
8622 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8623 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8625 MachineRegisterInfo &RegInfo = F->getRegInfo();
8626 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8627 : &PPC::GPRCRegClass;
8628 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8629 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8630 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8631 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8632 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8633 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8634 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8635 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8636 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8637 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8638 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8639 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8640 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8642 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8643 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8646 // fallthrough --> loopMBB
8647 BB->addSuccessor(loop1MBB);
8649 // The 4-byte load must be aligned, while a char or short may be
8650 // anywhere in the word. Hence all this nasty bookkeeping code.
8651 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8652 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8653 // xori shift, shift1, 24 [16]
8654 // rlwinm ptr, ptr1, 0, 0, 29
8655 // slw newval2, newval, shift
8656 // slw oldval2, oldval,shift
8657 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8658 // slw mask, mask2, shift
8659 // and newval3, newval2, mask
8660 // and oldval3, oldval2, mask
8662 // lwarx tmpDest, ptr
8663 // and tmp, tmpDest, mask
8664 // cmpw tmp, oldval3
8667 // andc tmp2, tmpDest, mask
8668 // or tmp4, tmp2, newval3
8673 // stwcx. tmpDest, ptr
8675 // srw dest, tmpDest, shift
8676 if (ptrA != ZeroReg) {
8677 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8678 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8679 .addReg(ptrA).addReg(ptrB);
8683 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8684 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8685 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8686 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8688 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8689 .addReg(Ptr1Reg).addImm(0).addImm(61);
8691 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8692 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8693 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8694 .addReg(newval).addReg(ShiftReg);
8695 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8696 .addReg(oldval).addReg(ShiftReg);
8698 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8700 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8701 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8702 .addReg(Mask3Reg).addImm(65535);
8704 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8705 .addReg(Mask2Reg).addReg(ShiftReg);
8706 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8707 .addReg(NewVal2Reg).addReg(MaskReg);
8708 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8709 .addReg(OldVal2Reg).addReg(MaskReg);
8712 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8713 .addReg(ZeroReg).addReg(PtrReg);
8714 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8715 .addReg(TmpDestReg).addReg(MaskReg);
8716 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8717 .addReg(TmpReg).addReg(OldVal3Reg);
8718 BuildMI(BB, dl, TII->get(PPC::BCC))
8719 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8720 BB->addSuccessor(loop2MBB);
8721 BB->addSuccessor(midMBB);
8724 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8725 .addReg(TmpDestReg).addReg(MaskReg);
8726 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8727 .addReg(Tmp2Reg).addReg(NewVal3Reg);
8728 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8729 .addReg(ZeroReg).addReg(PtrReg);
8730 BuildMI(BB, dl, TII->get(PPC::BCC))
8731 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8732 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8733 BB->addSuccessor(loop1MBB);
8734 BB->addSuccessor(exitMBB);
8737 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8738 .addReg(ZeroReg).addReg(PtrReg);
8739 BB->addSuccessor(exitMBB);
8744 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8746 } else if (MI->getOpcode() == PPC::FADDrtz) {
8747 // This pseudo performs an FADD with rounding mode temporarily forced
8748 // to round-to-zero. We emit this via custom inserter since the FPSCR
8749 // is not modeled at the SelectionDAG level.
8750 unsigned Dest = MI->getOperand(0).getReg();
8751 unsigned Src1 = MI->getOperand(1).getReg();
8752 unsigned Src2 = MI->getOperand(2).getReg();
8753 DebugLoc dl = MI->getDebugLoc();
8755 MachineRegisterInfo &RegInfo = F->getRegInfo();
8756 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8758 // Save FPSCR value.
8759 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8761 // Set rounding mode to round-to-zero.
8762 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8763 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8765 // Perform addition.
8766 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8768 // Restore FPSCR value.
8769 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8770 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8771 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8772 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8773 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8774 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8775 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8776 PPC::ANDIo8 : PPC::ANDIo;
8777 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8778 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8780 MachineRegisterInfo &RegInfo = F->getRegInfo();
8781 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8782 &PPC::GPRCRegClass :
8783 &PPC::G8RCRegClass);
8785 DebugLoc dl = MI->getDebugLoc();
8786 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8787 .addReg(MI->getOperand(1).getReg()).addImm(1);
8788 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8789 MI->getOperand(0).getReg())
8790 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8792 llvm_unreachable("Unexpected instr type to insert");
8795 MI->eraseFromParent(); // The pseudo instruction is gone now.
8799 //===----------------------------------------------------------------------===//
8800 // Target Optimization Hooks
8801 //===----------------------------------------------------------------------===//
8803 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8804 DAGCombinerInfo &DCI,
8805 unsigned &RefinementSteps,
8806 bool &UseOneConstNR) const {
8807 EVT VT = Operand.getValueType();
8808 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8809 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8810 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8811 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8812 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8813 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8814 // Convergence is quadratic, so we essentially double the number of digits
8815 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8816 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8817 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8818 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8819 if (VT.getScalarType() == MVT::f64)
8821 UseOneConstNR = true;
8822 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8827 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8828 DAGCombinerInfo &DCI,
8829 unsigned &RefinementSteps) const {
8830 EVT VT = Operand.getValueType();
8831 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8832 (VT == MVT::f64 && Subtarget.hasFRE()) ||
8833 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8834 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8835 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8836 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8837 // Convergence is quadratic, so we essentially double the number of digits
8838 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8839 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8840 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8841 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8842 if (VT.getScalarType() == MVT::f64)
8844 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8849 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8850 // Note: This functionality is used only when unsafe-fp-math is enabled, and
8851 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8852 // enabled for division), this functionality is redundant with the default
8853 // combiner logic (once the division -> reciprocal/multiply transformation
8854 // has taken place). As a result, this matters more for older cores than for
8857 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8858 // reciprocal if there are two or more FDIVs (for embedded cores with only
8859 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8860 switch (Subtarget.getDarwinDirective()) {
8862 return NumUsers > 2;
8865 case PPC::DIR_E500mc:
8866 case PPC::DIR_E5500:
8867 return NumUsers > 1;
8871 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8872 unsigned Bytes, int Dist,
8873 SelectionDAG &DAG) {
8874 if (VT.getSizeInBits() / 8 != Bytes)
8877 SDValue BaseLoc = Base->getBasePtr();
8878 if (Loc.getOpcode() == ISD::FrameIndex) {
8879 if (BaseLoc.getOpcode() != ISD::FrameIndex)
8881 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8882 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
8883 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8884 int FS = MFI->getObjectSize(FI);
8885 int BFS = MFI->getObjectSize(BFI);
8886 if (FS != BFS || FS != (int)Bytes) return false;
8887 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8891 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8892 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8895 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8896 const GlobalValue *GV1 = nullptr;
8897 const GlobalValue *GV2 = nullptr;
8898 int64_t Offset1 = 0;
8899 int64_t Offset2 = 0;
8900 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8901 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8902 if (isGA1 && isGA2 && GV1 == GV2)
8903 return Offset1 == (Offset2 + Dist*Bytes);
8907 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8908 // not enforce equality of the chain operands.
8909 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8910 unsigned Bytes, int Dist,
8911 SelectionDAG &DAG) {
8912 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8913 EVT VT = LS->getMemoryVT();
8914 SDValue Loc = LS->getBasePtr();
8915 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8918 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8920 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8921 default: return false;
8922 case Intrinsic::ppc_qpx_qvlfd:
8923 case Intrinsic::ppc_qpx_qvlfda:
8926 case Intrinsic::ppc_qpx_qvlfs:
8927 case Intrinsic::ppc_qpx_qvlfsa:
8930 case Intrinsic::ppc_qpx_qvlfcd:
8931 case Intrinsic::ppc_qpx_qvlfcda:
8934 case Intrinsic::ppc_qpx_qvlfcs:
8935 case Intrinsic::ppc_qpx_qvlfcsa:
8938 case Intrinsic::ppc_qpx_qvlfiwa:
8939 case Intrinsic::ppc_qpx_qvlfiwz:
8940 case Intrinsic::ppc_altivec_lvx:
8941 case Intrinsic::ppc_altivec_lvxl:
8942 case Intrinsic::ppc_vsx_lxvw4x:
8945 case Intrinsic::ppc_vsx_lxvd2x:
8948 case Intrinsic::ppc_altivec_lvebx:
8951 case Intrinsic::ppc_altivec_lvehx:
8954 case Intrinsic::ppc_altivec_lvewx:
8959 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8962 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8964 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8965 default: return false;
8966 case Intrinsic::ppc_qpx_qvstfd:
8967 case Intrinsic::ppc_qpx_qvstfda:
8970 case Intrinsic::ppc_qpx_qvstfs:
8971 case Intrinsic::ppc_qpx_qvstfsa:
8974 case Intrinsic::ppc_qpx_qvstfcd:
8975 case Intrinsic::ppc_qpx_qvstfcda:
8978 case Intrinsic::ppc_qpx_qvstfcs:
8979 case Intrinsic::ppc_qpx_qvstfcsa:
8982 case Intrinsic::ppc_qpx_qvstfiw:
8983 case Intrinsic::ppc_qpx_qvstfiwa:
8984 case Intrinsic::ppc_altivec_stvx:
8985 case Intrinsic::ppc_altivec_stvxl:
8986 case Intrinsic::ppc_vsx_stxvw4x:
8989 case Intrinsic::ppc_vsx_stxvd2x:
8992 case Intrinsic::ppc_altivec_stvebx:
8995 case Intrinsic::ppc_altivec_stvehx:
8998 case Intrinsic::ppc_altivec_stvewx:
9003 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9009 // Return true is there is a nearyby consecutive load to the one provided
9010 // (regardless of alignment). We search up and down the chain, looking though
9011 // token factors and other loads (but nothing else). As a result, a true result
9012 // indicates that it is safe to create a new consecutive load adjacent to the
9014 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9015 SDValue Chain = LD->getChain();
9016 EVT VT = LD->getMemoryVT();
9018 SmallSet<SDNode *, 16> LoadRoots;
9019 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9020 SmallSet<SDNode *, 16> Visited;
9022 // First, search up the chain, branching to follow all token-factor operands.
9023 // If we find a consecutive load, then we're done, otherwise, record all
9024 // nodes just above the top-level loads and token factors.
9025 while (!Queue.empty()) {
9026 SDNode *ChainNext = Queue.pop_back_val();
9027 if (!Visited.insert(ChainNext).second)
9030 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9031 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9034 if (!Visited.count(ChainLD->getChain().getNode()))
9035 Queue.push_back(ChainLD->getChain().getNode());
9036 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9037 for (const SDUse &O : ChainNext->ops())
9038 if (!Visited.count(O.getNode()))
9039 Queue.push_back(O.getNode());
9041 LoadRoots.insert(ChainNext);
9044 // Second, search down the chain, starting from the top-level nodes recorded
9045 // in the first phase. These top-level nodes are the nodes just above all
9046 // loads and token factors. Starting with their uses, recursively look though
9047 // all loads (just the chain uses) and token factors to find a consecutive
9052 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9053 IE = LoadRoots.end(); I != IE; ++I) {
9054 Queue.push_back(*I);
9056 while (!Queue.empty()) {
9057 SDNode *LoadRoot = Queue.pop_back_val();
9058 if (!Visited.insert(LoadRoot).second)
9061 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9062 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9065 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9066 UE = LoadRoot->use_end(); UI != UE; ++UI)
9067 if (((isa<MemSDNode>(*UI) &&
9068 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9069 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9070 Queue.push_back(*UI);
9077 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9078 DAGCombinerInfo &DCI) const {
9079 SelectionDAG &DAG = DCI.DAG;
9082 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9083 // If we're tracking CR bits, we need to be careful that we don't have:
9084 // trunc(binary-ops(zext(x), zext(y)))
9086 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9087 // such that we're unnecessarily moving things into GPRs when it would be
9088 // better to keep them in CR bits.
9090 // Note that trunc here can be an actual i1 trunc, or can be the effective
9091 // truncation that comes from a setcc or select_cc.
9092 if (N->getOpcode() == ISD::TRUNCATE &&
9093 N->getValueType(0) != MVT::i1)
9096 if (N->getOperand(0).getValueType() != MVT::i32 &&
9097 N->getOperand(0).getValueType() != MVT::i64)
9100 if (N->getOpcode() == ISD::SETCC ||
9101 N->getOpcode() == ISD::SELECT_CC) {
9102 // If we're looking at a comparison, then we need to make sure that the
9103 // high bits (all except for the first) don't matter the result.
9105 cast<CondCodeSDNode>(N->getOperand(
9106 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9107 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9109 if (ISD::isSignedIntSetCC(CC)) {
9110 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9111 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9113 } else if (ISD::isUnsignedIntSetCC(CC)) {
9114 if (!DAG.MaskedValueIsZero(N->getOperand(0),
9115 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9116 !DAG.MaskedValueIsZero(N->getOperand(1),
9117 APInt::getHighBitsSet(OpBits, OpBits-1)))
9120 // This is neither a signed nor an unsigned comparison, just make sure
9121 // that the high bits are equal.
9122 APInt Op1Zero, Op1One;
9123 APInt Op2Zero, Op2One;
9124 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9125 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9127 // We don't really care about what is known about the first bit (if
9128 // anything), so clear it in all masks prior to comparing them.
9129 Op1Zero.clearBit(0); Op1One.clearBit(0);
9130 Op2Zero.clearBit(0); Op2One.clearBit(0);
9132 if (Op1Zero != Op2Zero || Op1One != Op2One)
9137 // We now know that the higher-order bits are irrelevant, we just need to
9138 // make sure that all of the intermediate operations are bit operations, and
9139 // all inputs are extensions.
9140 if (N->getOperand(0).getOpcode() != ISD::AND &&
9141 N->getOperand(0).getOpcode() != ISD::OR &&
9142 N->getOperand(0).getOpcode() != ISD::XOR &&
9143 N->getOperand(0).getOpcode() != ISD::SELECT &&
9144 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9145 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9146 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9147 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9148 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9151 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9152 N->getOperand(1).getOpcode() != ISD::AND &&
9153 N->getOperand(1).getOpcode() != ISD::OR &&
9154 N->getOperand(1).getOpcode() != ISD::XOR &&
9155 N->getOperand(1).getOpcode() != ISD::SELECT &&
9156 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9157 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9158 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9159 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9160 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9163 SmallVector<SDValue, 4> Inputs;
9164 SmallVector<SDValue, 8> BinOps, PromOps;
9165 SmallPtrSet<SDNode *, 16> Visited;
9167 for (unsigned i = 0; i < 2; ++i) {
9168 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9169 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9170 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9171 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9172 isa<ConstantSDNode>(N->getOperand(i)))
9173 Inputs.push_back(N->getOperand(i));
9175 BinOps.push_back(N->getOperand(i));
9177 if (N->getOpcode() == ISD::TRUNCATE)
9181 // Visit all inputs, collect all binary operations (and, or, xor and
9182 // select) that are all fed by extensions.
9183 while (!BinOps.empty()) {
9184 SDValue BinOp = BinOps.back();
9187 if (!Visited.insert(BinOp.getNode()).second)
9190 PromOps.push_back(BinOp);
9192 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9193 // The condition of the select is not promoted.
9194 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9196 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9199 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9200 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9201 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9202 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9203 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9204 Inputs.push_back(BinOp.getOperand(i));
9205 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9206 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9207 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9208 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9209 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9210 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9211 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9212 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9213 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9214 BinOps.push_back(BinOp.getOperand(i));
9216 // We have an input that is not an extension or another binary
9217 // operation; we'll abort this transformation.
9223 // Make sure that this is a self-contained cluster of operations (which
9224 // is not quite the same thing as saying that everything has only one
9226 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9227 if (isa<ConstantSDNode>(Inputs[i]))
9230 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9231 UE = Inputs[i].getNode()->use_end();
9234 if (User != N && !Visited.count(User))
9237 // Make sure that we're not going to promote the non-output-value
9238 // operand(s) or SELECT or SELECT_CC.
9239 // FIXME: Although we could sometimes handle this, and it does occur in
9240 // practice that one of the condition inputs to the select is also one of
9241 // the outputs, we currently can't deal with this.
9242 if (User->getOpcode() == ISD::SELECT) {
9243 if (User->getOperand(0) == Inputs[i])
9245 } else if (User->getOpcode() == ISD::SELECT_CC) {
9246 if (User->getOperand(0) == Inputs[i] ||
9247 User->getOperand(1) == Inputs[i])
9253 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9254 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9255 UE = PromOps[i].getNode()->use_end();
9258 if (User != N && !Visited.count(User))
9261 // Make sure that we're not going to promote the non-output-value
9262 // operand(s) or SELECT or SELECT_CC.
9263 // FIXME: Although we could sometimes handle this, and it does occur in
9264 // practice that one of the condition inputs to the select is also one of
9265 // the outputs, we currently can't deal with this.
9266 if (User->getOpcode() == ISD::SELECT) {
9267 if (User->getOperand(0) == PromOps[i])
9269 } else if (User->getOpcode() == ISD::SELECT_CC) {
9270 if (User->getOperand(0) == PromOps[i] ||
9271 User->getOperand(1) == PromOps[i])
9277 // Replace all inputs with the extension operand.
9278 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9279 // Constants may have users outside the cluster of to-be-promoted nodes,
9280 // and so we need to replace those as we do the promotions.
9281 if (isa<ConstantSDNode>(Inputs[i]))
9284 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9287 // Replace all operations (these are all the same, but have a different
9288 // (i1) return type). DAG.getNode will validate that the types of
9289 // a binary operator match, so go through the list in reverse so that
9290 // we've likely promoted both operands first. Any intermediate truncations or
9291 // extensions disappear.
9292 while (!PromOps.empty()) {
9293 SDValue PromOp = PromOps.back();
9296 if (PromOp.getOpcode() == ISD::TRUNCATE ||
9297 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9298 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9299 PromOp.getOpcode() == ISD::ANY_EXTEND) {
9300 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9301 PromOp.getOperand(0).getValueType() != MVT::i1) {
9302 // The operand is not yet ready (see comment below).
9303 PromOps.insert(PromOps.begin(), PromOp);
9307 SDValue RepValue = PromOp.getOperand(0);
9308 if (isa<ConstantSDNode>(RepValue))
9309 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9311 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9316 switch (PromOp.getOpcode()) {
9317 default: C = 0; break;
9318 case ISD::SELECT: C = 1; break;
9319 case ISD::SELECT_CC: C = 2; break;
9322 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9323 PromOp.getOperand(C).getValueType() != MVT::i1) ||
9324 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9325 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9326 // The to-be-promoted operands of this node have not yet been
9327 // promoted (this should be rare because we're going through the
9328 // list backward, but if one of the operands has several users in
9329 // this cluster of to-be-promoted nodes, it is possible).
9330 PromOps.insert(PromOps.begin(), PromOp);
9334 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9335 PromOp.getNode()->op_end());
9337 // If there are any constant inputs, make sure they're replaced now.
9338 for (unsigned i = 0; i < 2; ++i)
9339 if (isa<ConstantSDNode>(Ops[C+i]))
9340 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9342 DAG.ReplaceAllUsesOfValueWith(PromOp,
9343 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9346 // Now we're left with the initial truncation itself.
9347 if (N->getOpcode() == ISD::TRUNCATE)
9348 return N->getOperand(0);
9350 // Otherwise, this is a comparison. The operands to be compared have just
9351 // changed type (to i1), but everything else is the same.
9352 return SDValue(N, 0);
9355 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9356 DAGCombinerInfo &DCI) const {
9357 SelectionDAG &DAG = DCI.DAG;
9360 // If we're tracking CR bits, we need to be careful that we don't have:
9361 // zext(binary-ops(trunc(x), trunc(y)))
9363 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9364 // such that we're unnecessarily moving things into CR bits that can more
9365 // efficiently stay in GPRs. Note that if we're not certain that the high
9366 // bits are set as required by the final extension, we still may need to do
9367 // some masking to get the proper behavior.
9369 // This same functionality is important on PPC64 when dealing with
9370 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9371 // the return values of functions. Because it is so similar, it is handled
9374 if (N->getValueType(0) != MVT::i32 &&
9375 N->getValueType(0) != MVT::i64)
9378 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9379 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9382 if (N->getOperand(0).getOpcode() != ISD::AND &&
9383 N->getOperand(0).getOpcode() != ISD::OR &&
9384 N->getOperand(0).getOpcode() != ISD::XOR &&
9385 N->getOperand(0).getOpcode() != ISD::SELECT &&
9386 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9389 SmallVector<SDValue, 4> Inputs;
9390 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9391 SmallPtrSet<SDNode *, 16> Visited;
9393 // Visit all inputs, collect all binary operations (and, or, xor and
9394 // select) that are all fed by truncations.
9395 while (!BinOps.empty()) {
9396 SDValue BinOp = BinOps.back();
9399 if (!Visited.insert(BinOp.getNode()).second)
9402 PromOps.push_back(BinOp);
9404 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9405 // The condition of the select is not promoted.
9406 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9408 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9411 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9412 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9413 Inputs.push_back(BinOp.getOperand(i));
9414 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9415 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9416 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9417 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9418 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9419 BinOps.push_back(BinOp.getOperand(i));
9421 // We have an input that is not a truncation or another binary
9422 // operation; we'll abort this transformation.
9428 // The operands of a select that must be truncated when the select is
9429 // promoted because the operand is actually part of the to-be-promoted set.
9430 DenseMap<SDNode *, EVT> SelectTruncOp[2];
9432 // Make sure that this is a self-contained cluster of operations (which
9433 // is not quite the same thing as saying that everything has only one
9435 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9436 if (isa<ConstantSDNode>(Inputs[i]))
9439 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9440 UE = Inputs[i].getNode()->use_end();
9443 if (User != N && !Visited.count(User))
9446 // If we're going to promote the non-output-value operand(s) or SELECT or
9447 // SELECT_CC, record them for truncation.
9448 if (User->getOpcode() == ISD::SELECT) {
9449 if (User->getOperand(0) == Inputs[i])
9450 SelectTruncOp[0].insert(std::make_pair(User,
9451 User->getOperand(0).getValueType()));
9452 } else if (User->getOpcode() == ISD::SELECT_CC) {
9453 if (User->getOperand(0) == Inputs[i])
9454 SelectTruncOp[0].insert(std::make_pair(User,
9455 User->getOperand(0).getValueType()));
9456 if (User->getOperand(1) == Inputs[i])
9457 SelectTruncOp[1].insert(std::make_pair(User,
9458 User->getOperand(1).getValueType()));
9463 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9464 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9465 UE = PromOps[i].getNode()->use_end();
9468 if (User != N && !Visited.count(User))
9471 // If we're going to promote the non-output-value operand(s) or SELECT or
9472 // SELECT_CC, record them for truncation.
9473 if (User->getOpcode() == ISD::SELECT) {
9474 if (User->getOperand(0) == PromOps[i])
9475 SelectTruncOp[0].insert(std::make_pair(User,
9476 User->getOperand(0).getValueType()));
9477 } else if (User->getOpcode() == ISD::SELECT_CC) {
9478 if (User->getOperand(0) == PromOps[i])
9479 SelectTruncOp[0].insert(std::make_pair(User,
9480 User->getOperand(0).getValueType()));
9481 if (User->getOperand(1) == PromOps[i])
9482 SelectTruncOp[1].insert(std::make_pair(User,
9483 User->getOperand(1).getValueType()));
9488 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9489 bool ReallyNeedsExt = false;
9490 if (N->getOpcode() != ISD::ANY_EXTEND) {
9491 // If all of the inputs are not already sign/zero extended, then
9492 // we'll still need to do that at the end.
9493 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9494 if (isa<ConstantSDNode>(Inputs[i]))
9498 Inputs[i].getOperand(0).getValueSizeInBits();
9499 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9501 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9502 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9503 APInt::getHighBitsSet(OpBits,
9504 OpBits-PromBits))) ||
9505 (N->getOpcode() == ISD::SIGN_EXTEND &&
9506 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9507 (OpBits-(PromBits-1)))) {
9508 ReallyNeedsExt = true;
9514 // Replace all inputs, either with the truncation operand, or a
9515 // truncation or extension to the final output type.
9516 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9517 // Constant inputs need to be replaced with the to-be-promoted nodes that
9518 // use them because they might have users outside of the cluster of
9520 if (isa<ConstantSDNode>(Inputs[i]))
9523 SDValue InSrc = Inputs[i].getOperand(0);
9524 if (Inputs[i].getValueType() == N->getValueType(0))
9525 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9526 else if (N->getOpcode() == ISD::SIGN_EXTEND)
9527 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9528 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9529 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9530 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9531 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9533 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9534 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9537 // Replace all operations (these are all the same, but have a different
9538 // (promoted) return type). DAG.getNode will validate that the types of
9539 // a binary operator match, so go through the list in reverse so that
9540 // we've likely promoted both operands first.
9541 while (!PromOps.empty()) {
9542 SDValue PromOp = PromOps.back();
9546 switch (PromOp.getOpcode()) {
9547 default: C = 0; break;
9548 case ISD::SELECT: C = 1; break;
9549 case ISD::SELECT_CC: C = 2; break;
9552 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9553 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9554 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9555 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9556 // The to-be-promoted operands of this node have not yet been
9557 // promoted (this should be rare because we're going through the
9558 // list backward, but if one of the operands has several users in
9559 // this cluster of to-be-promoted nodes, it is possible).
9560 PromOps.insert(PromOps.begin(), PromOp);
9564 // For SELECT and SELECT_CC nodes, we do a similar check for any
9565 // to-be-promoted comparison inputs.
9566 if (PromOp.getOpcode() == ISD::SELECT ||
9567 PromOp.getOpcode() == ISD::SELECT_CC) {
9568 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9569 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9570 (SelectTruncOp[1].count(PromOp.getNode()) &&
9571 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9572 PromOps.insert(PromOps.begin(), PromOp);
9577 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9578 PromOp.getNode()->op_end());
9580 // If this node has constant inputs, then they'll need to be promoted here.
9581 for (unsigned i = 0; i < 2; ++i) {
9582 if (!isa<ConstantSDNode>(Ops[C+i]))
9584 if (Ops[C+i].getValueType() == N->getValueType(0))
9587 if (N->getOpcode() == ISD::SIGN_EXTEND)
9588 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9589 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9590 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9592 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9595 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9596 // truncate them again to the original value type.
9597 if (PromOp.getOpcode() == ISD::SELECT ||
9598 PromOp.getOpcode() == ISD::SELECT_CC) {
9599 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9600 if (SI0 != SelectTruncOp[0].end())
9601 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9602 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9603 if (SI1 != SelectTruncOp[1].end())
9604 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9607 DAG.ReplaceAllUsesOfValueWith(PromOp,
9608 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9611 // Now we're left with the initial extension itself.
9612 if (!ReallyNeedsExt)
9613 return N->getOperand(0);
9615 // To zero extend, just mask off everything except for the first bit (in the
9617 if (N->getOpcode() == ISD::ZERO_EXTEND)
9618 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9619 DAG.getConstant(APInt::getLowBitsSet(
9620 N->getValueSizeInBits(0), PromBits),
9621 N->getValueType(0)));
9623 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9624 "Invalid extension type");
9625 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9627 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9628 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
9629 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9630 N->getOperand(0), ShiftCst), ShiftCst);
9633 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9634 DAGCombinerInfo &DCI) const {
9635 assert((N->getOpcode() == ISD::SINT_TO_FP ||
9636 N->getOpcode() == ISD::UINT_TO_FP) &&
9637 "Need an int -> FP conversion node here");
9639 if (!Subtarget.has64BitSupport())
9642 SelectionDAG &DAG = DCI.DAG;
9646 // Don't handle ppc_fp128 here or i1 conversions.
9647 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9649 if (Op.getOperand(0).getValueType() == MVT::i1)
9652 // For i32 intermediate values, unfortunately, the conversion functions
9653 // leave the upper 32 bits of the value are undefined. Within the set of
9654 // scalar instructions, we have no method for zero- or sign-extending the
9655 // value. Thus, we cannot handle i32 intermediate values here.
9656 if (Op.getOperand(0).getValueType() == MVT::i32)
9659 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9660 "UINT_TO_FP is supported only with FPCVT");
9662 // If we have FCFIDS, then use it when converting to single-precision.
9663 // Otherwise, convert to double-precision and then round.
9664 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9665 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9667 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9669 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9673 // If we're converting from a float, to an int, and back to a float again,
9674 // then we don't need the store/load pair at all.
9675 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9676 Subtarget.hasFPCVT()) ||
9677 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9678 SDValue Src = Op.getOperand(0).getOperand(0);
9679 if (Src.getValueType() == MVT::f32) {
9680 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9681 DCI.AddToWorklist(Src.getNode());
9685 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9688 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9689 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9691 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9692 FP = DAG.getNode(ISD::FP_ROUND, dl,
9693 MVT::f32, FP, DAG.getIntPtrConstant(0));
9694 DCI.AddToWorklist(FP.getNode());
9703 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9704 // builtins) into loads with swaps.
9705 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9706 DAGCombinerInfo &DCI) const {
9707 SelectionDAG &DAG = DCI.DAG;
9711 MachineMemOperand *MMO;
9713 switch (N->getOpcode()) {
9715 llvm_unreachable("Unexpected opcode for little endian VSX load");
9717 LoadSDNode *LD = cast<LoadSDNode>(N);
9718 Chain = LD->getChain();
9719 Base = LD->getBasePtr();
9720 MMO = LD->getMemOperand();
9721 // If the MMO suggests this isn't a load of a full vector, leave
9722 // things alone. For a built-in, we have to make the change for
9723 // correctness, so if there is a size problem that will be a bug.
9724 if (MMO->getSize() < 16)
9728 case ISD::INTRINSIC_W_CHAIN: {
9729 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9730 Chain = Intrin->getChain();
9731 Base = Intrin->getBasePtr();
9732 MMO = Intrin->getMemOperand();
9737 MVT VecTy = N->getValueType(0).getSimpleVT();
9738 SDValue LoadOps[] = { Chain, Base };
9739 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9740 DAG.getVTList(VecTy, MVT::Other),
9741 LoadOps, VecTy, MMO);
9742 DCI.AddToWorklist(Load.getNode());
9743 Chain = Load.getValue(1);
9744 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9745 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9746 DCI.AddToWorklist(Swap.getNode());
9750 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9751 // builtins) into stores with swaps.
9752 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9753 DAGCombinerInfo &DCI) const {
9754 SelectionDAG &DAG = DCI.DAG;
9759 MachineMemOperand *MMO;
9761 switch (N->getOpcode()) {
9763 llvm_unreachable("Unexpected opcode for little endian VSX store");
9765 StoreSDNode *ST = cast<StoreSDNode>(N);
9766 Chain = ST->getChain();
9767 Base = ST->getBasePtr();
9768 MMO = ST->getMemOperand();
9770 // If the MMO suggests this isn't a store of a full vector, leave
9771 // things alone. For a built-in, we have to make the change for
9772 // correctness, so if there is a size problem that will be a bug.
9773 if (MMO->getSize() < 16)
9777 case ISD::INTRINSIC_VOID: {
9778 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9779 Chain = Intrin->getChain();
9780 // Intrin->getBasePtr() oddly does not get what we want.
9781 Base = Intrin->getOperand(3);
9782 MMO = Intrin->getMemOperand();
9788 SDValue Src = N->getOperand(SrcOpnd);
9789 MVT VecTy = Src.getValueType().getSimpleVT();
9790 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9791 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9792 DCI.AddToWorklist(Swap.getNode());
9793 Chain = Swap.getValue(1);
9794 SDValue StoreOps[] = { Chain, Swap, Base };
9795 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9796 DAG.getVTList(MVT::Other),
9797 StoreOps, VecTy, MMO);
9798 DCI.AddToWorklist(Store.getNode());
9802 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9803 DAGCombinerInfo &DCI) const {
9804 SelectionDAG &DAG = DCI.DAG;
9806 switch (N->getOpcode()) {
9809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9810 if (C->isNullValue()) // 0 << V -> 0.
9811 return N->getOperand(0);
9815 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9816 if (C->isNullValue()) // 0 >>u V -> 0.
9817 return N->getOperand(0);
9821 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9822 if (C->isNullValue() || // 0 >>s V -> 0.
9823 C->isAllOnesValue()) // -1 >>s V -> -1.
9824 return N->getOperand(0);
9827 case ISD::SIGN_EXTEND:
9828 case ISD::ZERO_EXTEND:
9829 case ISD::ANY_EXTEND:
9830 return DAGCombineExtBoolTrunc(N, DCI);
9833 case ISD::SELECT_CC:
9834 return DAGCombineTruncBoolExt(N, DCI);
9835 case ISD::SINT_TO_FP:
9836 case ISD::UINT_TO_FP:
9837 return combineFPToIntToFP(N, DCI);
9839 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9840 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9841 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9842 N->getOperand(1).getValueType() == MVT::i32 &&
9843 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9844 SDValue Val = N->getOperand(1).getOperand(0);
9845 if (Val.getValueType() == MVT::f32) {
9846 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9847 DCI.AddToWorklist(Val.getNode());
9849 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9850 DCI.AddToWorklist(Val.getNode());
9853 N->getOperand(0), Val, N->getOperand(2),
9854 DAG.getValueType(N->getOperand(1).getValueType())
9857 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9858 DAG.getVTList(MVT::Other), Ops,
9859 cast<StoreSDNode>(N)->getMemoryVT(),
9860 cast<StoreSDNode>(N)->getMemOperand());
9861 DCI.AddToWorklist(Val.getNode());
9865 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9866 if (cast<StoreSDNode>(N)->isUnindexed() &&
9867 N->getOperand(1).getOpcode() == ISD::BSWAP &&
9868 N->getOperand(1).getNode()->hasOneUse() &&
9869 (N->getOperand(1).getValueType() == MVT::i32 ||
9870 N->getOperand(1).getValueType() == MVT::i16 ||
9871 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9872 N->getOperand(1).getValueType() == MVT::i64))) {
9873 SDValue BSwapOp = N->getOperand(1).getOperand(0);
9874 // Do an any-extend to 32-bits if this is a half-word input.
9875 if (BSwapOp.getValueType() == MVT::i16)
9876 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9879 N->getOperand(0), BSwapOp, N->getOperand(2),
9880 DAG.getValueType(N->getOperand(1).getValueType())
9883 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9884 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9885 cast<StoreSDNode>(N)->getMemOperand());
9888 // For little endian, VSX stores require generating xxswapd/lxvd2x.
9889 EVT VT = N->getOperand(1).getValueType();
9890 if (VT.isSimple()) {
9891 MVT StoreVT = VT.getSimpleVT();
9892 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9893 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9894 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9895 return expandVSXStoreForLE(N, DCI);
9900 LoadSDNode *LD = cast<LoadSDNode>(N);
9901 EVT VT = LD->getValueType(0);
9903 // For little endian, VSX loads require generating lxvd2x/xxswapd.
9904 if (VT.isSimple()) {
9905 MVT LoadVT = VT.getSimpleVT();
9906 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9907 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9908 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9909 return expandVSXLoadForLE(N, DCI);
9912 EVT MemVT = LD->getMemoryVT();
9913 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9914 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9915 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9916 unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9917 if (LD->isUnindexed() && VT.isVector() &&
9918 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9919 // P8 and later hardware should just use LOAD.
9920 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9921 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9922 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9923 LD->getAlignment() >= ScalarABIAlignment)) &&
9924 LD->getAlignment() < ABIAlignment) {
9925 // This is a type-legal unaligned Altivec or QPX load.
9926 SDValue Chain = LD->getChain();
9927 SDValue Ptr = LD->getBasePtr();
9928 bool isLittleEndian = Subtarget.isLittleEndian();
9930 // This implements the loading of unaligned vectors as described in
9931 // the venerable Apple Velocity Engine overview. Specifically:
9932 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9933 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9935 // The general idea is to expand a sequence of one or more unaligned
9936 // loads into an alignment-based permutation-control instruction (lvsl
9937 // or lvsr), a series of regular vector loads (which always truncate
9938 // their input address to an aligned address), and a series of
9939 // permutations. The results of these permutations are the requested
9940 // loaded values. The trick is that the last "extra" load is not taken
9941 // from the address you might suspect (sizeof(vector) bytes after the
9942 // last requested load), but rather sizeof(vector) - 1 bytes after the
9943 // last requested vector. The point of this is to avoid a page fault if
9944 // the base address happened to be aligned. This works because if the
9945 // base address is aligned, then adding less than a full vector length
9946 // will cause the last vector in the sequence to be (re)loaded.
9947 // Otherwise, the next vector will be fetched as you might suspect was
9950 // We might be able to reuse the permutation generation from
9951 // a different base address offset from this one by an aligned amount.
9952 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9953 // optimization later.
9954 Intrinsic::ID Intr, IntrLD, IntrPerm;
9955 MVT PermCntlTy, PermTy, LDTy;
9956 if (Subtarget.hasAltivec()) {
9957 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
9958 Intrinsic::ppc_altivec_lvsl;
9959 IntrLD = Intrinsic::ppc_altivec_lvx;
9960 IntrPerm = Intrinsic::ppc_altivec_vperm;
9961 PermCntlTy = MVT::v16i8;
9962 PermTy = MVT::v4i32;
9965 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
9966 Intrinsic::ppc_qpx_qvlpcls;
9967 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
9968 Intrinsic::ppc_qpx_qvlfs;
9969 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
9970 PermCntlTy = MVT::v4f64;
9971 PermTy = MVT::v4f64;
9972 LDTy = MemVT.getSimpleVT();
9975 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
9977 // Create the new MMO for the new base load. It is like the original MMO,
9978 // but represents an area in memory almost twice the vector size centered
9979 // on the original address. If the address is unaligned, we might start
9980 // reading up to (sizeof(vector)-1) bytes below the address of the
9981 // original unaligned load.
9982 MachineFunction &MF = DAG.getMachineFunction();
9983 MachineMemOperand *BaseMMO =
9984 MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
9985 2*MemVT.getStoreSize()-1);
9987 // Create the new base load.
9988 SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
9989 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9991 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9992 DAG.getVTList(PermTy, MVT::Other),
9993 BaseLoadOps, LDTy, BaseMMO);
9995 // Note that the value of IncOffset (which is provided to the next
9996 // load's pointer info offset value, and thus used to calculate the
9997 // alignment), and the value of IncValue (which is actually used to
9998 // increment the pointer value) are different! This is because we
9999 // require the next load to appear to be aligned, even though it
10000 // is actually offset from the base pointer by a lesser amount.
10001 int IncOffset = VT.getSizeInBits() / 8;
10002 int IncValue = IncOffset;
10004 // Walk (both up and down) the chain looking for another load at the real
10005 // (aligned) offset (the alignment of the other load does not matter in
10006 // this case). If found, then do not use the offset reduction trick, as
10007 // that will prevent the loads from being later combined (as they would
10008 // otherwise be duplicates).
10009 if (!findConsecutiveLoad(LD, DAG))
10012 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
10013 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10015 MachineMemOperand *ExtraMMO =
10016 MF.getMachineMemOperand(LD->getMemOperand(),
10017 1, 2*MemVT.getStoreSize()-1);
10018 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10019 SDValue ExtraLoad =
10020 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10021 DAG.getVTList(PermTy, MVT::Other),
10022 ExtraLoadOps, LDTy, ExtraMMO);
10024 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10025 BaseLoad.getValue(1), ExtraLoad.getValue(1));
10027 // Because vperm has a big-endian bias, we must reverse the order
10028 // of the input vectors and complement the permute control vector
10029 // when generating little endian code. We have already handled the
10030 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10031 // and ExtraLoad here.
10033 if (isLittleEndian)
10034 Perm = BuildIntrinsicOp(IntrPerm,
10035 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10037 Perm = BuildIntrinsicOp(IntrPerm,
10038 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10041 Perm = Subtarget.hasAltivec() ?
10042 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10043 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10044 DAG.getTargetConstant(1, MVT::i64));
10045 // second argument is 1 because this rounding
10046 // is always exact.
10048 // The output of the permutation is our loaded result, the TokenFactor is
10050 DCI.CombineTo(N, Perm, TF);
10051 return SDValue(N, 0);
10055 case ISD::INTRINSIC_WO_CHAIN: {
10056 bool isLittleEndian = Subtarget.isLittleEndian();
10057 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10058 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10059 : Intrinsic::ppc_altivec_lvsl);
10060 if ((IID == Intr ||
10061 IID == Intrinsic::ppc_qpx_qvlpcld ||
10062 IID == Intrinsic::ppc_qpx_qvlpcls) &&
10063 N->getOperand(1)->getOpcode() == ISD::ADD) {
10064 SDValue Add = N->getOperand(1);
10066 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10067 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10069 if (DAG.MaskedValueIsZero(
10070 Add->getOperand(1),
10071 APInt::getAllOnesValue(Bits /* alignment */)
10073 Add.getValueType().getScalarType().getSizeInBits()))) {
10074 SDNode *BasePtr = Add->getOperand(0).getNode();
10075 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10076 UE = BasePtr->use_end();
10078 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10079 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10080 // We've found another LVSL/LVSR, and this address is an aligned
10081 // multiple of that one. The results will be the same, so use the
10082 // one we've just found instead.
10084 return SDValue(*UI, 0);
10089 if (isa<ConstantSDNode>(Add->getOperand(1))) {
10090 SDNode *BasePtr = Add->getOperand(0).getNode();
10091 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10092 UE = BasePtr->use_end(); UI != UE; ++UI) {
10093 if (UI->getOpcode() == ISD::ADD &&
10094 isa<ConstantSDNode>(UI->getOperand(1)) &&
10095 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10096 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10097 (1ULL << Bits) == 0) {
10098 SDNode *OtherAdd = *UI;
10099 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10100 VE = OtherAdd->use_end(); VI != VE; ++VI) {
10101 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10102 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10103 return SDValue(*VI, 0);
10113 case ISD::INTRINSIC_W_CHAIN: {
10114 // For little endian, VSX loads require generating lxvd2x/xxswapd.
10115 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10116 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10119 case Intrinsic::ppc_vsx_lxvw4x:
10120 case Intrinsic::ppc_vsx_lxvd2x:
10121 return expandVSXLoadForLE(N, DCI);
10126 case ISD::INTRINSIC_VOID: {
10127 // For little endian, VSX stores require generating xxswapd/stxvd2x.
10128 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10129 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10132 case Intrinsic::ppc_vsx_stxvw4x:
10133 case Intrinsic::ppc_vsx_stxvd2x:
10134 return expandVSXStoreForLE(N, DCI);
10140 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10141 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10142 N->getOperand(0).hasOneUse() &&
10143 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10144 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10145 N->getValueType(0) == MVT::i64))) {
10146 SDValue Load = N->getOperand(0);
10147 LoadSDNode *LD = cast<LoadSDNode>(Load);
10148 // Create the byte-swapping load.
10150 LD->getChain(), // Chain
10151 LD->getBasePtr(), // Ptr
10152 DAG.getValueType(N->getValueType(0)) // VT
10155 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10156 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10157 MVT::i64 : MVT::i32, MVT::Other),
10158 Ops, LD->getMemoryVT(), LD->getMemOperand());
10160 // If this is an i16 load, insert the truncate.
10161 SDValue ResVal = BSLoad;
10162 if (N->getValueType(0) == MVT::i16)
10163 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10165 // First, combine the bswap away. This makes the value produced by the
10167 DCI.CombineTo(N, ResVal);
10169 // Next, combine the load away, we give it a bogus result value but a real
10170 // chain result. The result value is dead because the bswap is dead.
10171 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10173 // Return N so it doesn't get rechecked!
10174 return SDValue(N, 0);
10178 case PPCISD::VCMP: {
10179 // If a VCMPo node already exists with exactly the same operands as this
10180 // node, use its result instead of this node (VCMPo computes both a CR6 and
10181 // a normal output).
10183 if (!N->getOperand(0).hasOneUse() &&
10184 !N->getOperand(1).hasOneUse() &&
10185 !N->getOperand(2).hasOneUse()) {
10187 // Scan all of the users of the LHS, looking for VCMPo's that match.
10188 SDNode *VCMPoNode = nullptr;
10190 SDNode *LHSN = N->getOperand(0).getNode();
10191 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10193 if (UI->getOpcode() == PPCISD::VCMPo &&
10194 UI->getOperand(1) == N->getOperand(1) &&
10195 UI->getOperand(2) == N->getOperand(2) &&
10196 UI->getOperand(0) == N->getOperand(0)) {
10201 // If there is no VCMPo node, or if the flag value has a single use, don't
10203 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10206 // Look at the (necessarily single) use of the flag value. If it has a
10207 // chain, this transformation is more complex. Note that multiple things
10208 // could use the value result, which we should ignore.
10209 SDNode *FlagUser = nullptr;
10210 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10211 FlagUser == nullptr; ++UI) {
10212 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10213 SDNode *User = *UI;
10214 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10215 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10222 // If the user is a MFOCRF instruction, we know this is safe.
10223 // Otherwise we give up for right now.
10224 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10225 return SDValue(VCMPoNode, 0);
10229 case ISD::BRCOND: {
10230 SDValue Cond = N->getOperand(1);
10231 SDValue Target = N->getOperand(2);
10233 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10234 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10235 Intrinsic::ppc_is_decremented_ctr_nonzero) {
10237 // We now need to make the intrinsic dead (it cannot be instruction
10239 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10240 assert(Cond.getNode()->hasOneUse() &&
10241 "Counter decrement has more than one use");
10243 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10244 N->getOperand(0), Target);
10249 // If this is a branch on an altivec predicate comparison, lower this so
10250 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
10251 // lowering is done pre-legalize, because the legalizer lowers the predicate
10252 // compare down to code that is difficult to reassemble.
10253 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10254 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10256 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10257 // value. If so, pass-through the AND to get to the intrinsic.
10258 if (LHS.getOpcode() == ISD::AND &&
10259 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10260 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10261 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10262 isa<ConstantSDNode>(LHS.getOperand(1)) &&
10263 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10265 LHS = LHS.getOperand(0);
10267 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10268 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10269 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10270 isa<ConstantSDNode>(RHS)) {
10271 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10272 "Counter decrement comparison is not EQ or NE");
10274 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10275 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10276 (CC == ISD::SETNE && !Val);
10278 // We now need to make the intrinsic dead (it cannot be instruction
10280 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10281 assert(LHS.getNode()->hasOneUse() &&
10282 "Counter decrement has more than one use");
10284 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10285 N->getOperand(0), N->getOperand(4));
10291 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10292 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10293 getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10294 assert(isDot && "Can't compare against a vector result!");
10296 // If this is a comparison against something other than 0/1, then we know
10297 // that the condition is never/always true.
10298 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10299 if (Val != 0 && Val != 1) {
10300 if (CC == ISD::SETEQ) // Cond never true, remove branch.
10301 return N->getOperand(0);
10302 // Always !=, turn it into an unconditional branch.
10303 return DAG.getNode(ISD::BR, dl, MVT::Other,
10304 N->getOperand(0), N->getOperand(4));
10307 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10309 // Create the PPCISD altivec 'dot' comparison node.
10311 LHS.getOperand(2), // LHS of compare
10312 LHS.getOperand(3), // RHS of compare
10313 DAG.getConstant(CompareOpc, MVT::i32)
10315 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10316 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10318 // Unpack the result based on how the target uses it.
10319 PPC::Predicate CompOpc;
10320 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10321 default: // Can't happen, don't crash on invalid number though.
10322 case 0: // Branch on the value of the EQ bit of CR6.
10323 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10325 case 1: // Branch on the inverted value of the EQ bit of CR6.
10326 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10328 case 2: // Branch on the value of the LT bit of CR6.
10329 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10331 case 3: // Branch on the inverted value of the LT bit of CR6.
10332 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10336 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10337 DAG.getConstant(CompOpc, MVT::i32),
10338 DAG.getRegister(PPC::CR6, MVT::i32),
10339 N->getOperand(4), CompNode.getValue(1));
10349 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10351 std::vector<SDNode *> *Created) const {
10352 // fold (sdiv X, pow2)
10353 EVT VT = N->getValueType(0);
10354 if (VT == MVT::i64 && !Subtarget.isPPC64())
10356 if ((VT != MVT::i32 && VT != MVT::i64) ||
10357 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10361 SDValue N0 = N->getOperand(0);
10363 bool IsNegPow2 = (-Divisor).isPowerOf2();
10364 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10365 SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10367 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10369 Created->push_back(Op.getNode());
10372 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10374 Created->push_back(Op.getNode());
10380 //===----------------------------------------------------------------------===//
10381 // Inline Assembly Support
10382 //===----------------------------------------------------------------------===//
10384 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10387 const SelectionDAG &DAG,
10388 unsigned Depth) const {
10389 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10390 switch (Op.getOpcode()) {
10392 case PPCISD::LBRX: {
10393 // lhbrx is known to have the top bits cleared out.
10394 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10395 KnownZero = 0xFFFF0000;
10398 case ISD::INTRINSIC_WO_CHAIN: {
10399 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10401 case Intrinsic::ppc_altivec_vcmpbfp_p:
10402 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10403 case Intrinsic::ppc_altivec_vcmpequb_p:
10404 case Intrinsic::ppc_altivec_vcmpequh_p:
10405 case Intrinsic::ppc_altivec_vcmpequw_p:
10406 case Intrinsic::ppc_altivec_vcmpequd_p:
10407 case Intrinsic::ppc_altivec_vcmpgefp_p:
10408 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10409 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10410 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10411 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10412 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10413 case Intrinsic::ppc_altivec_vcmpgtub_p:
10414 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10415 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10416 case Intrinsic::ppc_altivec_vcmpgtud_p:
10417 KnownZero = ~1U; // All bits but the low one are known to be zero.
10424 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10425 switch (Subtarget.getDarwinDirective()) {
10428 case PPC::DIR_PWR4:
10429 case PPC::DIR_PWR5:
10430 case PPC::DIR_PWR5X:
10431 case PPC::DIR_PWR6:
10432 case PPC::DIR_PWR6X:
10433 case PPC::DIR_PWR7:
10434 case PPC::DIR_PWR8: {
10438 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10440 // For small loops (between 5 and 8 instructions), align to a 32-byte
10441 // boundary so that the entire loop fits in one instruction-cache line.
10442 uint64_t LoopSize = 0;
10443 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10444 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10445 LoopSize += TII->GetInstSizeInBytes(J);
10447 if (LoopSize > 16 && LoopSize <= 32)
10454 return TargetLowering::getPrefLoopAlignment(ML);
10457 /// getConstraintType - Given a constraint, return the type of
10458 /// constraint it is for this target.
10459 PPCTargetLowering::ConstraintType
10460 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10461 if (Constraint.size() == 1) {
10462 switch (Constraint[0]) {
10469 return C_RegisterClass;
10471 // FIXME: While Z does indicate a memory constraint, it specifically
10472 // indicates an r+r address (used in conjunction with the 'y' modifier
10473 // in the replacement string). Currently, we're forcing the base
10474 // register to be r0 in the asm printer (which is interpreted as zero)
10475 // and forming the complete address in the second register. This is
10479 } else if (Constraint == "wc") { // individual CR bits.
10480 return C_RegisterClass;
10481 } else if (Constraint == "wa" || Constraint == "wd" ||
10482 Constraint == "wf" || Constraint == "ws") {
10483 return C_RegisterClass; // VSX registers.
10485 return TargetLowering::getConstraintType(Constraint);
10488 /// Examine constraint type and operand type and determine a weight value.
10489 /// This object must already have been set up with the operand type
10490 /// and the current alternative constraint selected.
10491 TargetLowering::ConstraintWeight
10492 PPCTargetLowering::getSingleConstraintMatchWeight(
10493 AsmOperandInfo &info, const char *constraint) const {
10494 ConstraintWeight weight = CW_Invalid;
10495 Value *CallOperandVal = info.CallOperandVal;
10496 // If we don't have a value, we can't do a match,
10497 // but allow it at the lowest weight.
10498 if (!CallOperandVal)
10500 Type *type = CallOperandVal->getType();
10502 // Look at the constraint type.
10503 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10504 return CW_Register; // an individual CR bit.
10505 else if ((StringRef(constraint) == "wa" ||
10506 StringRef(constraint) == "wd" ||
10507 StringRef(constraint) == "wf") &&
10508 type->isVectorTy())
10509 return CW_Register;
10510 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10511 return CW_Register;
10513 switch (*constraint) {
10515 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10518 if (type->isIntegerTy())
10519 weight = CW_Register;
10522 if (type->isFloatTy())
10523 weight = CW_Register;
10526 if (type->isDoubleTy())
10527 weight = CW_Register;
10530 if (type->isVectorTy())
10531 weight = CW_Register;
10534 weight = CW_Register;
10537 weight = CW_Memory;
10543 std::pair<unsigned, const TargetRegisterClass *>
10544 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10545 const std::string &Constraint,
10547 if (Constraint.size() == 1) {
10548 // GCC RS6000 Constraint Letters
10549 switch (Constraint[0]) {
10550 case 'b': // R1-R31
10551 if (VT == MVT::i64 && Subtarget.isPPC64())
10552 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10553 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10554 case 'r': // R0-R31
10555 if (VT == MVT::i64 && Subtarget.isPPC64())
10556 return std::make_pair(0U, &PPC::G8RCRegClass);
10557 return std::make_pair(0U, &PPC::GPRCRegClass);
10559 if (VT == MVT::f32 || VT == MVT::i32)
10560 return std::make_pair(0U, &PPC::F4RCRegClass);
10561 if (VT == MVT::f64 || VT == MVT::i64)
10562 return std::make_pair(0U, &PPC::F8RCRegClass);
10563 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10564 return std::make_pair(0U, &PPC::QFRCRegClass);
10565 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10566 return std::make_pair(0U, &PPC::QSRCRegClass);
10569 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10570 return std::make_pair(0U, &PPC::QFRCRegClass);
10571 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10572 return std::make_pair(0U, &PPC::QSRCRegClass);
10573 return std::make_pair(0U, &PPC::VRRCRegClass);
10575 return std::make_pair(0U, &PPC::CRRCRegClass);
10577 } else if (Constraint == "wc") { // an individual CR bit.
10578 return std::make_pair(0U, &PPC::CRBITRCRegClass);
10579 } else if (Constraint == "wa" || Constraint == "wd" ||
10580 Constraint == "wf") {
10581 return std::make_pair(0U, &PPC::VSRCRegClass);
10582 } else if (Constraint == "ws") {
10583 return std::make_pair(0U, &PPC::VSFRCRegClass);
10586 std::pair<unsigned, const TargetRegisterClass *> R =
10587 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10589 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10590 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10591 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10593 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10594 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10595 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10596 PPC::GPRCRegClass.contains(R.first))
10597 return std::make_pair(TRI->getMatchingSuperReg(R.first,
10598 PPC::sub_32, &PPC::G8RCRegClass),
10599 &PPC::G8RCRegClass);
10601 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10602 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10603 R.first = PPC::CR0;
10604 R.second = &PPC::CRRCRegClass;
10611 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10612 /// vector. If it is invalid, don't add anything to Ops.
10613 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10614 std::string &Constraint,
10615 std::vector<SDValue>&Ops,
10616 SelectionDAG &DAG) const {
10619 // Only support length 1 constraints.
10620 if (Constraint.length() > 1) return;
10622 char Letter = Constraint[0];
10633 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10634 if (!CST) return; // Must be an immediate to match.
10635 int64_t Value = CST->getSExtValue();
10636 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10637 // numbers are printed as such.
10639 default: llvm_unreachable("Unknown constraint letter!");
10640 case 'I': // "I" is a signed 16-bit constant.
10641 if (isInt<16>(Value))
10642 Result = DAG.getTargetConstant(Value, TCVT);
10644 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
10645 if (isShiftedUInt<16, 16>(Value))
10646 Result = DAG.getTargetConstant(Value, TCVT);
10648 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
10649 if (isShiftedInt<16, 16>(Value))
10650 Result = DAG.getTargetConstant(Value, TCVT);
10652 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
10653 if (isUInt<16>(Value))
10654 Result = DAG.getTargetConstant(Value, TCVT);
10656 case 'M': // "M" is a constant that is greater than 31.
10658 Result = DAG.getTargetConstant(Value, TCVT);
10660 case 'N': // "N" is a positive constant that is an exact power of two.
10661 if (Value > 0 && isPowerOf2_64(Value))
10662 Result = DAG.getTargetConstant(Value, TCVT);
10664 case 'O': // "O" is the constant zero.
10666 Result = DAG.getTargetConstant(Value, TCVT);
10668 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
10669 if (isInt<16>(-Value))
10670 Result = DAG.getTargetConstant(Value, TCVT);
10677 if (Result.getNode()) {
10678 Ops.push_back(Result);
10682 // Handle standard constraint letters.
10683 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10686 // isLegalAddressingMode - Return true if the addressing mode represented
10687 // by AM is legal for this target, for a load/store of the specified type.
10688 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10690 // PPC does not allow r+i addressing modes for vectors!
10691 if (Ty->isVectorTy() && AM.BaseOffs != 0)
10694 // PPC allows a sign-extended 16-bit immediate field.
10695 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10698 // No global is ever allowed as a base.
10702 // PPC only support r+r,
10703 switch (AM.Scale) {
10704 case 0: // "r+i" or just "i", depending on HasBaseReg.
10707 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
10709 // Otherwise we have r+r or r+i.
10712 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
10714 // Allow 2*r as r+r.
10717 // No other scales are supported.
10724 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10725 SelectionDAG &DAG) const {
10726 MachineFunction &MF = DAG.getMachineFunction();
10727 MachineFrameInfo *MFI = MF.getFrameInfo();
10728 MFI->setReturnAddressIsTaken(true);
10730 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10734 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10736 // Make sure the function does not optimize away the store of the RA to
10738 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10739 FuncInfo->setLRStoreRequired();
10740 bool isPPC64 = Subtarget.isPPC64();
10743 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10745 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10746 isPPC64 ? MVT::i64 : MVT::i32);
10747 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10748 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10749 FrameAddr, Offset),
10750 MachinePointerInfo(), false, false, false, 0);
10753 // Just load the return address off the stack.
10754 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10755 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10756 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10759 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10760 SelectionDAG &DAG) const {
10762 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10764 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10765 bool isPPC64 = PtrVT == MVT::i64;
10767 MachineFunction &MF = DAG.getMachineFunction();
10768 MachineFrameInfo *MFI = MF.getFrameInfo();
10769 MFI->setFrameAddressIsTaken(true);
10771 // Naked functions never have a frame pointer, and so we use r1. For all
10772 // other functions, this decision must be delayed until during PEI.
10774 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10775 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10777 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10779 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10782 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10783 FrameAddr, MachinePointerInfo(), false, false,
10788 // FIXME? Maybe this could be a TableGen attribute on some registers and
10789 // this table could be generated automatically from RegInfo.
10790 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10792 bool isPPC64 = Subtarget.isPPC64();
10793 bool isDarwinABI = Subtarget.isDarwinABI();
10795 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10796 (!isPPC64 && VT != MVT::i32))
10797 report_fatal_error("Invalid register global variable type");
10799 bool is64Bit = isPPC64 && VT == MVT::i64;
10800 unsigned Reg = StringSwitch<unsigned>(RegName)
10801 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10802 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10803 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10804 (is64Bit ? PPC::X13 : PPC::R13))
10809 report_fatal_error("Invalid register name global variable");
10813 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10814 // The PowerPC target isn't yet aware of offsets.
10818 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10820 unsigned Intrinsic) const {
10822 switch (Intrinsic) {
10823 case Intrinsic::ppc_qpx_qvlfd:
10824 case Intrinsic::ppc_qpx_qvlfs:
10825 case Intrinsic::ppc_qpx_qvlfcd:
10826 case Intrinsic::ppc_qpx_qvlfcs:
10827 case Intrinsic::ppc_qpx_qvlfiwa:
10828 case Intrinsic::ppc_qpx_qvlfiwz:
10829 case Intrinsic::ppc_altivec_lvx:
10830 case Intrinsic::ppc_altivec_lvxl:
10831 case Intrinsic::ppc_altivec_lvebx:
10832 case Intrinsic::ppc_altivec_lvehx:
10833 case Intrinsic::ppc_altivec_lvewx:
10834 case Intrinsic::ppc_vsx_lxvd2x:
10835 case Intrinsic::ppc_vsx_lxvw4x: {
10837 switch (Intrinsic) {
10838 case Intrinsic::ppc_altivec_lvebx:
10841 case Intrinsic::ppc_altivec_lvehx:
10844 case Intrinsic::ppc_altivec_lvewx:
10847 case Intrinsic::ppc_vsx_lxvd2x:
10850 case Intrinsic::ppc_qpx_qvlfd:
10853 case Intrinsic::ppc_qpx_qvlfs:
10856 case Intrinsic::ppc_qpx_qvlfcd:
10859 case Intrinsic::ppc_qpx_qvlfcs:
10867 Info.opc = ISD::INTRINSIC_W_CHAIN;
10869 Info.ptrVal = I.getArgOperand(0);
10870 Info.offset = -VT.getStoreSize()+1;
10871 Info.size = 2*VT.getStoreSize()-1;
10874 Info.readMem = true;
10875 Info.writeMem = false;
10878 case Intrinsic::ppc_qpx_qvlfda:
10879 case Intrinsic::ppc_qpx_qvlfsa:
10880 case Intrinsic::ppc_qpx_qvlfcda:
10881 case Intrinsic::ppc_qpx_qvlfcsa:
10882 case Intrinsic::ppc_qpx_qvlfiwaa:
10883 case Intrinsic::ppc_qpx_qvlfiwza: {
10885 switch (Intrinsic) {
10886 case Intrinsic::ppc_qpx_qvlfda:
10889 case Intrinsic::ppc_qpx_qvlfsa:
10892 case Intrinsic::ppc_qpx_qvlfcda:
10895 case Intrinsic::ppc_qpx_qvlfcsa:
10903 Info.opc = ISD::INTRINSIC_W_CHAIN;
10905 Info.ptrVal = I.getArgOperand(0);
10907 Info.size = VT.getStoreSize();
10910 Info.readMem = true;
10911 Info.writeMem = false;
10914 case Intrinsic::ppc_qpx_qvstfd:
10915 case Intrinsic::ppc_qpx_qvstfs:
10916 case Intrinsic::ppc_qpx_qvstfcd:
10917 case Intrinsic::ppc_qpx_qvstfcs:
10918 case Intrinsic::ppc_qpx_qvstfiw:
10919 case Intrinsic::ppc_altivec_stvx:
10920 case Intrinsic::ppc_altivec_stvxl:
10921 case Intrinsic::ppc_altivec_stvebx:
10922 case Intrinsic::ppc_altivec_stvehx:
10923 case Intrinsic::ppc_altivec_stvewx:
10924 case Intrinsic::ppc_vsx_stxvd2x:
10925 case Intrinsic::ppc_vsx_stxvw4x: {
10927 switch (Intrinsic) {
10928 case Intrinsic::ppc_altivec_stvebx:
10931 case Intrinsic::ppc_altivec_stvehx:
10934 case Intrinsic::ppc_altivec_stvewx:
10937 case Intrinsic::ppc_vsx_stxvd2x:
10940 case Intrinsic::ppc_qpx_qvstfd:
10943 case Intrinsic::ppc_qpx_qvstfs:
10946 case Intrinsic::ppc_qpx_qvstfcd:
10949 case Intrinsic::ppc_qpx_qvstfcs:
10957 Info.opc = ISD::INTRINSIC_VOID;
10959 Info.ptrVal = I.getArgOperand(1);
10960 Info.offset = -VT.getStoreSize()+1;
10961 Info.size = 2*VT.getStoreSize()-1;
10964 Info.readMem = false;
10965 Info.writeMem = true;
10968 case Intrinsic::ppc_qpx_qvstfda:
10969 case Intrinsic::ppc_qpx_qvstfsa:
10970 case Intrinsic::ppc_qpx_qvstfcda:
10971 case Intrinsic::ppc_qpx_qvstfcsa:
10972 case Intrinsic::ppc_qpx_qvstfiwa: {
10974 switch (Intrinsic) {
10975 case Intrinsic::ppc_qpx_qvstfda:
10978 case Intrinsic::ppc_qpx_qvstfsa:
10981 case Intrinsic::ppc_qpx_qvstfcda:
10984 case Intrinsic::ppc_qpx_qvstfcsa:
10992 Info.opc = ISD::INTRINSIC_VOID;
10994 Info.ptrVal = I.getArgOperand(1);
10996 Info.size = VT.getStoreSize();
10999 Info.readMem = false;
11000 Info.writeMem = true;
11010 /// getOptimalMemOpType - Returns the target specific optimal type for load
11011 /// and store operations as a result of memset, memcpy, and memmove
11012 /// lowering. If DstAlign is zero that means it's safe to destination
11013 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11014 /// means there isn't a need to check it against alignment requirement,
11015 /// probably because the source does not need to be loaded. If 'IsMemset' is
11016 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11017 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11018 /// source is constant so it does not need to be loaded.
11019 /// It returns EVT::Other if the type should be determined using generic
11020 /// target-independent logic.
11021 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11022 unsigned DstAlign, unsigned SrcAlign,
11023 bool IsMemset, bool ZeroMemset,
11025 MachineFunction &MF) const {
11026 const Function *F = MF.getFunction();
11027 // When expanding a memset, require at least two QPX instructions to cover
11028 // the cost of loading the value to be stored from the constant pool.
11029 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11030 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11031 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11035 // We should use Altivec/VSX loads and stores when available. For unaligned
11036 // addresses, unaligned VSX loads are only fast starting with the P8.
11037 if (Subtarget.hasAltivec() && Size >= 16 &&
11038 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11039 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11042 if (Subtarget.isPPC64()) {
11049 /// \brief Returns true if it is beneficial to convert a load of a constant
11050 /// to just the constant itself.
11051 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11053 assert(Ty->isIntegerTy());
11055 unsigned BitSize = Ty->getPrimitiveSizeInBits();
11056 if (BitSize == 0 || BitSize > 64)
11061 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11062 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11064 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11065 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11066 return NumBits1 == 64 && NumBits2 == 32;
11069 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11070 if (!VT1.isInteger() || !VT2.isInteger())
11072 unsigned NumBits1 = VT1.getSizeInBits();
11073 unsigned NumBits2 = VT2.getSizeInBits();
11074 return NumBits1 == 64 && NumBits2 == 32;
11077 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11078 // Generally speaking, zexts are not free, but they are free when they can be
11079 // folded with other operations.
11080 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11081 EVT MemVT = LD->getMemoryVT();
11082 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11083 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11084 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11085 LD->getExtensionType() == ISD::ZEXTLOAD))
11089 // FIXME: Add other cases...
11090 // - 32-bit shifts with a zext to i64
11091 // - zext after ctlz, bswap, etc.
11092 // - zext after and by a constant mask
11094 return TargetLowering::isZExtFree(Val, VT2);
11097 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11098 assert(VT.isFloatingPoint());
11102 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11103 return isInt<16>(Imm) || isUInt<16>(Imm);
11106 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11107 return isInt<16>(Imm) || isUInt<16>(Imm);
11110 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11113 bool *Fast) const {
11114 if (DisablePPCUnaligned)
11117 // PowerPC supports unaligned memory access for simple non-vector types.
11118 // Although accessing unaligned addresses is not as efficient as accessing
11119 // aligned addresses, it is generally more efficient than manual expansion,
11120 // and generally only traps for software emulation when crossing page
11123 if (!VT.isSimple())
11126 if (VT.getSimpleVT().isVector()) {
11127 if (Subtarget.hasVSX()) {
11128 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11129 VT != MVT::v4f32 && VT != MVT::v4i32)
11136 if (VT == MVT::ppcf128)
11145 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11146 VT = VT.getScalarType();
11148 if (!VT.isSimple())
11151 switch (VT.getSimpleVT().SimpleTy) {
11163 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11164 // LR is a callee-save register, but we must treat it as clobbered by any call
11165 // site. Hence we include LR in the scratch registers, which are in turn added
11166 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11167 // to CTR, which is used by any indirect call.
11168 static const MCPhysReg ScratchRegs[] = {
11169 PPC::X12, PPC::LR8, PPC::CTR8, 0
11172 return ScratchRegs;
11176 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11177 EVT VT , unsigned DefinedValues) const {
11178 if (VT == MVT::v2i64)
11181 if (Subtarget.hasQPX()) {
11182 if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11186 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11189 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11190 if (DisableILPPref || Subtarget.enableMachineScheduler())
11191 return TargetLowering::getSchedulingPreference(N);
11196 // Create a fast isel object.
11198 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11199 const TargetLibraryInfo *LibInfo) const {
11200 return PPC::createFastISel(FuncInfo, LibInfo);