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 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1291 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1292 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1293 SelectionDAG &DAG) {
1294 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1295 assert(isSplatShuffleMask(SVOp, EltSize));
1296 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1297 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1299 return SVOp->getMaskElt(0) / EltSize;
1302 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1303 /// by using a vspltis[bhw] instruction of the specified element size, return
1304 /// the constant being splatted. The ByteSize field indicates the number of
1305 /// bytes of each element [124] -> [bhw].
1306 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1307 SDValue OpVal(nullptr, 0);
1309 // If ByteSize of the splat is bigger than the element size of the
1310 // build_vector, then we have a case where we are checking for a splat where
1311 // multiple elements of the buildvector are folded together into a single
1312 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1313 unsigned EltSize = 16/N->getNumOperands();
1314 if (EltSize < ByteSize) {
1315 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1316 SDValue UniquedVals[4];
1317 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1319 // See if all of the elements in the buildvector agree across.
1320 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1321 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1322 // If the element isn't a constant, bail fully out.
1323 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1326 if (!UniquedVals[i&(Multiple-1)].getNode())
1327 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1328 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1329 return SDValue(); // no match.
1332 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1333 // either constant or undef values that are identical for each chunk. See
1334 // if these chunks can form into a larger vspltis*.
1336 // Check to see if all of the leading entries are either 0 or -1. If
1337 // neither, then this won't fit into the immediate field.
1338 bool LeadingZero = true;
1339 bool LeadingOnes = true;
1340 for (unsigned i = 0; i != Multiple-1; ++i) {
1341 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1343 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1344 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1346 // Finally, check the least significant entry.
1348 if (!UniquedVals[Multiple-1].getNode())
1349 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1350 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1352 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1355 if (!UniquedVals[Multiple-1].getNode())
1356 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1357 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1358 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1359 return DAG.getTargetConstant(Val, MVT::i32);
1365 // Check to see if this buildvec has a single non-undef value in its elements.
1366 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1367 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1368 if (!OpVal.getNode())
1369 OpVal = N->getOperand(i);
1370 else if (OpVal != N->getOperand(i))
1374 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1376 unsigned ValSizeInBytes = EltSize;
1378 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1379 Value = CN->getZExtValue();
1380 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1381 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1382 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1385 // If the splat value is larger than the element value, then we can never do
1386 // this splat. The only case that we could fit the replicated bits into our
1387 // immediate field for would be zero, and we prefer to use vxor for it.
1388 if (ValSizeInBytes < ByteSize) return SDValue();
1390 // If the element value is larger than the splat value, check if it consists
1391 // of a repeated bit pattern of size ByteSize.
1392 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1395 // Properly sign extend the value.
1396 int MaskVal = SignExtend32(Value, ByteSize * 8);
1398 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1399 if (MaskVal == 0) return SDValue();
1401 // Finally, if this value fits in a 5 bit sext field, return it
1402 if (SignExtend32<5>(MaskVal) == MaskVal)
1403 return DAG.getTargetConstant(MaskVal, MVT::i32);
1407 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1408 /// amount, otherwise return -1.
1409 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1410 EVT VT = N->getValueType(0);
1411 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1414 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1416 // Find the first non-undef value in the shuffle mask.
1418 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1421 if (i == 4) return -1; // all undef.
1423 // Otherwise, check to see if the rest of the elements are consecutively
1424 // numbered from this value.
1425 unsigned ShiftAmt = SVOp->getMaskElt(i);
1426 if (ShiftAmt < i) return -1;
1429 // Check the rest of the elements to see if they are consecutive.
1430 for (++i; i != 4; ++i)
1431 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1437 //===----------------------------------------------------------------------===//
1438 // Addressing Mode Selection
1439 //===----------------------------------------------------------------------===//
1441 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1442 /// or 64-bit immediate, and if the value can be accurately represented as a
1443 /// sign extension from a 16-bit value. If so, this returns true and the
1445 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1446 if (!isa<ConstantSDNode>(N))
1449 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1450 if (N->getValueType(0) == MVT::i32)
1451 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1453 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1455 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1456 return isIntS16Immediate(Op.getNode(), Imm);
1460 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1461 /// can be represented as an indexed [r+r] operation. Returns false if it
1462 /// can be more efficiently represented with [r+imm].
1463 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1465 SelectionDAG &DAG) const {
1467 if (N.getOpcode() == ISD::ADD) {
1468 if (isIntS16Immediate(N.getOperand(1), imm))
1469 return false; // r+i
1470 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1471 return false; // r+i
1473 Base = N.getOperand(0);
1474 Index = N.getOperand(1);
1476 } else if (N.getOpcode() == ISD::OR) {
1477 if (isIntS16Immediate(N.getOperand(1), imm))
1478 return false; // r+i can fold it if we can.
1480 // If this is an or of disjoint bitfields, we can codegen this as an add
1481 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1483 APInt LHSKnownZero, LHSKnownOne;
1484 APInt RHSKnownZero, RHSKnownOne;
1485 DAG.computeKnownBits(N.getOperand(0),
1486 LHSKnownZero, LHSKnownOne);
1488 if (LHSKnownZero.getBoolValue()) {
1489 DAG.computeKnownBits(N.getOperand(1),
1490 RHSKnownZero, RHSKnownOne);
1491 // If all of the bits are known zero on the LHS or RHS, the add won't
1493 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1494 Base = N.getOperand(0);
1495 Index = N.getOperand(1);
1504 // If we happen to be doing an i64 load or store into a stack slot that has
1505 // less than a 4-byte alignment, then the frame-index elimination may need to
1506 // use an indexed load or store instruction (because the offset may not be a
1507 // multiple of 4). The extra register needed to hold the offset comes from the
1508 // register scavenger, and it is possible that the scavenger will need to use
1509 // an emergency spill slot. As a result, we need to make sure that a spill slot
1510 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1512 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1513 // FIXME: This does not handle the LWA case.
1517 // NOTE: We'll exclude negative FIs here, which come from argument
1518 // lowering, because there are no known test cases triggering this problem
1519 // using packed structures (or similar). We can remove this exclusion if
1520 // we find such a test case. The reason why this is so test-case driven is
1521 // because this entire 'fixup' is only to prevent crashes (from the
1522 // register scavenger) on not-really-valid inputs. For example, if we have:
1524 // %b = bitcast i1* %a to i64*
1525 // store i64* a, i64 b
1526 // then the store should really be marked as 'align 1', but is not. If it
1527 // were marked as 'align 1' then the indexed form would have been
1528 // instruction-selected initially, and the problem this 'fixup' is preventing
1529 // won't happen regardless.
1533 MachineFunction &MF = DAG.getMachineFunction();
1534 MachineFrameInfo *MFI = MF.getFrameInfo();
1536 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1540 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1541 FuncInfo->setHasNonRISpills();
1544 /// Returns true if the address N can be represented by a base register plus
1545 /// a signed 16-bit displacement [r+imm], and if it is not better
1546 /// represented as reg+reg. If Aligned is true, only accept displacements
1547 /// suitable for STD and friends, i.e. multiples of 4.
1548 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1551 bool Aligned) const {
1552 // FIXME dl should come from parent load or store, not from address
1554 // If this can be more profitably realized as r+r, fail.
1555 if (SelectAddressRegReg(N, Disp, Base, DAG))
1558 if (N.getOpcode() == ISD::ADD) {
1560 if (isIntS16Immediate(N.getOperand(1), imm) &&
1561 (!Aligned || (imm & 3) == 0)) {
1562 Disp = DAG.getTargetConstant(imm, N.getValueType());
1563 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1564 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1565 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1567 Base = N.getOperand(0);
1569 return true; // [r+i]
1570 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1571 // Match LOAD (ADD (X, Lo(G))).
1572 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1573 && "Cannot handle constant offsets yet!");
1574 Disp = N.getOperand(1).getOperand(0); // The global address.
1575 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1576 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1577 Disp.getOpcode() == ISD::TargetConstantPool ||
1578 Disp.getOpcode() == ISD::TargetJumpTable);
1579 Base = N.getOperand(0);
1580 return true; // [&g+r]
1582 } else if (N.getOpcode() == ISD::OR) {
1584 if (isIntS16Immediate(N.getOperand(1), imm) &&
1585 (!Aligned || (imm & 3) == 0)) {
1586 // If this is an or of disjoint bitfields, we can codegen this as an add
1587 // (for better address arithmetic) if the LHS and RHS of the OR are
1588 // provably disjoint.
1589 APInt LHSKnownZero, LHSKnownOne;
1590 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1592 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1593 // If all of the bits are known zero on the LHS or RHS, the add won't
1595 if (FrameIndexSDNode *FI =
1596 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1597 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1598 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1600 Base = N.getOperand(0);
1602 Disp = DAG.getTargetConstant(imm, N.getValueType());
1606 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1607 // Loading from a constant address.
1609 // If this address fits entirely in a 16-bit sext immediate field, codegen
1612 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1613 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1614 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1615 CN->getValueType(0));
1619 // Handle 32-bit sext immediates with LIS + addr mode.
1620 if ((CN->getValueType(0) == MVT::i32 ||
1621 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1622 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1623 int Addr = (int)CN->getZExtValue();
1625 // Otherwise, break this down into an LIS + disp.
1626 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1628 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1629 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1630 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1635 Disp = DAG.getTargetConstant(0, getPointerTy());
1636 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1637 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1638 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1641 return true; // [r+0]
1644 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1645 /// represented as an indexed [r+r] operation.
1646 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1648 SelectionDAG &DAG) const {
1649 // Check to see if we can easily represent this as an [r+r] address. This
1650 // will fail if it thinks that the address is more profitably represented as
1651 // reg+imm, e.g. where imm = 0.
1652 if (SelectAddressRegReg(N, Base, Index, DAG))
1655 // If the operand is an addition, always emit this as [r+r], since this is
1656 // better (for code size, and execution, as the memop does the add for free)
1657 // than emitting an explicit add.
1658 if (N.getOpcode() == ISD::ADD) {
1659 Base = N.getOperand(0);
1660 Index = N.getOperand(1);
1664 // Otherwise, do it the hard way, using R0 as the base register.
1665 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1671 /// getPreIndexedAddressParts - returns true by value, base pointer and
1672 /// offset pointer and addressing mode by reference if the node's address
1673 /// can be legally represented as pre-indexed load / store address.
1674 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1676 ISD::MemIndexedMode &AM,
1677 SelectionDAG &DAG) const {
1678 if (DisablePPCPreinc) return false;
1684 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1685 Ptr = LD->getBasePtr();
1686 VT = LD->getMemoryVT();
1687 Alignment = LD->getAlignment();
1688 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1689 Ptr = ST->getBasePtr();
1690 VT = ST->getMemoryVT();
1691 Alignment = ST->getAlignment();
1696 // PowerPC doesn't have preinc load/store instructions for vectors (except
1697 // for QPX, which does have preinc r+r forms).
1698 if (VT.isVector()) {
1699 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1701 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1707 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1709 // Common code will reject creating a pre-inc form if the base pointer
1710 // is a frame index, or if N is a store and the base pointer is either
1711 // the same as or a predecessor of the value being stored. Check for
1712 // those situations here, and try with swapped Base/Offset instead.
1715 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1718 SDValue Val = cast<StoreSDNode>(N)->getValue();
1719 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1724 std::swap(Base, Offset);
1730 // LDU/STU can only handle immediates that are a multiple of 4.
1731 if (VT != MVT::i64) {
1732 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1735 // LDU/STU need an address with at least 4-byte alignment.
1739 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1743 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1744 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1745 // sext i32 to i64 when addr mode is r+i.
1746 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1747 LD->getExtensionType() == ISD::SEXTLOAD &&
1748 isa<ConstantSDNode>(Offset))
1756 //===----------------------------------------------------------------------===//
1757 // LowerOperation implementation
1758 //===----------------------------------------------------------------------===//
1760 /// GetLabelAccessInfo - Return true if we should reference labels using a
1761 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1762 static bool GetLabelAccessInfo(const TargetMachine &TM,
1763 const PPCSubtarget &Subtarget,
1764 unsigned &HiOpFlags, unsigned &LoOpFlags,
1765 const GlobalValue *GV = nullptr) {
1766 HiOpFlags = PPCII::MO_HA;
1767 LoOpFlags = PPCII::MO_LO;
1769 // Don't use the pic base if not in PIC relocation model.
1770 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1773 HiOpFlags |= PPCII::MO_PIC_FLAG;
1774 LoOpFlags |= PPCII::MO_PIC_FLAG;
1777 // If this is a reference to a global value that requires a non-lazy-ptr, make
1778 // sure that instruction lowering adds it.
1779 if (GV && Subtarget.hasLazyResolverStub(GV)) {
1780 HiOpFlags |= PPCII::MO_NLP_FLAG;
1781 LoOpFlags |= PPCII::MO_NLP_FLAG;
1783 if (GV->hasHiddenVisibility()) {
1784 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1785 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1792 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1793 SelectionDAG &DAG) {
1794 EVT PtrVT = HiPart.getValueType();
1795 SDValue Zero = DAG.getConstant(0, PtrVT);
1798 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1799 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1801 // With PIC, the first instruction is actually "GR+hi(&G)".
1803 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1804 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1806 // Generate non-pic code that has direct accesses to the constant pool.
1807 // The address of the global is just (hi(&g)+lo(&g)).
1808 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1811 static void setUsesTOCBasePtr(MachineFunction &MF) {
1812 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1813 FuncInfo->setUsesTOCBasePtr();
1816 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1817 setUsesTOCBasePtr(DAG.getMachineFunction());
1820 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1822 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1823 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1824 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1826 SDValue Ops[] = { GA, Reg };
1827 return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1828 DAG.getVTList(VT, MVT::Other), Ops, VT,
1829 MachinePointerInfo::getGOT(), 0, false, true,
1833 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1834 SelectionDAG &DAG) const {
1835 EVT PtrVT = Op.getValueType();
1836 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1837 const Constant *C = CP->getConstVal();
1839 // 64-bit SVR4 ABI code is always position-independent.
1840 // The actual address of the GlobalValue is stored in the TOC.
1841 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1842 setUsesTOCBasePtr(DAG);
1843 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1844 return getTOCEntry(DAG, SDLoc(CP), true, GA);
1847 unsigned MOHiFlag, MOLoFlag;
1849 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1851 if (isPIC && Subtarget.isSVR4ABI()) {
1852 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1853 PPCII::MO_PIC_FLAG);
1854 return getTOCEntry(DAG, SDLoc(CP), false, GA);
1858 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1860 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1861 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1864 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1865 EVT PtrVT = Op.getValueType();
1866 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1868 // 64-bit SVR4 ABI code is always position-independent.
1869 // The actual address of the GlobalValue is stored in the TOC.
1870 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1871 setUsesTOCBasePtr(DAG);
1872 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1873 return getTOCEntry(DAG, SDLoc(JT), true, GA);
1876 unsigned MOHiFlag, MOLoFlag;
1878 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1880 if (isPIC && Subtarget.isSVR4ABI()) {
1881 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1882 PPCII::MO_PIC_FLAG);
1883 return getTOCEntry(DAG, SDLoc(GA), false, GA);
1886 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1887 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1888 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1891 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1892 SelectionDAG &DAG) const {
1893 EVT PtrVT = Op.getValueType();
1894 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1895 const BlockAddress *BA = BASDN->getBlockAddress();
1897 // 64-bit SVR4 ABI code is always position-independent.
1898 // The actual BlockAddress is stored in the TOC.
1899 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1900 setUsesTOCBasePtr(DAG);
1901 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1902 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1905 unsigned MOHiFlag, MOLoFlag;
1907 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1908 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1909 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1910 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1913 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1914 SelectionDAG &DAG) const {
1916 // FIXME: TLS addresses currently use medium model code sequences,
1917 // which is the most useful form. Eventually support for small and
1918 // large models could be added if users need it, at the cost of
1919 // additional complexity.
1920 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1922 const GlobalValue *GV = GA->getGlobal();
1923 EVT PtrVT = getPointerTy();
1924 bool is64bit = Subtarget.isPPC64();
1925 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1926 PICLevel::Level picLevel = M->getPICLevel();
1928 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1930 if (Model == TLSModel::LocalExec) {
1931 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1932 PPCII::MO_TPREL_HA);
1933 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1934 PPCII::MO_TPREL_LO);
1935 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1936 is64bit ? MVT::i64 : MVT::i32);
1937 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1938 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1941 if (Model == TLSModel::InitialExec) {
1942 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1943 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1947 setUsesTOCBasePtr(DAG);
1948 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1949 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1950 PtrVT, GOTReg, TGA);
1952 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1953 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1954 PtrVT, TGA, GOTPtr);
1955 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1958 if (Model == TLSModel::GeneralDynamic) {
1959 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1962 setUsesTOCBasePtr(DAG);
1963 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1964 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1967 if (picLevel == PICLevel::Small)
1968 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1970 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1972 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1976 if (Model == TLSModel::LocalDynamic) {
1977 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1980 setUsesTOCBasePtr(DAG);
1981 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1982 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1985 if (picLevel == PICLevel::Small)
1986 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1988 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1990 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
1991 PtrVT, GOTPtr, TGA, TGA);
1992 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
1993 PtrVT, TLSAddr, TGA);
1994 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1997 llvm_unreachable("Unknown TLS model!");
2000 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2001 SelectionDAG &DAG) const {
2002 EVT PtrVT = Op.getValueType();
2003 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2005 const GlobalValue *GV = GSDN->getGlobal();
2007 // 64-bit SVR4 ABI code is always position-independent.
2008 // The actual address of the GlobalValue is stored in the TOC.
2009 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2010 setUsesTOCBasePtr(DAG);
2011 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2012 return getTOCEntry(DAG, DL, true, GA);
2015 unsigned MOHiFlag, MOLoFlag;
2017 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2019 if (isPIC && Subtarget.isSVR4ABI()) {
2020 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2022 PPCII::MO_PIC_FLAG);
2023 return getTOCEntry(DAG, DL, false, GA);
2027 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2029 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2031 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2033 // If the global reference is actually to a non-lazy-pointer, we have to do an
2034 // extra load to get the address of the global.
2035 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2036 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2037 false, false, false, 0);
2041 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2042 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2045 if (Op.getValueType() == MVT::v2i64) {
2046 // When the operands themselves are v2i64 values, we need to do something
2047 // special because VSX has no underlying comparison operations for these.
2048 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2049 // Equality can be handled by casting to the legal type for Altivec
2050 // comparisons, everything else needs to be expanded.
2051 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2052 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2053 DAG.getSetCC(dl, MVT::v4i32,
2054 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2055 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2062 // We handle most of these in the usual way.
2066 // If we're comparing for equality to zero, expose the fact that this is
2067 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2068 // fold the new nodes.
2069 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2070 if (C->isNullValue() && CC == ISD::SETEQ) {
2071 EVT VT = Op.getOperand(0).getValueType();
2072 SDValue Zext = Op.getOperand(0);
2073 if (VT.bitsLT(MVT::i32)) {
2075 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2077 unsigned Log2b = Log2_32(VT.getSizeInBits());
2078 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2079 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2080 DAG.getConstant(Log2b, MVT::i32));
2081 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2083 // Leave comparisons against 0 and -1 alone for now, since they're usually
2084 // optimized. FIXME: revisit this when we can custom lower all setcc
2086 if (C->isAllOnesValue() || C->isNullValue())
2090 // If we have an integer seteq/setne, turn it into a compare against zero
2091 // by xor'ing the rhs with the lhs, which is faster than setting a
2092 // condition register, reading it back out, and masking the correct bit. The
2093 // normal approach here uses sub to do this instead of xor. Using xor exposes
2094 // the result to other bit-twiddling opportunities.
2095 EVT LHSVT = Op.getOperand(0).getValueType();
2096 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2097 EVT VT = Op.getValueType();
2098 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2100 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2105 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2106 const PPCSubtarget &Subtarget) const {
2107 SDNode *Node = Op.getNode();
2108 EVT VT = Node->getValueType(0);
2109 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2110 SDValue InChain = Node->getOperand(0);
2111 SDValue VAListPtr = Node->getOperand(1);
2112 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2115 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2118 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2119 VAListPtr, MachinePointerInfo(SV), MVT::i8,
2120 false, false, false, 0);
2121 InChain = GprIndex.getValue(1);
2123 if (VT == MVT::i64) {
2124 // Check if GprIndex is even
2125 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2126 DAG.getConstant(1, MVT::i32));
2127 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2128 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2129 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2130 DAG.getConstant(1, MVT::i32));
2131 // Align GprIndex to be even if it isn't
2132 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2136 // fpr index is 1 byte after gpr
2137 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2138 DAG.getConstant(1, MVT::i32));
2141 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2142 FprPtr, MachinePointerInfo(SV), MVT::i8,
2143 false, false, false, 0);
2144 InChain = FprIndex.getValue(1);
2146 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2147 DAG.getConstant(8, MVT::i32));
2149 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2150 DAG.getConstant(4, MVT::i32));
2153 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2154 MachinePointerInfo(), false, false,
2156 InChain = OverflowArea.getValue(1);
2158 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2159 MachinePointerInfo(), false, false,
2161 InChain = RegSaveArea.getValue(1);
2163 // select overflow_area if index > 8
2164 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2165 DAG.getConstant(8, MVT::i32), ISD::SETLT);
2167 // adjustment constant gpr_index * 4/8
2168 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2169 VT.isInteger() ? GprIndex : FprIndex,
2170 DAG.getConstant(VT.isInteger() ? 4 : 8,
2173 // OurReg = RegSaveArea + RegConstant
2174 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2177 // Floating types are 32 bytes into RegSaveArea
2178 if (VT.isFloatingPoint())
2179 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2180 DAG.getConstant(32, MVT::i32));
2182 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2183 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2184 VT.isInteger() ? GprIndex : FprIndex,
2185 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2188 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2189 VT.isInteger() ? VAListPtr : FprPtr,
2190 MachinePointerInfo(SV),
2191 MVT::i8, false, false, 0);
2193 // determine if we should load from reg_save_area or overflow_area
2194 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2196 // increase overflow_area by 4/8 if gpr/fpr > 8
2197 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2198 DAG.getConstant(VT.isInteger() ? 4 : 8,
2201 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2204 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2206 MachinePointerInfo(),
2207 MVT::i32, false, false, 0);
2209 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2210 false, false, false, 0);
2213 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2214 const PPCSubtarget &Subtarget) const {
2215 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2217 // We have to copy the entire va_list struct:
2218 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2219 return DAG.getMemcpy(Op.getOperand(0), Op,
2220 Op.getOperand(1), Op.getOperand(2),
2221 DAG.getConstant(12, MVT::i32), 8, false, true,
2222 MachinePointerInfo(), MachinePointerInfo());
2225 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2226 SelectionDAG &DAG) const {
2227 return Op.getOperand(0);
2230 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2231 SelectionDAG &DAG) const {
2232 SDValue Chain = Op.getOperand(0);
2233 SDValue Trmp = Op.getOperand(1); // trampoline
2234 SDValue FPtr = Op.getOperand(2); // nested function
2235 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2238 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2239 bool isPPC64 = (PtrVT == MVT::i64);
2241 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2244 TargetLowering::ArgListTy Args;
2245 TargetLowering::ArgListEntry Entry;
2247 Entry.Ty = IntPtrTy;
2248 Entry.Node = Trmp; Args.push_back(Entry);
2250 // TrampSize == (isPPC64 ? 48 : 40);
2251 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2252 isPPC64 ? MVT::i64 : MVT::i32);
2253 Args.push_back(Entry);
2255 Entry.Node = FPtr; Args.push_back(Entry);
2256 Entry.Node = Nest; Args.push_back(Entry);
2258 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2259 TargetLowering::CallLoweringInfo CLI(DAG);
2260 CLI.setDebugLoc(dl).setChain(Chain)
2261 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2262 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2263 std::move(Args), 0);
2265 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2266 return CallResult.second;
2269 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2270 const PPCSubtarget &Subtarget) const {
2271 MachineFunction &MF = DAG.getMachineFunction();
2272 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2276 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2277 // vastart just stores the address of the VarArgsFrameIndex slot into the
2278 // memory location argument.
2279 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2280 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2281 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2282 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2283 MachinePointerInfo(SV),
2287 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2288 // We suppose the given va_list is already allocated.
2291 // char gpr; /* index into the array of 8 GPRs
2292 // * stored in the register save area
2293 // * gpr=0 corresponds to r3,
2294 // * gpr=1 to r4, etc.
2296 // char fpr; /* index into the array of 8 FPRs
2297 // * stored in the register save area
2298 // * fpr=0 corresponds to f1,
2299 // * fpr=1 to f2, etc.
2301 // char *overflow_arg_area;
2302 // /* location on stack that holds
2303 // * the next overflow argument
2305 // char *reg_save_area;
2306 // /* where r3:r10 and f1:f8 (if saved)
2312 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2313 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2316 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2318 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2320 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2323 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2324 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2326 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2327 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2329 uint64_t FPROffset = 1;
2330 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2332 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2334 // Store first byte : number of int regs
2335 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2337 MachinePointerInfo(SV),
2338 MVT::i8, false, false, 0);
2339 uint64_t nextOffset = FPROffset;
2340 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2343 // Store second byte : number of float regs
2344 SDValue secondStore =
2345 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2346 MachinePointerInfo(SV, nextOffset), MVT::i8,
2348 nextOffset += StackOffset;
2349 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2351 // Store second word : arguments given on stack
2352 SDValue thirdStore =
2353 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2354 MachinePointerInfo(SV, nextOffset),
2356 nextOffset += FrameOffset;
2357 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2359 // Store third word : arguments given in registers
2360 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2361 MachinePointerInfo(SV, nextOffset),
2366 #include "PPCGenCallingConv.inc"
2368 // Function whose sole purpose is to kill compiler warnings
2369 // stemming from unused functions included from PPCGenCallingConv.inc.
2370 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2371 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2374 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2375 CCValAssign::LocInfo &LocInfo,
2376 ISD::ArgFlagsTy &ArgFlags,
2381 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2383 CCValAssign::LocInfo &LocInfo,
2384 ISD::ArgFlagsTy &ArgFlags,
2386 static const MCPhysReg ArgRegs[] = {
2387 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2388 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2390 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2392 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2394 // Skip one register if the first unallocated register has an even register
2395 // number and there are still argument registers available which have not been
2396 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2397 // need to skip a register if RegNum is odd.
2398 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2399 State.AllocateReg(ArgRegs[RegNum]);
2402 // Always return false here, as this function only makes sure that the first
2403 // unallocated register has an odd register number and does not actually
2404 // allocate a register for the current argument.
2408 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2410 CCValAssign::LocInfo &LocInfo,
2411 ISD::ArgFlagsTy &ArgFlags,
2413 static const MCPhysReg ArgRegs[] = {
2414 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2418 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2420 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2422 // If there is only one Floating-point register left we need to put both f64
2423 // values of a split ppc_fp128 value on the stack.
2424 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2425 State.AllocateReg(ArgRegs[RegNum]);
2428 // Always return false here, as this function only makes sure that the two f64
2429 // values a ppc_fp128 value is split into are both passed in registers or both
2430 // passed on the stack and does not actually allocate a register for the
2431 // current argument.
2435 /// FPR - The set of FP registers that should be allocated for arguments,
2437 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2438 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2439 PPC::F11, PPC::F12, PPC::F13};
2441 /// QFPR - The set of QPX registers that should be allocated for arguments.
2442 static const MCPhysReg QFPR[] = {
2443 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2444 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2446 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2448 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2449 unsigned PtrByteSize) {
2450 unsigned ArgSize = ArgVT.getStoreSize();
2451 if (Flags.isByVal())
2452 ArgSize = Flags.getByValSize();
2454 // Round up to multiples of the pointer size, except for array members,
2455 // which are always packed.
2456 if (!Flags.isInConsecutiveRegs())
2457 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2462 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2464 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2465 ISD::ArgFlagsTy Flags,
2466 unsigned PtrByteSize) {
2467 unsigned Align = PtrByteSize;
2469 // Altivec parameters are padded to a 16 byte boundary.
2470 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2471 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2472 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2474 // QPX vector types stored in double-precision are padded to a 32 byte
2476 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2479 // ByVal parameters are aligned as requested.
2480 if (Flags.isByVal()) {
2481 unsigned BVAlign = Flags.getByValAlign();
2482 if (BVAlign > PtrByteSize) {
2483 if (BVAlign % PtrByteSize != 0)
2485 "ByVal alignment is not a multiple of the pointer size");
2491 // Array members are always packed to their original alignment.
2492 if (Flags.isInConsecutiveRegs()) {
2493 // If the array member was split into multiple registers, the first
2494 // needs to be aligned to the size of the full type. (Except for
2495 // ppcf128, which is only aligned as its f64 components.)
2496 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2497 Align = OrigVT.getStoreSize();
2499 Align = ArgVT.getStoreSize();
2505 /// CalculateStackSlotUsed - Return whether this argument will use its
2506 /// stack slot (instead of being passed in registers). ArgOffset,
2507 /// AvailableFPRs, and AvailableVRs must hold the current argument
2508 /// position, and will be updated to account for this argument.
2509 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2510 ISD::ArgFlagsTy Flags,
2511 unsigned PtrByteSize,
2512 unsigned LinkageSize,
2513 unsigned ParamAreaSize,
2514 unsigned &ArgOffset,
2515 unsigned &AvailableFPRs,
2516 unsigned &AvailableVRs, bool HasQPX) {
2517 bool UseMemory = false;
2519 // Respect alignment of argument on the stack.
2521 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2522 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2523 // If there's no space left in the argument save area, we must
2524 // use memory (this check also catches zero-sized arguments).
2525 if (ArgOffset >= LinkageSize + ParamAreaSize)
2528 // Allocate argument on the stack.
2529 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2530 if (Flags.isInConsecutiveRegsLast())
2531 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2532 // If we overran the argument save area, we must use memory
2533 // (this check catches arguments passed partially in memory)
2534 if (ArgOffset > LinkageSize + ParamAreaSize)
2537 // However, if the argument is actually passed in an FPR or a VR,
2538 // we don't use memory after all.
2539 if (!Flags.isByVal()) {
2540 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2541 // QPX registers overlap with the scalar FP registers.
2542 (HasQPX && (ArgVT == MVT::v4f32 ||
2543 ArgVT == MVT::v4f64 ||
2544 ArgVT == MVT::v4i1)))
2545 if (AvailableFPRs > 0) {
2549 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2550 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2551 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2552 if (AvailableVRs > 0) {
2561 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2562 /// ensure minimum alignment required for target.
2563 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2564 unsigned NumBytes) {
2565 unsigned TargetAlign = Lowering->getStackAlignment();
2566 unsigned AlignMask = TargetAlign - 1;
2567 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2572 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2573 CallingConv::ID CallConv, bool isVarArg,
2574 const SmallVectorImpl<ISD::InputArg>
2576 SDLoc dl, SelectionDAG &DAG,
2577 SmallVectorImpl<SDValue> &InVals)
2579 if (Subtarget.isSVR4ABI()) {
2580 if (Subtarget.isPPC64())
2581 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2584 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2587 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2593 PPCTargetLowering::LowerFormalArguments_32SVR4(
2595 CallingConv::ID CallConv, bool isVarArg,
2596 const SmallVectorImpl<ISD::InputArg>
2598 SDLoc dl, SelectionDAG &DAG,
2599 SmallVectorImpl<SDValue> &InVals) const {
2601 // 32-bit SVR4 ABI Stack Frame Layout:
2602 // +-----------------------------------+
2603 // +--> | Back chain |
2604 // | +-----------------------------------+
2605 // | | Floating-point register save area |
2606 // | +-----------------------------------+
2607 // | | General register save area |
2608 // | +-----------------------------------+
2609 // | | CR save word |
2610 // | +-----------------------------------+
2611 // | | VRSAVE save word |
2612 // | +-----------------------------------+
2613 // | | Alignment padding |
2614 // | +-----------------------------------+
2615 // | | Vector register save area |
2616 // | +-----------------------------------+
2617 // | | Local variable space |
2618 // | +-----------------------------------+
2619 // | | Parameter list area |
2620 // | +-----------------------------------+
2621 // | | LR save word |
2622 // | +-----------------------------------+
2623 // SP--> +--- | Back chain |
2624 // +-----------------------------------+
2627 // System V Application Binary Interface PowerPC Processor Supplement
2628 // AltiVec Technology Programming Interface Manual
2630 MachineFunction &MF = DAG.getMachineFunction();
2631 MachineFrameInfo *MFI = MF.getFrameInfo();
2632 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2634 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2635 // Potential tail calls could cause overwriting of argument stack slots.
2636 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2637 (CallConv == CallingConv::Fast));
2638 unsigned PtrByteSize = 4;
2640 // Assign locations to all of the incoming arguments.
2641 SmallVector<CCValAssign, 16> ArgLocs;
2642 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2645 // Reserve space for the linkage area on the stack.
2646 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2647 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2649 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2651 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2652 CCValAssign &VA = ArgLocs[i];
2654 // Arguments stored in registers.
2655 if (VA.isRegLoc()) {
2656 const TargetRegisterClass *RC;
2657 EVT ValVT = VA.getValVT();
2659 switch (ValVT.getSimpleVT().SimpleTy) {
2661 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2664 RC = &PPC::GPRCRegClass;
2667 RC = &PPC::F4RCRegClass;
2670 if (Subtarget.hasVSX())
2671 RC = &PPC::VSFRCRegClass;
2673 RC = &PPC::F8RCRegClass;
2678 RC = &PPC::VRRCRegClass;
2681 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2685 RC = &PPC::VSHRCRegClass;
2688 RC = &PPC::QFRCRegClass;
2691 RC = &PPC::QBRCRegClass;
2695 // Transform the arguments stored in physical registers into virtual ones.
2696 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2697 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2698 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2700 if (ValVT == MVT::i1)
2701 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2703 InVals.push_back(ArgValue);
2705 // Argument stored in memory.
2706 assert(VA.isMemLoc());
2708 unsigned ArgSize = VA.getLocVT().getStoreSize();
2709 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2712 // Create load nodes to retrieve arguments from the stack.
2713 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2714 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2715 MachinePointerInfo(),
2716 false, false, false, 0));
2720 // Assign locations to all of the incoming aggregate by value arguments.
2721 // Aggregates passed by value are stored in the local variable space of the
2722 // caller's stack frame, right above the parameter list area.
2723 SmallVector<CCValAssign, 16> ByValArgLocs;
2724 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2725 ByValArgLocs, *DAG.getContext());
2727 // Reserve stack space for the allocations in CCInfo.
2728 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2730 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2732 // Area that is at least reserved in the caller of this function.
2733 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2734 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2736 // Set the size that is at least reserved in caller of this function. Tail
2737 // call optimized function's reserved stack space needs to be aligned so that
2738 // taking the difference between two stack areas will result in an aligned
2741 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2742 FuncInfo->setMinReservedArea(MinReservedArea);
2744 SmallVector<SDValue, 8> MemOps;
2746 // If the function takes variable number of arguments, make a frame index for
2747 // the start of the first vararg value... for expansion of llvm.va_start.
2749 static const MCPhysReg GPArgRegs[] = {
2750 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2751 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2753 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2755 static const MCPhysReg FPArgRegs[] = {
2756 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2759 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2760 if (DisablePPCFloatInVariadic)
2763 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2764 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2766 // Make room for NumGPArgRegs and NumFPArgRegs.
2767 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2768 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2770 FuncInfo->setVarArgsStackOffset(
2771 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2772 CCInfo.getNextStackOffset(), true));
2774 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2775 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2777 // The fixed integer arguments of a variadic function are stored to the
2778 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2779 // the result of va_next.
2780 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2781 // Get an existing live-in vreg, or add a new one.
2782 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2784 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2786 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2787 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2788 MachinePointerInfo(), false, false, 0);
2789 MemOps.push_back(Store);
2790 // Increment the address by four for the next argument to store
2791 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2792 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2795 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2797 // The double arguments are stored to the VarArgsFrameIndex
2799 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2800 // Get an existing live-in vreg, or add a new one.
2801 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2803 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2805 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2806 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2807 MachinePointerInfo(), false, false, 0);
2808 MemOps.push_back(Store);
2809 // Increment the address by eight for the next argument to store
2810 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2812 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2816 if (!MemOps.empty())
2817 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2822 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2823 // value to MVT::i64 and then truncate to the correct register size.
2825 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2826 SelectionDAG &DAG, SDValue ArgVal,
2829 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2830 DAG.getValueType(ObjectVT));
2831 else if (Flags.isZExt())
2832 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2833 DAG.getValueType(ObjectVT));
2835 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2839 PPCTargetLowering::LowerFormalArguments_64SVR4(
2841 CallingConv::ID CallConv, bool isVarArg,
2842 const SmallVectorImpl<ISD::InputArg>
2844 SDLoc dl, SelectionDAG &DAG,
2845 SmallVectorImpl<SDValue> &InVals) const {
2846 // TODO: add description of PPC stack frame format, or at least some docs.
2848 bool isELFv2ABI = Subtarget.isELFv2ABI();
2849 bool isLittleEndian = Subtarget.isLittleEndian();
2850 MachineFunction &MF = DAG.getMachineFunction();
2851 MachineFrameInfo *MFI = MF.getFrameInfo();
2852 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2854 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2855 "fastcc not supported on varargs functions");
2857 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2858 // Potential tail calls could cause overwriting of argument stack slots.
2859 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2860 (CallConv == CallingConv::Fast));
2861 unsigned PtrByteSize = 8;
2862 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2864 static const MCPhysReg GPR[] = {
2865 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2866 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2868 static const MCPhysReg VR[] = {
2869 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2870 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2872 static const MCPhysReg VSRH[] = {
2873 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2874 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2877 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2878 const unsigned Num_FPR_Regs = 13;
2879 const unsigned Num_VR_Regs = array_lengthof(VR);
2880 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2882 // Do a first pass over the arguments to determine whether the ABI
2883 // guarantees that our caller has allocated the parameter save area
2884 // on its stack frame. In the ELFv1 ABI, this is always the case;
2885 // in the ELFv2 ABI, it is true if this is a vararg function or if
2886 // any parameter is located in a stack slot.
2888 bool HasParameterArea = !isELFv2ABI || isVarArg;
2889 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2890 unsigned NumBytes = LinkageSize;
2891 unsigned AvailableFPRs = Num_FPR_Regs;
2892 unsigned AvailableVRs = Num_VR_Regs;
2893 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2894 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2895 PtrByteSize, LinkageSize, ParamAreaSize,
2896 NumBytes, AvailableFPRs, AvailableVRs,
2897 Subtarget.hasQPX()))
2898 HasParameterArea = true;
2900 // Add DAG nodes to load the arguments or copy them out of registers. On
2901 // entry to a function on PPC, the arguments start after the linkage area,
2902 // although the first ones are often in registers.
2904 unsigned ArgOffset = LinkageSize;
2905 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2906 unsigned &QFPR_idx = FPR_idx;
2907 SmallVector<SDValue, 8> MemOps;
2908 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2909 unsigned CurArgIdx = 0;
2910 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2912 bool needsLoad = false;
2913 EVT ObjectVT = Ins[ArgNo].VT;
2914 EVT OrigVT = Ins[ArgNo].ArgVT;
2915 unsigned ObjSize = ObjectVT.getStoreSize();
2916 unsigned ArgSize = ObjSize;
2917 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2918 if (Ins[ArgNo].isOrigArg()) {
2919 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2920 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2922 // We re-align the argument offset for each argument, except when using the
2923 // fast calling convention, when we need to make sure we do that only when
2924 // we'll actually use a stack slot.
2925 unsigned CurArgOffset, Align;
2926 auto ComputeArgOffset = [&]() {
2927 /* Respect alignment of argument on the stack. */
2928 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2929 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2930 CurArgOffset = ArgOffset;
2933 if (CallConv != CallingConv::Fast) {
2936 /* Compute GPR index associated with argument offset. */
2937 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2938 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2941 // FIXME the codegen can be much improved in some cases.
2942 // We do not have to keep everything in memory.
2943 if (Flags.isByVal()) {
2944 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2946 if (CallConv == CallingConv::Fast)
2949 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2950 ObjSize = Flags.getByValSize();
2951 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2952 // Empty aggregate parameters do not take up registers. Examples:
2956 // etc. However, we have to provide a place-holder in InVals, so
2957 // pretend we have an 8-byte item at the current address for that
2960 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2961 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2962 InVals.push_back(FIN);
2966 // Create a stack object covering all stack doublewords occupied
2967 // by the argument. If the argument is (fully or partially) on
2968 // the stack, or if the argument is fully in registers but the
2969 // caller has allocated the parameter save anyway, we can refer
2970 // directly to the caller's stack frame. Otherwise, create a
2971 // local copy in our own frame.
2973 if (HasParameterArea ||
2974 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2975 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2977 FI = MFI->CreateStackObject(ArgSize, Align, false);
2978 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2980 // Handle aggregates smaller than 8 bytes.
2981 if (ObjSize < PtrByteSize) {
2982 // The value of the object is its address, which differs from the
2983 // address of the enclosing doubleword on big-endian systems.
2985 if (!isLittleEndian) {
2986 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2987 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2989 InVals.push_back(Arg);
2991 if (GPR_idx != Num_GPR_Regs) {
2992 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2993 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2996 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2997 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2998 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2999 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3000 MachinePointerInfo(FuncArg),
3001 ObjType, false, false, 0);
3003 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3004 // store the whole register as-is to the parameter save area
3006 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3007 MachinePointerInfo(FuncArg),
3011 MemOps.push_back(Store);
3013 // Whether we copied from a register or not, advance the offset
3014 // into the parameter save area by a full doubleword.
3015 ArgOffset += PtrByteSize;
3019 // The value of the object is its address, which is the address of
3020 // its first stack doubleword.
3021 InVals.push_back(FIN);
3023 // Store whatever pieces of the object are in registers to memory.
3024 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3025 if (GPR_idx == Num_GPR_Regs)
3028 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3029 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3032 SDValue Off = DAG.getConstant(j, PtrVT);
3033 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3035 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3036 MachinePointerInfo(FuncArg, j),
3038 MemOps.push_back(Store);
3041 ArgOffset += ArgSize;
3045 switch (ObjectVT.getSimpleVT().SimpleTy) {
3046 default: llvm_unreachable("Unhandled argument type!");
3050 // These can be scalar arguments or elements of an integer array type
3051 // passed directly. Clang may use those instead of "byval" aggregate
3052 // types to avoid forcing arguments to memory unnecessarily.
3053 if (GPR_idx != Num_GPR_Regs) {
3054 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3055 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3057 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3058 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3059 // value to MVT::i64 and then truncate to the correct register size.
3060 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3062 if (CallConv == CallingConv::Fast)
3066 ArgSize = PtrByteSize;
3068 if (CallConv != CallingConv::Fast || needsLoad)
3074 // These can be scalar arguments or elements of a float array type
3075 // passed directly. The latter are used to implement ELFv2 homogenous
3076 // float aggregates.
3077 if (FPR_idx != Num_FPR_Regs) {
3080 if (ObjectVT == MVT::f32)
3081 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3083 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3084 ? &PPC::VSFRCRegClass
3085 : &PPC::F8RCRegClass);
3087 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3089 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3090 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3091 // once we support fp <-> gpr moves.
3093 // This can only ever happen in the presence of f32 array types,
3094 // since otherwise we never run out of FPRs before running out
3096 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3097 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3099 if (ObjectVT == MVT::f32) {
3100 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3101 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3102 DAG.getConstant(32, MVT::i32));
3103 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3106 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3108 if (CallConv == CallingConv::Fast)
3114 // When passing an array of floats, the array occupies consecutive
3115 // space in the argument area; only round up to the next doubleword
3116 // at the end of the array. Otherwise, each float takes 8 bytes.
3117 if (CallConv != CallingConv::Fast || needsLoad) {
3118 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3119 ArgOffset += ArgSize;
3120 if (Flags.isInConsecutiveRegsLast())
3121 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3130 if (!Subtarget.hasQPX()) {
3131 // These can be scalar arguments or elements of a vector array type
3132 // passed directly. The latter are used to implement ELFv2 homogenous
3133 // vector aggregates.
3134 if (VR_idx != Num_VR_Regs) {
3135 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3136 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3137 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3138 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3141 if (CallConv == CallingConv::Fast)
3146 if (CallConv != CallingConv::Fast || needsLoad)
3151 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3152 "Invalid QPX parameter type");
3157 // QPX vectors are treated like their scalar floating-point subregisters
3158 // (except that they're larger).
3159 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3160 if (QFPR_idx != Num_QFPR_Regs) {
3161 const TargetRegisterClass *RC;
3162 switch (ObjectVT.getSimpleVT().SimpleTy) {
3163 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3164 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3165 default: RC = &PPC::QBRCRegClass; break;
3168 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3169 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3172 if (CallConv == CallingConv::Fast)
3176 if (CallConv != CallingConv::Fast || needsLoad)
3181 // We need to load the argument to a virtual register if we determined
3182 // above that we ran out of physical registers of the appropriate type.
3184 if (ObjSize < ArgSize && !isLittleEndian)
3185 CurArgOffset += ArgSize - ObjSize;
3186 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3187 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3188 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3189 false, false, false, 0);
3192 InVals.push_back(ArgVal);
3195 // Area that is at least reserved in the caller of this function.
3196 unsigned MinReservedArea;
3197 if (HasParameterArea)
3198 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3200 MinReservedArea = LinkageSize;
3202 // Set the size that is at least reserved in caller of this function. Tail
3203 // call optimized functions' reserved stack space needs to be aligned so that
3204 // taking the difference between two stack areas will result in an aligned
3207 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3208 FuncInfo->setMinReservedArea(MinReservedArea);
3210 // If the function takes variable number of arguments, make a frame index for
3211 // the start of the first vararg value... for expansion of llvm.va_start.
3213 int Depth = ArgOffset;
3215 FuncInfo->setVarArgsFrameIndex(
3216 MFI->CreateFixedObject(PtrByteSize, Depth, true));
3217 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3219 // If this function is vararg, store any remaining integer argument regs
3220 // to their spots on the stack so that they may be loaded by deferencing the
3221 // result of va_next.
3222 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3223 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3224 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3225 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3226 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3227 MachinePointerInfo(), false, false, 0);
3228 MemOps.push_back(Store);
3229 // Increment the address by four for the next argument to store
3230 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3231 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3235 if (!MemOps.empty())
3236 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3242 PPCTargetLowering::LowerFormalArguments_Darwin(
3244 CallingConv::ID CallConv, bool isVarArg,
3245 const SmallVectorImpl<ISD::InputArg>
3247 SDLoc dl, SelectionDAG &DAG,
3248 SmallVectorImpl<SDValue> &InVals) const {
3249 // TODO: add description of PPC stack frame format, or at least some docs.
3251 MachineFunction &MF = DAG.getMachineFunction();
3252 MachineFrameInfo *MFI = MF.getFrameInfo();
3253 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3255 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3256 bool isPPC64 = PtrVT == MVT::i64;
3257 // Potential tail calls could cause overwriting of argument stack slots.
3258 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3259 (CallConv == CallingConv::Fast));
3260 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3261 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3262 unsigned ArgOffset = LinkageSize;
3263 // Area that is at least reserved in caller of this function.
3264 unsigned MinReservedArea = ArgOffset;
3266 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3267 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3268 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3270 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3271 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3272 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3274 static const MCPhysReg VR[] = {
3275 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3276 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3279 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3280 const unsigned Num_FPR_Regs = 13;
3281 const unsigned Num_VR_Regs = array_lengthof( VR);
3283 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3285 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3287 // In 32-bit non-varargs functions, the stack space for vectors is after the
3288 // stack space for non-vectors. We do not use this space unless we have
3289 // too many vectors to fit in registers, something that only occurs in
3290 // constructed examples:), but we have to walk the arglist to figure
3291 // that out...for the pathological case, compute VecArgOffset as the
3292 // start of the vector parameter area. Computing VecArgOffset is the
3293 // entire point of the following loop.
3294 unsigned VecArgOffset = ArgOffset;
3295 if (!isVarArg && !isPPC64) {
3296 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3298 EVT ObjectVT = Ins[ArgNo].VT;
3299 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3301 if (Flags.isByVal()) {
3302 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3303 unsigned ObjSize = Flags.getByValSize();
3305 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3306 VecArgOffset += ArgSize;
3310 switch(ObjectVT.getSimpleVT().SimpleTy) {
3311 default: llvm_unreachable("Unhandled argument type!");
3317 case MVT::i64: // PPC64
3319 // FIXME: We are guaranteed to be !isPPC64 at this point.
3320 // Does MVT::i64 apply?
3327 // Nothing to do, we're only looking at Nonvector args here.
3332 // We've found where the vector parameter area in memory is. Skip the
3333 // first 12 parameters; these don't use that memory.
3334 VecArgOffset = ((VecArgOffset+15)/16)*16;
3335 VecArgOffset += 12*16;
3337 // Add DAG nodes to load the arguments or copy them out of registers. On
3338 // entry to a function on PPC, the arguments start after the linkage area,
3339 // although the first ones are often in registers.
3341 SmallVector<SDValue, 8> MemOps;
3342 unsigned nAltivecParamsAtEnd = 0;
3343 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3344 unsigned CurArgIdx = 0;
3345 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3347 bool needsLoad = false;
3348 EVT ObjectVT = Ins[ArgNo].VT;
3349 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3350 unsigned ArgSize = ObjSize;
3351 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3352 if (Ins[ArgNo].isOrigArg()) {
3353 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3354 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3356 unsigned CurArgOffset = ArgOffset;
3358 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3359 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3360 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3361 if (isVarArg || isPPC64) {
3362 MinReservedArea = ((MinReservedArea+15)/16)*16;
3363 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3366 } else nAltivecParamsAtEnd++;
3368 // Calculate min reserved area.
3369 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3373 // FIXME the codegen can be much improved in some cases.
3374 // We do not have to keep everything in memory.
3375 if (Flags.isByVal()) {
3376 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3378 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3379 ObjSize = Flags.getByValSize();
3380 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3381 // Objects of size 1 and 2 are right justified, everything else is
3382 // left justified. This means the memory address is adjusted forwards.
3383 if (ObjSize==1 || ObjSize==2) {
3384 CurArgOffset = CurArgOffset + (4 - ObjSize);
3386 // The value of the object is its address.
3387 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3388 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3389 InVals.push_back(FIN);
3390 if (ObjSize==1 || ObjSize==2) {
3391 if (GPR_idx != Num_GPR_Regs) {
3394 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3396 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3397 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3398 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3399 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3400 MachinePointerInfo(FuncArg),
3401 ObjType, false, false, 0);
3402 MemOps.push_back(Store);
3406 ArgOffset += PtrByteSize;
3410 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3411 // Store whatever pieces of the object are in registers
3412 // to memory. ArgOffset will be the address of the beginning
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 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3421 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3422 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3423 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3424 MachinePointerInfo(FuncArg, j),
3426 MemOps.push_back(Store);
3428 ArgOffset += PtrByteSize;
3430 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3437 switch (ObjectVT.getSimpleVT().SimpleTy) {
3438 default: llvm_unreachable("Unhandled argument type!");
3442 if (GPR_idx != Num_GPR_Regs) {
3443 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3444 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3446 if (ObjectVT == MVT::i1)
3447 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3452 ArgSize = PtrByteSize;
3454 // All int arguments reserve stack space in the Darwin ABI.
3455 ArgOffset += PtrByteSize;
3459 case MVT::i64: // PPC64
3460 if (GPR_idx != Num_GPR_Regs) {
3461 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3462 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3464 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3465 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3466 // value to MVT::i64 and then truncate to the correct register size.
3467 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3472 ArgSize = PtrByteSize;
3474 // All int arguments reserve stack space in the Darwin ABI.
3480 // Every 4 bytes of argument space consumes one of the GPRs available for
3481 // argument passing.
3482 if (GPR_idx != Num_GPR_Regs) {
3484 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3487 if (FPR_idx != Num_FPR_Regs) {
3490 if (ObjectVT == MVT::f32)
3491 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3493 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3495 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3501 // All FP arguments reserve stack space in the Darwin ABI.
3502 ArgOffset += isPPC64 ? 8 : ObjSize;
3508 // Note that vector arguments in registers don't reserve stack space,
3509 // except in varargs functions.
3510 if (VR_idx != Num_VR_Regs) {
3511 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3512 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3514 while ((ArgOffset % 16) != 0) {
3515 ArgOffset += PtrByteSize;
3516 if (GPR_idx != Num_GPR_Regs)
3520 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3524 if (!isVarArg && !isPPC64) {
3525 // Vectors go after all the nonvectors.
3526 CurArgOffset = VecArgOffset;
3529 // Vectors are aligned.
3530 ArgOffset = ((ArgOffset+15)/16)*16;
3531 CurArgOffset = ArgOffset;
3539 // We need to load the argument to a virtual register if we determined above
3540 // that we ran out of physical registers of the appropriate type.
3542 int FI = MFI->CreateFixedObject(ObjSize,
3543 CurArgOffset + (ArgSize - ObjSize),
3545 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3546 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3547 false, false, false, 0);
3550 InVals.push_back(ArgVal);
3553 // Allow for Altivec parameters at the end, if needed.
3554 if (nAltivecParamsAtEnd) {
3555 MinReservedArea = ((MinReservedArea+15)/16)*16;
3556 MinReservedArea += 16*nAltivecParamsAtEnd;
3559 // Area that is at least reserved in the caller of this function.
3560 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3562 // Set the size that is at least reserved in caller of this function. Tail
3563 // call optimized functions' reserved stack space needs to be aligned so that
3564 // taking the difference between two stack areas will result in an aligned
3567 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3568 FuncInfo->setMinReservedArea(MinReservedArea);
3570 // If the function takes variable number of arguments, make a frame index for
3571 // the start of the first vararg value... for expansion of llvm.va_start.
3573 int Depth = ArgOffset;
3575 FuncInfo->setVarArgsFrameIndex(
3576 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3578 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3580 // If this function is vararg, store any remaining integer argument regs
3581 // to their spots on the stack so that they may be loaded by deferencing the
3582 // result of va_next.
3583 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3587 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3589 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3591 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3592 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3593 MachinePointerInfo(), false, false, 0);
3594 MemOps.push_back(Store);
3595 // Increment the address by four for the next argument to store
3596 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3597 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3601 if (!MemOps.empty())
3602 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3607 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3608 /// adjusted to accommodate the arguments for the tailcall.
3609 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3610 unsigned ParamSize) {
3612 if (!isTailCall) return 0;
3614 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3615 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3616 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3617 // Remember only if the new adjustement is bigger.
3618 if (SPDiff < FI->getTailCallSPDelta())
3619 FI->setTailCallSPDelta(SPDiff);
3624 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3625 /// for tail call optimization. Targets which want to do tail call
3626 /// optimization should implement this function.
3628 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3629 CallingConv::ID CalleeCC,
3631 const SmallVectorImpl<ISD::InputArg> &Ins,
3632 SelectionDAG& DAG) const {
3633 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3636 // Variable argument functions are not supported.
3640 MachineFunction &MF = DAG.getMachineFunction();
3641 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3642 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3643 // Functions containing by val parameters are not supported.
3644 for (unsigned i = 0; i != Ins.size(); i++) {
3645 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3646 if (Flags.isByVal()) return false;
3649 // Non-PIC/GOT tail calls are supported.
3650 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3653 // At the moment we can only do local tail calls (in same module, hidden
3654 // or protected) if we are generating PIC.
3655 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3656 return G->getGlobal()->hasHiddenVisibility()
3657 || G->getGlobal()->hasProtectedVisibility();
3663 /// isCallCompatibleAddress - Return the immediate to use if the specified
3664 /// 32-bit value is representable in the immediate field of a BxA instruction.
3665 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3666 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3667 if (!C) return nullptr;
3669 int Addr = C->getZExtValue();
3670 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3671 SignExtend32<26>(Addr) != Addr)
3672 return nullptr; // Top 6 bits have to be sext of immediate.
3674 return DAG.getConstant((int)C->getZExtValue() >> 2,
3675 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3680 struct TailCallArgumentInfo {
3685 TailCallArgumentInfo() : FrameIdx(0) {}
3690 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3692 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3694 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3695 SmallVectorImpl<SDValue> &MemOpChains,
3697 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3698 SDValue Arg = TailCallArgs[i].Arg;
3699 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3700 int FI = TailCallArgs[i].FrameIdx;
3701 // Store relative to framepointer.
3702 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3703 MachinePointerInfo::getFixedStack(FI),
3708 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3709 /// the appropriate stack slot for the tail call optimized function call.
3710 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3711 MachineFunction &MF,
3720 // Calculate the new stack slot for the return address.
3721 int SlotSize = isPPC64 ? 8 : 4;
3722 const PPCFrameLowering *FL =
3723 MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3724 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3725 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3726 NewRetAddrLoc, true);
3727 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3728 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3729 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3730 MachinePointerInfo::getFixedStack(NewRetAddr),
3733 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3734 // slot as the FP is never overwritten.
3736 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3737 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3739 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3740 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3741 MachinePointerInfo::getFixedStack(NewFPIdx),
3748 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3749 /// the position of the argument.
3751 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3752 SDValue Arg, int SPDiff, unsigned ArgOffset,
3753 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3754 int Offset = ArgOffset + SPDiff;
3755 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3756 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3757 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3758 SDValue FIN = DAG.getFrameIndex(FI, VT);
3759 TailCallArgumentInfo Info;
3761 Info.FrameIdxOp = FIN;
3763 TailCallArguments.push_back(Info);
3766 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3767 /// stack slot. Returns the chain as result and the loaded frame pointers in
3768 /// LROpOut/FPOpout. Used when tail calling.
3769 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3777 // Load the LR and FP stack slot for later adjusting.
3778 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3779 LROpOut = getReturnAddrFrameIndex(DAG);
3780 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3781 false, false, false, 0);
3782 Chain = SDValue(LROpOut.getNode(), 1);
3784 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3785 // slot as the FP is never overwritten.
3787 FPOpOut = getFramePointerFrameIndex(DAG);
3788 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3789 false, false, false, 0);
3790 Chain = SDValue(FPOpOut.getNode(), 1);
3796 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3797 /// by "Src" to address "Dst" of size "Size". Alignment information is
3798 /// specified by the specific parameter attribute. The copy will be passed as
3799 /// a byval function parameter.
3800 /// Sometimes what we are copying is the end of a larger object, the part that
3801 /// does not fit in registers.
3803 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3804 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3806 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3807 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3808 false, false, MachinePointerInfo(),
3809 MachinePointerInfo());
3812 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3815 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3816 SDValue Arg, SDValue PtrOff, int SPDiff,
3817 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3818 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3819 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3821 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3826 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3828 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3829 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3830 DAG.getConstant(ArgOffset, PtrVT));
3832 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3833 MachinePointerInfo(), false, false, 0));
3834 // Calculate and remember argument location.
3835 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3840 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3841 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3842 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3843 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3844 MachineFunction &MF = DAG.getMachineFunction();
3846 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3847 // might overwrite each other in case of tail call optimization.
3848 SmallVector<SDValue, 8> MemOpChains2;
3849 // Do not flag preceding copytoreg stuff together with the following stuff.
3851 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3853 if (!MemOpChains2.empty())
3854 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3856 // Store the return address to the appropriate stack slot.
3857 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3858 isPPC64, isDarwinABI, dl);
3860 // Emit callseq_end just before tailcall node.
3861 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3862 DAG.getIntPtrConstant(0, true), InFlag, dl);
3863 InFlag = Chain.getValue(1);
3866 // Is this global address that of a function that can be called by name? (as
3867 // opposed to something that must hold a descriptor for an indirect call).
3868 static bool isFunctionGlobalAddress(SDValue Callee) {
3869 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3870 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3871 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3874 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3881 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3882 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3883 bool isTailCall, bool IsPatchPoint,
3884 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3885 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3886 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3888 bool isPPC64 = Subtarget.isPPC64();
3889 bool isSVR4ABI = Subtarget.isSVR4ABI();
3890 bool isELFv2ABI = Subtarget.isELFv2ABI();
3892 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3893 NodeTys.push_back(MVT::Other); // Returns a chain
3894 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3896 unsigned CallOpc = PPCISD::CALL;
3898 bool needIndirectCall = true;
3899 if (!isSVR4ABI || !isPPC64)
3900 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3901 // If this is an absolute destination address, use the munged value.
3902 Callee = SDValue(Dest, 0);
3903 needIndirectCall = false;
3906 if (isFunctionGlobalAddress(Callee)) {
3907 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3908 // A call to a TLS address is actually an indirect call to a
3909 // thread-specific pointer.
3910 unsigned OpFlags = 0;
3911 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3912 (Subtarget.getTargetTriple().isMacOSX() &&
3913 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3914 (G->getGlobal()->isDeclaration() ||
3915 G->getGlobal()->isWeakForLinker())) ||
3916 (Subtarget.isTargetELF() && !isPPC64 &&
3917 !G->getGlobal()->hasLocalLinkage() &&
3918 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3919 // PC-relative references to external symbols should go through $stub,
3920 // unless we're building with the leopard linker or later, which
3921 // automatically synthesizes these stubs.
3922 OpFlags = PPCII::MO_PLT_OR_STUB;
3925 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3926 // every direct call is) turn it into a TargetGlobalAddress /
3927 // TargetExternalSymbol node so that legalize doesn't hack it.
3928 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3929 Callee.getValueType(), 0, OpFlags);
3930 needIndirectCall = false;
3933 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3934 unsigned char OpFlags = 0;
3936 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3937 (Subtarget.getTargetTriple().isMacOSX() &&
3938 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3939 (Subtarget.isTargetELF() && !isPPC64 &&
3940 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3941 // PC-relative references to external symbols should go through $stub,
3942 // unless we're building with the leopard linker or later, which
3943 // automatically synthesizes these stubs.
3944 OpFlags = PPCII::MO_PLT_OR_STUB;
3947 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3949 needIndirectCall = false;
3953 // We'll form an invalid direct call when lowering a patchpoint; the full
3954 // sequence for an indirect call is complicated, and many of the
3955 // instructions introduced might have side effects (and, thus, can't be
3956 // removed later). The call itself will be removed as soon as the
3957 // argument/return lowering is complete, so the fact that it has the wrong
3958 // kind of operands should not really matter.
3959 needIndirectCall = false;
3962 if (needIndirectCall) {
3963 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3964 // to do the call, we can't use PPCISD::CALL.
3965 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3967 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3968 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3969 // entry point, but to the function descriptor (the function entry point
3970 // address is part of the function descriptor though).
3971 // The function descriptor is a three doubleword structure with the
3972 // following fields: function entry point, TOC base address and
3973 // environment pointer.
3974 // Thus for a call through a function pointer, the following actions need
3976 // 1. Save the TOC of the caller in the TOC save area of its stack
3977 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3978 // 2. Load the address of the function entry point from the function
3980 // 3. Load the TOC of the callee from the function descriptor into r2.
3981 // 4. Load the environment pointer from the function descriptor into
3983 // 5. Branch to the function entry point address.
3984 // 6. On return of the callee, the TOC of the caller needs to be
3985 // restored (this is done in FinishCall()).
3987 // The loads are scheduled at the beginning of the call sequence, and the
3988 // register copies are flagged together to ensure that no other
3989 // operations can be scheduled in between. E.g. without flagging the
3990 // copies together, a TOC access in the caller could be scheduled between
3991 // the assignment of the callee TOC and the branch to the callee, which
3992 // results in the TOC access going through the TOC of the callee instead
3993 // of going through the TOC of the caller, which leads to incorrect code.
3995 // Load the address of the function entry point from the function
3997 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
3998 if (LDChain.getValueType() == MVT::Glue)
3999 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4001 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4003 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4004 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4005 false, false, LoadsInv, 8);
4007 // Load environment pointer into r11.
4008 SDValue PtrOff = DAG.getIntPtrConstant(16);
4009 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4010 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4011 MPI.getWithOffset(16), false, false,
4014 SDValue TOCOff = DAG.getIntPtrConstant(8);
4015 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4016 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4017 MPI.getWithOffset(8), false, false,
4020 setUsesTOCBasePtr(DAG);
4021 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4023 Chain = TOCVal.getValue(0);
4024 InFlag = TOCVal.getValue(1);
4026 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4029 Chain = EnvVal.getValue(0);
4030 InFlag = EnvVal.getValue(1);
4032 MTCTROps[0] = Chain;
4033 MTCTROps[1] = LoadFuncPtr;
4034 MTCTROps[2] = InFlag;
4037 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4038 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4039 InFlag = Chain.getValue(1);
4042 NodeTys.push_back(MVT::Other);
4043 NodeTys.push_back(MVT::Glue);
4044 Ops.push_back(Chain);
4045 CallOpc = PPCISD::BCTRL;
4046 Callee.setNode(nullptr);
4047 // Add use of X11 (holding environment pointer)
4048 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4049 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4050 // Add CTR register as callee so a bctr can be emitted later.
4052 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4055 // If this is a direct call, pass the chain and the callee.
4056 if (Callee.getNode()) {
4057 Ops.push_back(Chain);
4058 Ops.push_back(Callee);
4060 // If this is a tail call add stack pointer delta.
4062 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4064 // Add argument registers to the end of the list so that they are known live
4066 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4067 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4068 RegsToPass[i].second.getValueType()));
4070 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4072 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4073 setUsesTOCBasePtr(DAG);
4074 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4081 bool isLocalCall(const SDValue &Callee)
4083 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4084 return !G->getGlobal()->isDeclaration() &&
4085 !G->getGlobal()->isWeakForLinker();
4090 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4091 CallingConv::ID CallConv, bool isVarArg,
4092 const SmallVectorImpl<ISD::InputArg> &Ins,
4093 SDLoc dl, SelectionDAG &DAG,
4094 SmallVectorImpl<SDValue> &InVals) const {
4096 SmallVector<CCValAssign, 16> RVLocs;
4097 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4099 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4101 // Copy all of the result registers out of their specified physreg.
4102 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4103 CCValAssign &VA = RVLocs[i];
4104 assert(VA.isRegLoc() && "Can only return in registers!");
4106 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4107 VA.getLocReg(), VA.getLocVT(), InFlag);
4108 Chain = Val.getValue(1);
4109 InFlag = Val.getValue(2);
4111 switch (VA.getLocInfo()) {
4112 default: llvm_unreachable("Unknown loc info!");
4113 case CCValAssign::Full: break;
4114 case CCValAssign::AExt:
4115 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4117 case CCValAssign::ZExt:
4118 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4119 DAG.getValueType(VA.getValVT()));
4120 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4122 case CCValAssign::SExt:
4123 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4124 DAG.getValueType(VA.getValVT()));
4125 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4129 InVals.push_back(Val);
4136 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4137 bool isTailCall, bool isVarArg, bool IsPatchPoint,
4139 SmallVector<std::pair<unsigned, SDValue>, 8>
4141 SDValue InFlag, SDValue Chain,
4142 SDValue CallSeqStart, SDValue &Callee,
4143 int SPDiff, unsigned NumBytes,
4144 const SmallVectorImpl<ISD::InputArg> &Ins,
4145 SmallVectorImpl<SDValue> &InVals,
4146 ImmutableCallSite *CS) const {
4148 std::vector<EVT> NodeTys;
4149 SmallVector<SDValue, 8> Ops;
4150 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4151 SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4152 Ops, NodeTys, CS, Subtarget);
4154 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4155 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4156 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4158 // When performing tail call optimization the callee pops its arguments off
4159 // the stack. Account for this here so these bytes can be pushed back on in
4160 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4161 int BytesCalleePops =
4162 (CallConv == CallingConv::Fast &&
4163 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4165 // Add a register mask operand representing the call-preserved registers.
4166 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4167 const uint32_t *Mask =
4168 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4169 assert(Mask && "Missing call preserved mask for calling convention");
4170 Ops.push_back(DAG.getRegisterMask(Mask));
4172 if (InFlag.getNode())
4173 Ops.push_back(InFlag);
4177 assert(((Callee.getOpcode() == ISD::Register &&
4178 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4179 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4180 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4181 isa<ConstantSDNode>(Callee)) &&
4182 "Expecting an global address, external symbol, absolute value or register");
4184 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4187 // Add a NOP immediately after the branch instruction when using the 64-bit
4188 // SVR4 ABI. At link time, if caller and callee are in a different module and
4189 // thus have a different TOC, the call will be replaced with a call to a stub
4190 // function which saves the current TOC, loads the TOC of the callee and
4191 // branches to the callee. The NOP will be replaced with a load instruction
4192 // which restores the TOC of the caller from the TOC save slot of the current
4193 // stack frame. If caller and callee belong to the same module (and have the
4194 // same TOC), the NOP will remain unchanged.
4196 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4198 if (CallOpc == PPCISD::BCTRL) {
4199 // This is a call through a function pointer.
4200 // Restore the caller TOC from the save area into R2.
4201 // See PrepareCall() for more information about calls through function
4202 // pointers in the 64-bit SVR4 ABI.
4203 // We are using a target-specific load with r2 hard coded, because the
4204 // result of a target-independent load would never go directly into r2,
4205 // since r2 is a reserved register (which prevents the register allocator
4206 // from allocating it), resulting in an additional register being
4207 // allocated and an unnecessary move instruction being generated.
4208 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4210 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4211 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4212 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4213 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4214 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4216 // The address needs to go after the chain input but before the flag (or
4217 // any other variadic arguments).
4218 Ops.insert(std::next(Ops.begin()), AddTOC);
4219 } else if ((CallOpc == PPCISD::CALL) &&
4220 (!isLocalCall(Callee) ||
4221 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4222 // Otherwise insert NOP for non-local calls.
4223 CallOpc = PPCISD::CALL_NOP;
4226 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4227 InFlag = Chain.getValue(1);
4229 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4230 DAG.getIntPtrConstant(BytesCalleePops, true),
4233 InFlag = Chain.getValue(1);
4235 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4236 Ins, dl, DAG, InVals);
4240 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4241 SmallVectorImpl<SDValue> &InVals) const {
4242 SelectionDAG &DAG = CLI.DAG;
4244 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4245 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4246 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4247 SDValue Chain = CLI.Chain;
4248 SDValue Callee = CLI.Callee;
4249 bool &isTailCall = CLI.IsTailCall;
4250 CallingConv::ID CallConv = CLI.CallConv;
4251 bool isVarArg = CLI.IsVarArg;
4252 bool IsPatchPoint = CLI.IsPatchPoint;
4253 ImmutableCallSite *CS = CLI.CS;
4256 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4259 if (!isTailCall && CS && CS->isMustTailCall())
4260 report_fatal_error("failed to perform tail call elimination on a call "
4261 "site marked musttail");
4263 if (Subtarget.isSVR4ABI()) {
4264 if (Subtarget.isPPC64())
4265 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4266 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4267 dl, DAG, InVals, CS);
4269 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4270 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4271 dl, DAG, InVals, CS);
4274 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4275 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4276 dl, DAG, InVals, CS);
4280 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4281 CallingConv::ID CallConv, bool isVarArg,
4282 bool isTailCall, bool IsPatchPoint,
4283 const SmallVectorImpl<ISD::OutputArg> &Outs,
4284 const SmallVectorImpl<SDValue> &OutVals,
4285 const SmallVectorImpl<ISD::InputArg> &Ins,
4286 SDLoc dl, SelectionDAG &DAG,
4287 SmallVectorImpl<SDValue> &InVals,
4288 ImmutableCallSite *CS) const {
4289 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4290 // of the 32-bit SVR4 ABI stack frame layout.
4292 assert((CallConv == CallingConv::C ||
4293 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4295 unsigned PtrByteSize = 4;
4297 MachineFunction &MF = DAG.getMachineFunction();
4299 // Mark this function as potentially containing a function that contains a
4300 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4301 // and restoring the callers stack pointer in this functions epilog. This is
4302 // done because by tail calling the called function might overwrite the value
4303 // in this function's (MF) stack pointer stack slot 0(SP).
4304 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4305 CallConv == CallingConv::Fast)
4306 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4308 // Count how many bytes are to be pushed on the stack, including the linkage
4309 // area, parameter list area and the part of the local variable space which
4310 // contains copies of aggregates which are passed by value.
4312 // Assign locations to all of the outgoing arguments.
4313 SmallVector<CCValAssign, 16> ArgLocs;
4314 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4317 // Reserve space for the linkage area on the stack.
4318 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4322 // Handle fixed and variable vector arguments differently.
4323 // Fixed vector arguments go into registers as long as registers are
4324 // available. Variable vector arguments always go into memory.
4325 unsigned NumArgs = Outs.size();
4327 for (unsigned i = 0; i != NumArgs; ++i) {
4328 MVT ArgVT = Outs[i].VT;
4329 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4332 if (Outs[i].IsFixed) {
4333 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4336 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4342 errs() << "Call operand #" << i << " has unhandled type "
4343 << EVT(ArgVT).getEVTString() << "\n";
4345 llvm_unreachable(nullptr);
4349 // All arguments are treated the same.
4350 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4353 // Assign locations to all of the outgoing aggregate by value arguments.
4354 SmallVector<CCValAssign, 16> ByValArgLocs;
4355 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4356 ByValArgLocs, *DAG.getContext());
4358 // Reserve stack space for the allocations in CCInfo.
4359 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4361 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4363 // Size of the linkage area, parameter list area and the part of the local
4364 // space variable where copies of aggregates which are passed by value are
4366 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4368 // Calculate by how many bytes the stack has to be adjusted in case of tail
4369 // call optimization.
4370 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4372 // Adjust the stack pointer for the new arguments...
4373 // These operations are automatically eliminated by the prolog/epilog pass
4374 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4376 SDValue CallSeqStart = Chain;
4378 // Load the return address and frame pointer so it can be moved somewhere else
4381 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4384 // Set up a copy of the stack pointer for use loading and storing any
4385 // arguments that may not fit in the registers available for argument
4387 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4389 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4390 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4391 SmallVector<SDValue, 8> MemOpChains;
4393 bool seenFloatArg = false;
4394 // Walk the register/memloc assignments, inserting copies/loads.
4395 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4398 CCValAssign &VA = ArgLocs[i];
4399 SDValue Arg = OutVals[i];
4400 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4402 if (Flags.isByVal()) {
4403 // Argument is an aggregate which is passed by value, thus we need to
4404 // create a copy of it in the local variable space of the current stack
4405 // frame (which is the stack frame of the caller) and pass the address of
4406 // this copy to the callee.
4407 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4408 CCValAssign &ByValVA = ByValArgLocs[j++];
4409 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4411 // Memory reserved in the local variable space of the callers stack frame.
4412 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4414 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4415 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4417 // Create a copy of the argument in the local area of the current
4419 SDValue MemcpyCall =
4420 CreateCopyOfByValArgument(Arg, PtrOff,
4421 CallSeqStart.getNode()->getOperand(0),
4424 // This must go outside the CALLSEQ_START..END.
4425 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4426 CallSeqStart.getNode()->getOperand(1),
4428 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4429 NewCallSeqStart.getNode());
4430 Chain = CallSeqStart = NewCallSeqStart;
4432 // Pass the address of the aggregate copy on the stack either in a
4433 // physical register or in the parameter list area of the current stack
4434 // frame to the callee.
4438 if (VA.isRegLoc()) {
4439 if (Arg.getValueType() == MVT::i1)
4440 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4442 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4443 // Put argument in a physical register.
4444 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4446 // Put argument in the parameter list area of the current stack frame.
4447 assert(VA.isMemLoc());
4448 unsigned LocMemOffset = VA.getLocMemOffset();
4451 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4452 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4454 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4455 MachinePointerInfo(),
4458 // Calculate and remember argument location.
4459 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4465 if (!MemOpChains.empty())
4466 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4468 // Build a sequence of copy-to-reg nodes chained together with token chain
4469 // and flag operands which copy the outgoing args into the appropriate regs.
4471 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4472 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4473 RegsToPass[i].second, InFlag);
4474 InFlag = Chain.getValue(1);
4477 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4480 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4481 SDValue Ops[] = { Chain, InFlag };
4483 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4484 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4486 InFlag = Chain.getValue(1);
4490 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4491 false, TailCallArguments);
4493 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4494 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4495 NumBytes, Ins, InVals, CS);
4498 // Copy an argument into memory, being careful to do this outside the
4499 // call sequence for the call to which the argument belongs.
4501 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4502 SDValue CallSeqStart,
4503 ISD::ArgFlagsTy Flags,
4506 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4507 CallSeqStart.getNode()->getOperand(0),
4509 // The MEMCPY must go outside the CALLSEQ_START..END.
4510 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4511 CallSeqStart.getNode()->getOperand(1),
4513 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4514 NewCallSeqStart.getNode());
4515 return NewCallSeqStart;
4519 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4520 CallingConv::ID CallConv, bool isVarArg,
4521 bool isTailCall, bool IsPatchPoint,
4522 const SmallVectorImpl<ISD::OutputArg> &Outs,
4523 const SmallVectorImpl<SDValue> &OutVals,
4524 const SmallVectorImpl<ISD::InputArg> &Ins,
4525 SDLoc dl, SelectionDAG &DAG,
4526 SmallVectorImpl<SDValue> &InVals,
4527 ImmutableCallSite *CS) const {
4529 bool isELFv2ABI = Subtarget.isELFv2ABI();
4530 bool isLittleEndian = Subtarget.isLittleEndian();
4531 unsigned NumOps = Outs.size();
4533 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4534 unsigned PtrByteSize = 8;
4536 MachineFunction &MF = DAG.getMachineFunction();
4538 // Mark this function as potentially containing a function that contains a
4539 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4540 // and restoring the callers stack pointer in this functions epilog. This is
4541 // done because by tail calling the called function might overwrite the value
4542 // in this function's (MF) stack pointer stack slot 0(SP).
4543 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4544 CallConv == CallingConv::Fast)
4545 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4547 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4548 "fastcc not supported on varargs functions");
4550 // Count how many bytes are to be pushed on the stack, including the linkage
4551 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4552 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4553 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4554 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4555 unsigned NumBytes = LinkageSize;
4556 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4557 unsigned &QFPR_idx = FPR_idx;
4559 static const MCPhysReg GPR[] = {
4560 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4561 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4563 static const MCPhysReg VR[] = {
4564 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4565 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4567 static const MCPhysReg VSRH[] = {
4568 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4569 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4572 const unsigned NumGPRs = array_lengthof(GPR);
4573 const unsigned NumFPRs = 13;
4574 const unsigned NumVRs = array_lengthof(VR);
4575 const unsigned NumQFPRs = NumFPRs;
4577 // When using the fast calling convention, we don't provide backing for
4578 // arguments that will be in registers.
4579 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4581 // Add up all the space actually used.
4582 for (unsigned i = 0; i != NumOps; ++i) {
4583 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4584 EVT ArgVT = Outs[i].VT;
4585 EVT OrigVT = Outs[i].ArgVT;
4587 if (CallConv == CallingConv::Fast) {
4588 if (Flags.isByVal())
4589 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4591 switch (ArgVT.getSimpleVT().SimpleTy) {
4592 default: llvm_unreachable("Unexpected ValueType for argument!");
4596 if (++NumGPRsUsed <= NumGPRs)
4604 if (++NumVRsUsed <= NumVRs)
4608 // When using QPX, this is handled like a FP register, otherwise, it
4609 // is an Altivec register.
4610 if (Subtarget.hasQPX()) {
4611 if (++NumFPRsUsed <= NumFPRs)
4614 if (++NumVRsUsed <= NumVRs)
4620 case MVT::v4f64: // QPX
4621 case MVT::v4i1: // QPX
4622 if (++NumFPRsUsed <= NumFPRs)
4628 /* Respect alignment of argument on the stack. */
4630 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4631 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4633 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4634 if (Flags.isInConsecutiveRegsLast())
4635 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4638 unsigned NumBytesActuallyUsed = NumBytes;
4640 // The prolog code of the callee may store up to 8 GPR argument registers to
4641 // the stack, allowing va_start to index over them in memory if its varargs.
4642 // Because we cannot tell if this is needed on the caller side, we have to
4643 // conservatively assume that it is needed. As such, make sure we have at
4644 // least enough stack space for the caller to store the 8 GPRs.
4645 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4646 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4648 // Tail call needs the stack to be aligned.
4649 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4650 CallConv == CallingConv::Fast)
4651 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4653 // Calculate by how many bytes the stack has to be adjusted in case of tail
4654 // call optimization.
4655 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4657 // To protect arguments on the stack from being clobbered in a tail call,
4658 // force all the loads to happen before doing any other lowering.
4660 Chain = DAG.getStackArgumentTokenFactor(Chain);
4662 // Adjust the stack pointer for the new arguments...
4663 // These operations are automatically eliminated by the prolog/epilog pass
4664 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4666 SDValue CallSeqStart = Chain;
4668 // Load the return address and frame pointer so it can be move somewhere else
4671 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4674 // Set up a copy of the stack pointer for use loading and storing any
4675 // arguments that may not fit in the registers available for argument
4677 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4679 // Figure out which arguments are going to go in registers, and which in
4680 // memory. Also, if this is a vararg function, floating point operations
4681 // must be stored to our stack, and loaded into integer regs as well, if
4682 // any integer regs are available for argument passing.
4683 unsigned ArgOffset = LinkageSize;
4685 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4686 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4688 SmallVector<SDValue, 8> MemOpChains;
4689 for (unsigned i = 0; i != NumOps; ++i) {
4690 SDValue Arg = OutVals[i];
4691 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4692 EVT ArgVT = Outs[i].VT;
4693 EVT OrigVT = Outs[i].ArgVT;
4695 // PtrOff will be used to store the current argument to the stack if a
4696 // register cannot be found for it.
4699 // We re-align the argument offset for each argument, except when using the
4700 // fast calling convention, when we need to make sure we do that only when
4701 // we'll actually use a stack slot.
4702 auto ComputePtrOff = [&]() {
4703 /* Respect alignment of argument on the stack. */
4705 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4706 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4708 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4710 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4713 if (CallConv != CallingConv::Fast) {
4716 /* Compute GPR index associated with argument offset. */
4717 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4718 GPR_idx = std::min(GPR_idx, NumGPRs);
4721 // Promote integers to 64-bit values.
4722 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4723 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4724 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4725 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4728 // FIXME memcpy is used way more than necessary. Correctness first.
4729 // Note: "by value" is code for passing a structure by value, not
4731 if (Flags.isByVal()) {
4732 // Note: Size includes alignment padding, so
4733 // struct x { short a; char b; }
4734 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4735 // These are the proper values we need for right-justifying the
4736 // aggregate in a parameter register.
4737 unsigned Size = Flags.getByValSize();
4739 // An empty aggregate parameter takes up no storage and no
4744 if (CallConv == CallingConv::Fast)
4747 // All aggregates smaller than 8 bytes must be passed right-justified.
4748 if (Size==1 || Size==2 || Size==4) {
4749 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4750 if (GPR_idx != NumGPRs) {
4751 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4752 MachinePointerInfo(), VT,
4753 false, false, false, 0);
4754 MemOpChains.push_back(Load.getValue(1));
4755 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4757 ArgOffset += PtrByteSize;
4762 if (GPR_idx == NumGPRs && Size < 8) {
4763 SDValue AddPtr = PtrOff;
4764 if (!isLittleEndian) {
4765 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4766 PtrOff.getValueType());
4767 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4769 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4772 ArgOffset += PtrByteSize;
4775 // Copy entire object into memory. There are cases where gcc-generated
4776 // code assumes it is there, even if it could be put entirely into
4777 // registers. (This is not what the doc says.)
4779 // FIXME: The above statement is likely due to a misunderstanding of the
4780 // documents. All arguments must be copied into the parameter area BY
4781 // THE CALLEE in the event that the callee takes the address of any
4782 // formal argument. That has not yet been implemented. However, it is
4783 // reasonable to use the stack area as a staging area for the register
4786 // Skip this for small aggregates, as we will use the same slot for a
4787 // right-justified copy, below.
4789 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4793 // When a register is available, pass a small aggregate right-justified.
4794 if (Size < 8 && GPR_idx != NumGPRs) {
4795 // The easiest way to get this right-justified in a register
4796 // is to copy the structure into the rightmost portion of a
4797 // local variable slot, then load the whole slot into the
4799 // FIXME: The memcpy seems to produce pretty awful code for
4800 // small aggregates, particularly for packed ones.
4801 // FIXME: It would be preferable to use the slot in the
4802 // parameter save area instead of a new local variable.
4803 SDValue AddPtr = PtrOff;
4804 if (!isLittleEndian) {
4805 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4806 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4808 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4812 // Load the slot into the register.
4813 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4814 MachinePointerInfo(),
4815 false, false, false, 0);
4816 MemOpChains.push_back(Load.getValue(1));
4817 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4819 // Done with this argument.
4820 ArgOffset += PtrByteSize;
4824 // For aggregates larger than PtrByteSize, copy the pieces of the
4825 // object that fit into registers from the parameter save area.
4826 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4827 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4828 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4829 if (GPR_idx != NumGPRs) {
4830 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4831 MachinePointerInfo(),
4832 false, false, false, 0);
4833 MemOpChains.push_back(Load.getValue(1));
4834 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4835 ArgOffset += PtrByteSize;
4837 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4844 switch (Arg.getSimpleValueType().SimpleTy) {
4845 default: llvm_unreachable("Unexpected ValueType for argument!");
4849 // These can be scalar arguments or elements of an integer array type
4850 // passed directly. Clang may use those instead of "byval" aggregate
4851 // types to avoid forcing arguments to memory unnecessarily.
4852 if (GPR_idx != NumGPRs) {
4853 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4855 if (CallConv == CallingConv::Fast)
4858 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4859 true, isTailCall, false, MemOpChains,
4860 TailCallArguments, dl);
4861 if (CallConv == CallingConv::Fast)
4862 ArgOffset += PtrByteSize;
4864 if (CallConv != CallingConv::Fast)
4865 ArgOffset += PtrByteSize;
4869 // These can be scalar arguments or elements of a float array type
4870 // passed directly. The latter are used to implement ELFv2 homogenous
4871 // float aggregates.
4873 // Named arguments go into FPRs first, and once they overflow, the
4874 // remaining arguments go into GPRs and then the parameter save area.
4875 // Unnamed arguments for vararg functions always go to GPRs and
4876 // then the parameter save area. For now, put all arguments to vararg
4877 // routines always in both locations (FPR *and* GPR or stack slot).
4878 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4879 bool NeededLoad = false;
4881 // First load the argument into the next available FPR.
4882 if (FPR_idx != NumFPRs)
4883 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4885 // Next, load the argument into GPR or stack slot if needed.
4886 if (!NeedGPROrStack)
4888 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4889 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4890 // once we support fp <-> gpr moves.
4892 // In the non-vararg case, this can only ever happen in the
4893 // presence of f32 array types, since otherwise we never run
4894 // out of FPRs before running out of GPRs.
4897 // Double values are always passed in a single GPR.
4898 if (Arg.getValueType() != MVT::f32) {
4899 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4901 // Non-array float values are extended and passed in a GPR.
4902 } else if (!Flags.isInConsecutiveRegs()) {
4903 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4904 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4906 // If we have an array of floats, we collect every odd element
4907 // together with its predecessor into one GPR.
4908 } else if (ArgOffset % PtrByteSize != 0) {
4910 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4911 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4912 if (!isLittleEndian)
4914 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4916 // The final element, if even, goes into the first half of a GPR.
4917 } else if (Flags.isInConsecutiveRegsLast()) {
4918 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4919 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4920 if (!isLittleEndian)
4921 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4922 DAG.getConstant(32, MVT::i32));
4924 // Non-final even elements are skipped; they will be handled
4925 // together the with subsequent argument on the next go-around.
4929 if (ArgVal.getNode())
4930 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4932 if (CallConv == CallingConv::Fast)
4935 // Single-precision floating-point values are mapped to the
4936 // second (rightmost) word of the stack doubleword.
4937 if (Arg.getValueType() == MVT::f32 &&
4938 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4939 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4940 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4943 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4944 true, isTailCall, false, MemOpChains,
4945 TailCallArguments, dl);
4949 // When passing an array of floats, the array occupies consecutive
4950 // space in the argument area; only round up to the next doubleword
4951 // at the end of the array. Otherwise, each float takes 8 bytes.
4952 if (CallConv != CallingConv::Fast || NeededLoad) {
4953 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4954 Flags.isInConsecutiveRegs()) ? 4 : 8;
4955 if (Flags.isInConsecutiveRegsLast())
4956 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4966 if (!Subtarget.hasQPX()) {
4967 // These can be scalar arguments or elements of a vector array type
4968 // passed directly. The latter are used to implement ELFv2 homogenous
4969 // vector aggregates.
4971 // For a varargs call, named arguments go into VRs or on the stack as
4972 // usual; unnamed arguments always go to the stack or the corresponding
4973 // GPRs when within range. For now, we always put the value in both
4974 // locations (or even all three).
4976 // We could elide this store in the case where the object fits
4977 // entirely in R registers. Maybe later.
4978 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4979 MachinePointerInfo(), false, false, 0);
4980 MemOpChains.push_back(Store);
4981 if (VR_idx != NumVRs) {
4982 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4983 MachinePointerInfo(),
4984 false, false, false, 0);
4985 MemOpChains.push_back(Load.getValue(1));
4987 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4988 Arg.getSimpleValueType() == MVT::v2i64) ?
4989 VSRH[VR_idx] : VR[VR_idx];
4992 RegsToPass.push_back(std::make_pair(VReg, Load));
4995 for (unsigned i=0; i<16; i+=PtrByteSize) {
4996 if (GPR_idx == NumGPRs)
4998 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4999 DAG.getConstant(i, PtrVT));
5000 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5001 false, false, false, 0);
5002 MemOpChains.push_back(Load.getValue(1));
5003 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5008 // Non-varargs Altivec params go into VRs or on the stack.
5009 if (VR_idx != NumVRs) {
5010 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5011 Arg.getSimpleValueType() == MVT::v2i64) ?
5012 VSRH[VR_idx] : VR[VR_idx];
5015 RegsToPass.push_back(std::make_pair(VReg, Arg));
5017 if (CallConv == CallingConv::Fast)
5020 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5021 true, isTailCall, true, MemOpChains,
5022 TailCallArguments, dl);
5023 if (CallConv == CallingConv::Fast)
5027 if (CallConv != CallingConv::Fast)
5032 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5033 "Invalid QPX parameter type");
5038 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5040 // We could elide this store in the case where the object fits
5041 // entirely in R registers. Maybe later.
5042 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5043 MachinePointerInfo(), false, false, 0);
5044 MemOpChains.push_back(Store);
5045 if (QFPR_idx != NumQFPRs) {
5046 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5047 Store, PtrOff, MachinePointerInfo(),
5048 false, false, false, 0);
5049 MemOpChains.push_back(Load.getValue(1));
5050 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5052 ArgOffset += (IsF32 ? 16 : 32);
5053 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5054 if (GPR_idx == NumGPRs)
5056 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5057 DAG.getConstant(i, PtrVT));
5058 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5059 false, false, false, 0);
5060 MemOpChains.push_back(Load.getValue(1));
5061 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5066 // Non-varargs QPX params go into registers or on the stack.
5067 if (QFPR_idx != NumQFPRs) {
5068 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5070 if (CallConv == CallingConv::Fast)
5073 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5074 true, isTailCall, true, MemOpChains,
5075 TailCallArguments, dl);
5076 if (CallConv == CallingConv::Fast)
5077 ArgOffset += (IsF32 ? 16 : 32);
5080 if (CallConv != CallingConv::Fast)
5081 ArgOffset += (IsF32 ? 16 : 32);
5087 assert(NumBytesActuallyUsed == ArgOffset);
5088 (void)NumBytesActuallyUsed;
5090 if (!MemOpChains.empty())
5091 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5093 // Check if this is an indirect call (MTCTR/BCTRL).
5094 // See PrepareCall() for more information about calls through function
5095 // pointers in the 64-bit SVR4 ABI.
5096 if (!isTailCall && !IsPatchPoint &&
5097 !isFunctionGlobalAddress(Callee) &&
5098 !isa<ExternalSymbolSDNode>(Callee)) {
5099 // Load r2 into a virtual register and store it to the TOC save area.
5100 setUsesTOCBasePtr(DAG);
5101 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5102 // TOC save area offset.
5103 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5104 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5105 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5106 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5107 MachinePointerInfo::getStack(TOCSaveOffset),
5109 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5110 // This does not mean the MTCTR instruction must use R12; it's easier
5111 // to model this as an extra parameter, so do that.
5112 if (isELFv2ABI && !IsPatchPoint)
5113 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5116 // Build a sequence of copy-to-reg nodes chained together with token chain
5117 // and flag operands which copy the outgoing args into the appropriate regs.
5119 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5120 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5121 RegsToPass[i].second, InFlag);
5122 InFlag = Chain.getValue(1);
5126 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5127 FPOp, true, TailCallArguments);
5129 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5130 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5131 NumBytes, Ins, InVals, CS);
5135 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5136 CallingConv::ID CallConv, bool isVarArg,
5137 bool isTailCall, bool IsPatchPoint,
5138 const SmallVectorImpl<ISD::OutputArg> &Outs,
5139 const SmallVectorImpl<SDValue> &OutVals,
5140 const SmallVectorImpl<ISD::InputArg> &Ins,
5141 SDLoc dl, SelectionDAG &DAG,
5142 SmallVectorImpl<SDValue> &InVals,
5143 ImmutableCallSite *CS) const {
5145 unsigned NumOps = Outs.size();
5147 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5148 bool isPPC64 = PtrVT == MVT::i64;
5149 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5151 MachineFunction &MF = DAG.getMachineFunction();
5153 // Mark this function as potentially containing a function that contains a
5154 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5155 // and restoring the callers stack pointer in this functions epilog. This is
5156 // done because by tail calling the called function might overwrite the value
5157 // in this function's (MF) stack pointer stack slot 0(SP).
5158 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5159 CallConv == CallingConv::Fast)
5160 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5162 // Count how many bytes are to be pushed on the stack, including the linkage
5163 // area, and parameter passing area. We start with 24/48 bytes, which is
5164 // prereserved space for [SP][CR][LR][3 x unused].
5165 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5166 unsigned NumBytes = LinkageSize;
5168 // Add up all the space actually used.
5169 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5170 // they all go in registers, but we must reserve stack space for them for
5171 // possible use by the caller. In varargs or 64-bit calls, parameters are
5172 // assigned stack space in order, with padding so Altivec parameters are
5174 unsigned nAltivecParamsAtEnd = 0;
5175 for (unsigned i = 0; i != NumOps; ++i) {
5176 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5177 EVT ArgVT = Outs[i].VT;
5178 // Varargs Altivec parameters are padded to a 16 byte boundary.
5179 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5180 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5181 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5182 if (!isVarArg && !isPPC64) {
5183 // Non-varargs Altivec parameters go after all the non-Altivec
5184 // parameters; handle those later so we know how much padding we need.
5185 nAltivecParamsAtEnd++;
5188 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5189 NumBytes = ((NumBytes+15)/16)*16;
5191 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5194 // Allow for Altivec parameters at the end, if needed.
5195 if (nAltivecParamsAtEnd) {
5196 NumBytes = ((NumBytes+15)/16)*16;
5197 NumBytes += 16*nAltivecParamsAtEnd;
5200 // The prolog code of the callee may store up to 8 GPR argument registers to
5201 // the stack, allowing va_start to index over them in memory if its varargs.
5202 // Because we cannot tell if this is needed on the caller side, we have to
5203 // conservatively assume that it is needed. As such, make sure we have at
5204 // least enough stack space for the caller to store the 8 GPRs.
5205 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5207 // Tail call needs the stack to be aligned.
5208 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5209 CallConv == CallingConv::Fast)
5210 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5212 // Calculate by how many bytes the stack has to be adjusted in case of tail
5213 // call optimization.
5214 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5216 // To protect arguments on the stack from being clobbered in a tail call,
5217 // force all the loads to happen before doing any other lowering.
5219 Chain = DAG.getStackArgumentTokenFactor(Chain);
5221 // Adjust the stack pointer for the new arguments...
5222 // These operations are automatically eliminated by the prolog/epilog pass
5223 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5225 SDValue CallSeqStart = Chain;
5227 // Load the return address and frame pointer so it can be move somewhere else
5230 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5233 // Set up a copy of the stack pointer for use loading and storing any
5234 // arguments that may not fit in the registers available for argument
5238 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5240 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5242 // Figure out which arguments are going to go in registers, and which in
5243 // memory. Also, if this is a vararg function, floating point operations
5244 // must be stored to our stack, and loaded into integer regs as well, if
5245 // any integer regs are available for argument passing.
5246 unsigned ArgOffset = LinkageSize;
5247 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5249 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5250 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5251 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5253 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5254 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5255 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5257 static const MCPhysReg VR[] = {
5258 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5259 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5261 const unsigned NumGPRs = array_lengthof(GPR_32);
5262 const unsigned NumFPRs = 13;
5263 const unsigned NumVRs = array_lengthof(VR);
5265 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5267 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5268 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5270 SmallVector<SDValue, 8> MemOpChains;
5271 for (unsigned i = 0; i != NumOps; ++i) {
5272 SDValue Arg = OutVals[i];
5273 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5275 // PtrOff will be used to store the current argument to the stack if a
5276 // register cannot be found for it.
5279 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5281 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5283 // On PPC64, promote integers to 64-bit values.
5284 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5285 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5286 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5287 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5290 // FIXME memcpy is used way more than necessary. Correctness first.
5291 // Note: "by value" is code for passing a structure by value, not
5293 if (Flags.isByVal()) {
5294 unsigned Size = Flags.getByValSize();
5295 // Very small objects are passed right-justified. Everything else is
5296 // passed left-justified.
5297 if (Size==1 || Size==2) {
5298 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5299 if (GPR_idx != NumGPRs) {
5300 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5301 MachinePointerInfo(), VT,
5302 false, false, false, 0);
5303 MemOpChains.push_back(Load.getValue(1));
5304 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5306 ArgOffset += PtrByteSize;
5308 SDValue Const = DAG.getConstant(PtrByteSize - Size,
5309 PtrOff.getValueType());
5310 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5311 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5314 ArgOffset += PtrByteSize;
5318 // Copy entire object into memory. There are cases where gcc-generated
5319 // code assumes it is there, even if it could be put entirely into
5320 // registers. (This is not what the doc says.)
5321 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5325 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5326 // copy the pieces of the object that fit into registers from the
5327 // parameter save area.
5328 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5329 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5330 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5331 if (GPR_idx != NumGPRs) {
5332 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5333 MachinePointerInfo(),
5334 false, false, false, 0);
5335 MemOpChains.push_back(Load.getValue(1));
5336 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5337 ArgOffset += PtrByteSize;
5339 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5346 switch (Arg.getSimpleValueType().SimpleTy) {
5347 default: llvm_unreachable("Unexpected ValueType for argument!");
5351 if (GPR_idx != NumGPRs) {
5352 if (Arg.getValueType() == MVT::i1)
5353 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5355 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5357 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5358 isPPC64, isTailCall, false, MemOpChains,
5359 TailCallArguments, dl);
5361 ArgOffset += PtrByteSize;
5365 if (FPR_idx != NumFPRs) {
5366 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5369 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5370 MachinePointerInfo(), false, false, 0);
5371 MemOpChains.push_back(Store);
5373 // Float varargs are always shadowed in available integer registers
5374 if (GPR_idx != NumGPRs) {
5375 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5376 MachinePointerInfo(), false, false,
5378 MemOpChains.push_back(Load.getValue(1));
5379 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5381 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5382 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5383 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5384 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5385 MachinePointerInfo(),
5386 false, false, false, 0);
5387 MemOpChains.push_back(Load.getValue(1));
5388 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5391 // If we have any FPRs remaining, we may also have GPRs remaining.
5392 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5394 if (GPR_idx != NumGPRs)
5396 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5397 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5401 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5402 isPPC64, isTailCall, false, MemOpChains,
5403 TailCallArguments, dl);
5407 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5414 // These go aligned on the stack, or in the corresponding R registers
5415 // when within range. The Darwin PPC ABI doc claims they also go in
5416 // V registers; in fact gcc does this only for arguments that are
5417 // prototyped, not for those that match the ... We do it for all
5418 // arguments, seems to work.
5419 while (ArgOffset % 16 !=0) {
5420 ArgOffset += PtrByteSize;
5421 if (GPR_idx != NumGPRs)
5424 // We could elide this store in the case where the object fits
5425 // entirely in R registers. Maybe later.
5426 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5427 DAG.getConstant(ArgOffset, PtrVT));
5428 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5429 MachinePointerInfo(), false, false, 0);
5430 MemOpChains.push_back(Store);
5431 if (VR_idx != NumVRs) {
5432 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5433 MachinePointerInfo(),
5434 false, false, false, 0);
5435 MemOpChains.push_back(Load.getValue(1));
5436 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5439 for (unsigned i=0; i<16; i+=PtrByteSize) {
5440 if (GPR_idx == NumGPRs)
5442 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5443 DAG.getConstant(i, PtrVT));
5444 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5445 false, false, false, 0);
5446 MemOpChains.push_back(Load.getValue(1));
5447 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5452 // Non-varargs Altivec params generally go in registers, but have
5453 // stack space allocated at the end.
5454 if (VR_idx != NumVRs) {
5455 // Doesn't have GPR space allocated.
5456 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5457 } else if (nAltivecParamsAtEnd==0) {
5458 // We are emitting Altivec params in order.
5459 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5460 isPPC64, isTailCall, true, MemOpChains,
5461 TailCallArguments, dl);
5467 // If all Altivec parameters fit in registers, as they usually do,
5468 // they get stack space following the non-Altivec parameters. We
5469 // don't track this here because nobody below needs it.
5470 // If there are more Altivec parameters than fit in registers emit
5472 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5474 // Offset is aligned; skip 1st 12 params which go in V registers.
5475 ArgOffset = ((ArgOffset+15)/16)*16;
5477 for (unsigned i = 0; i != NumOps; ++i) {
5478 SDValue Arg = OutVals[i];
5479 EVT ArgType = Outs[i].VT;
5480 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5481 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5484 // We are emitting Altivec params in order.
5485 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5486 isPPC64, isTailCall, true, MemOpChains,
5487 TailCallArguments, dl);
5494 if (!MemOpChains.empty())
5495 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5497 // On Darwin, R12 must contain the address of an indirect callee. This does
5498 // not mean the MTCTR instruction must use R12; it's easier to model this as
5499 // an extra parameter, so do that.
5501 !isFunctionGlobalAddress(Callee) &&
5502 !isa<ExternalSymbolSDNode>(Callee) &&
5503 !isBLACompatibleAddress(Callee, DAG))
5504 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5505 PPC::R12), Callee));
5507 // Build a sequence of copy-to-reg nodes chained together with token chain
5508 // and flag operands which copy the outgoing args into the appropriate regs.
5510 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5511 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5512 RegsToPass[i].second, InFlag);
5513 InFlag = Chain.getValue(1);
5517 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5518 FPOp, true, TailCallArguments);
5520 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5521 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5522 NumBytes, Ins, InVals, CS);
5526 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5527 MachineFunction &MF, bool isVarArg,
5528 const SmallVectorImpl<ISD::OutputArg> &Outs,
5529 LLVMContext &Context) const {
5530 SmallVector<CCValAssign, 16> RVLocs;
5531 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5532 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5536 PPCTargetLowering::LowerReturn(SDValue Chain,
5537 CallingConv::ID CallConv, bool isVarArg,
5538 const SmallVectorImpl<ISD::OutputArg> &Outs,
5539 const SmallVectorImpl<SDValue> &OutVals,
5540 SDLoc dl, SelectionDAG &DAG) const {
5542 SmallVector<CCValAssign, 16> RVLocs;
5543 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5545 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5548 SmallVector<SDValue, 4> RetOps(1, Chain);
5550 // Copy the result values into the output registers.
5551 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5552 CCValAssign &VA = RVLocs[i];
5553 assert(VA.isRegLoc() && "Can only return in registers!");
5555 SDValue Arg = OutVals[i];
5557 switch (VA.getLocInfo()) {
5558 default: llvm_unreachable("Unknown loc info!");
5559 case CCValAssign::Full: break;
5560 case CCValAssign::AExt:
5561 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5563 case CCValAssign::ZExt:
5564 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5566 case CCValAssign::SExt:
5567 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5571 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5572 Flag = Chain.getValue(1);
5573 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5576 RetOps[0] = Chain; // Update chain.
5578 // Add the flag if we have it.
5580 RetOps.push_back(Flag);
5582 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5585 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5586 const PPCSubtarget &Subtarget) const {
5587 // When we pop the dynamic allocation we need to restore the SP link.
5590 // Get the corect type for pointers.
5591 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5593 // Construct the stack pointer operand.
5594 bool isPPC64 = Subtarget.isPPC64();
5595 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5596 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5598 // Get the operands for the STACKRESTORE.
5599 SDValue Chain = Op.getOperand(0);
5600 SDValue SaveSP = Op.getOperand(1);
5602 // Load the old link SP.
5603 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5604 MachinePointerInfo(),
5605 false, false, false, 0);
5607 // Restore the stack pointer.
5608 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5610 // Store the old link SP.
5611 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5618 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5619 MachineFunction &MF = DAG.getMachineFunction();
5620 bool isPPC64 = Subtarget.isPPC64();
5621 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5623 // Get current frame pointer save index. The users of this index will be
5624 // primarily DYNALLOC instructions.
5625 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5626 int RASI = FI->getReturnAddrSaveIndex();
5628 // If the frame pointer save index hasn't been defined yet.
5630 // Find out what the fix offset of the frame pointer save area.
5631 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5632 // Allocate the frame index for frame pointer save area.
5633 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5635 FI->setReturnAddrSaveIndex(RASI);
5637 return DAG.getFrameIndex(RASI, PtrVT);
5641 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5642 MachineFunction &MF = DAG.getMachineFunction();
5643 bool isPPC64 = Subtarget.isPPC64();
5644 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5646 // Get current frame pointer save index. The users of this index will be
5647 // primarily DYNALLOC instructions.
5648 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5649 int FPSI = FI->getFramePointerSaveIndex();
5651 // If the frame pointer save index hasn't been defined yet.
5653 // Find out what the fix offset of the frame pointer save area.
5654 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5655 // Allocate the frame index for frame pointer save area.
5656 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5658 FI->setFramePointerSaveIndex(FPSI);
5660 return DAG.getFrameIndex(FPSI, PtrVT);
5663 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5665 const PPCSubtarget &Subtarget) const {
5667 SDValue Chain = Op.getOperand(0);
5668 SDValue Size = Op.getOperand(1);
5671 // Get the corect type for pointers.
5672 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5674 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5675 DAG.getConstant(0, PtrVT), Size);
5676 // Construct a node for the frame pointer save index.
5677 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5678 // Build a DYNALLOC node.
5679 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5680 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5681 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5684 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5685 SelectionDAG &DAG) const {
5687 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5688 DAG.getVTList(MVT::i32, MVT::Other),
5689 Op.getOperand(0), Op.getOperand(1));
5692 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5693 SelectionDAG &DAG) const {
5695 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5696 Op.getOperand(0), Op.getOperand(1));
5699 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5700 if (Op.getValueType().isVector())
5701 return LowerVectorLoad(Op, DAG);
5703 assert(Op.getValueType() == MVT::i1 &&
5704 "Custom lowering only for i1 loads");
5706 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5709 LoadSDNode *LD = cast<LoadSDNode>(Op);
5711 SDValue Chain = LD->getChain();
5712 SDValue BasePtr = LD->getBasePtr();
5713 MachineMemOperand *MMO = LD->getMemOperand();
5715 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5716 BasePtr, MVT::i8, MMO);
5717 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5719 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5720 return DAG.getMergeValues(Ops, dl);
5723 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5724 if (Op.getOperand(1).getValueType().isVector())
5725 return LowerVectorStore(Op, DAG);
5727 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5728 "Custom lowering only for i1 stores");
5730 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5733 StoreSDNode *ST = cast<StoreSDNode>(Op);
5735 SDValue Chain = ST->getChain();
5736 SDValue BasePtr = ST->getBasePtr();
5737 SDValue Value = ST->getValue();
5738 MachineMemOperand *MMO = ST->getMemOperand();
5740 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5741 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5744 // FIXME: Remove this once the ANDI glue bug is fixed:
5745 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5746 assert(Op.getValueType() == MVT::i1 &&
5747 "Custom lowering only for i1 results");
5750 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5754 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5756 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5757 // Not FP? Not a fsel.
5758 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5759 !Op.getOperand(2).getValueType().isFloatingPoint())
5762 // We might be able to do better than this under some circumstances, but in
5763 // general, fsel-based lowering of select is a finite-math-only optimization.
5764 // For more information, see section F.3 of the 2.06 ISA specification.
5765 if (!DAG.getTarget().Options.NoInfsFPMath ||
5766 !DAG.getTarget().Options.NoNaNsFPMath)
5769 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5771 EVT ResVT = Op.getValueType();
5772 EVT CmpVT = Op.getOperand(0).getValueType();
5773 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5774 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5777 // If the RHS of the comparison is a 0.0, we don't need to do the
5778 // subtraction at all.
5780 if (isFloatingPointZero(RHS))
5782 default: break; // SETUO etc aren't handled by fsel.
5786 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5787 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5788 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5789 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5790 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5791 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5792 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5795 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5798 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5799 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5800 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5803 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5806 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5807 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5808 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5809 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5814 default: break; // SETUO etc aren't handled by fsel.
5818 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5819 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5820 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5821 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5822 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5823 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5824 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5825 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5828 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5829 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5830 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5831 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5834 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5835 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5836 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5837 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5840 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5841 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5842 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5843 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5846 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5847 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5848 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5849 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5854 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5857 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5858 SDValue Src = Op.getOperand(0);
5859 if (Src.getValueType() == MVT::f32)
5860 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5863 switch (Op.getSimpleValueType().SimpleTy) {
5864 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5867 Op.getOpcode() == ISD::FP_TO_SINT
5869 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5873 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5874 "i64 FP_TO_UINT is supported only with FPCVT");
5875 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5881 // Convert the FP value to an int value through memory.
5882 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5883 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5884 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5885 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5886 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5888 // Emit a store to the stack slot.
5891 MachineFunction &MF = DAG.getMachineFunction();
5892 MachineMemOperand *MMO =
5893 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5894 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5895 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5896 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5898 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5899 MPI, false, false, 0);
5901 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5903 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5904 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5905 DAG.getConstant(4, FIPtr.getValueType()));
5906 MPI = MPI.getWithOffset(4);
5914 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5917 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5919 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5920 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5924 // We're trying to insert a regular store, S, and then a load, L. If the
5925 // incoming value, O, is a load, we might just be able to have our load use the
5926 // address used by O. However, we don't know if anything else will store to
5927 // that address before we can load from it. To prevent this situation, we need
5928 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5929 // the same chain operand as O, we create a token factor from the chain results
5930 // of O and L, and we replace all uses of O's chain result with that token
5931 // factor (see spliceIntoChain below for this last part).
5932 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5935 ISD::LoadExtType ET) const {
5937 if (ET == ISD::NON_EXTLOAD &&
5938 (Op.getOpcode() == ISD::FP_TO_UINT ||
5939 Op.getOpcode() == ISD::FP_TO_SINT) &&
5940 isOperationLegalOrCustom(Op.getOpcode(),
5941 Op.getOperand(0).getValueType())) {
5943 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5947 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5948 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5949 LD->isNonTemporal())
5951 if (LD->getMemoryVT() != MemVT)
5954 RLI.Ptr = LD->getBasePtr();
5955 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5956 assert(LD->getAddressingMode() == ISD::PRE_INC &&
5957 "Non-pre-inc AM on PPC?");
5958 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5962 RLI.Chain = LD->getChain();
5963 RLI.MPI = LD->getPointerInfo();
5964 RLI.IsInvariant = LD->isInvariant();
5965 RLI.Alignment = LD->getAlignment();
5966 RLI.AAInfo = LD->getAAInfo();
5967 RLI.Ranges = LD->getRanges();
5969 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5973 // Given the head of the old chain, ResChain, insert a token factor containing
5974 // it and NewResChain, and make users of ResChain now be users of that token
5976 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5977 SDValue NewResChain,
5978 SelectionDAG &DAG) const {
5982 SDLoc dl(NewResChain);
5984 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5985 NewResChain, DAG.getUNDEF(MVT::Other));
5986 assert(TF.getNode() != NewResChain.getNode() &&
5987 "A new TF really is required here");
5989 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
5990 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
5993 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5994 SelectionDAG &DAG) const {
5997 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
5998 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6001 SDValue Value = Op.getOperand(0);
6002 // The values are now known to be -1 (false) or 1 (true). To convert this
6003 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6004 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6005 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6007 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6008 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6009 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6011 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6013 if (Op.getValueType() != MVT::v4f64)
6014 Value = DAG.getNode(ISD::FP_ROUND, dl,
6015 Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6019 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6020 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6023 if (Op.getOperand(0).getValueType() == MVT::i1)
6024 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6025 DAG.getConstantFP(1.0, Op.getValueType()),
6026 DAG.getConstantFP(0.0, Op.getValueType()));
6028 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6029 "UINT_TO_FP is supported only with FPCVT");
6031 // If we have FCFIDS, then use it when converting to single-precision.
6032 // Otherwise, convert to double-precision and then round.
6033 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6034 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6036 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6038 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6042 if (Op.getOperand(0).getValueType() == MVT::i64) {
6043 SDValue SINT = Op.getOperand(0);
6044 // When converting to single-precision, we actually need to convert
6045 // to double-precision first and then round to single-precision.
6046 // To avoid double-rounding effects during that operation, we have
6047 // to prepare the input operand. Bits that might be truncated when
6048 // converting to double-precision are replaced by a bit that won't
6049 // be lost at this stage, but is below the single-precision rounding
6052 // However, if -enable-unsafe-fp-math is in effect, accept double
6053 // rounding to avoid the extra overhead.
6054 if (Op.getValueType() == MVT::f32 &&
6055 !Subtarget.hasFPCVT() &&
6056 !DAG.getTarget().Options.UnsafeFPMath) {
6058 // Twiddle input to make sure the low 11 bits are zero. (If this
6059 // is the case, we are guaranteed the value will fit into the 53 bit
6060 // mantissa of an IEEE double-precision value without rounding.)
6061 // If any of those low 11 bits were not zero originally, make sure
6062 // bit 12 (value 2048) is set instead, so that the final rounding
6063 // to single-precision gets the correct result.
6064 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6065 SINT, DAG.getConstant(2047, MVT::i64));
6066 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6067 Round, DAG.getConstant(2047, MVT::i64));
6068 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6069 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6070 Round, DAG.getConstant(-2048, MVT::i64));
6072 // However, we cannot use that value unconditionally: if the magnitude
6073 // of the input value is small, the bit-twiddling we did above might
6074 // end up visibly changing the output. Fortunately, in that case, we
6075 // don't need to twiddle bits since the original input will convert
6076 // exactly to double-precision floating-point already. Therefore,
6077 // construct a conditional to use the original value if the top 11
6078 // bits are all sign-bit copies, and use the rounded value computed
6080 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6081 SINT, DAG.getConstant(53, MVT::i32));
6082 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6083 Cond, DAG.getConstant(1, MVT::i64));
6084 Cond = DAG.getSetCC(dl, MVT::i32,
6085 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6087 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6093 MachineFunction &MF = DAG.getMachineFunction();
6094 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6095 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6096 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6098 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6099 } else if (Subtarget.hasLFIWAX() &&
6100 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6101 MachineMemOperand *MMO =
6102 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6103 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6104 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6105 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6106 DAG.getVTList(MVT::f64, MVT::Other),
6107 Ops, MVT::i32, MMO);
6108 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6109 } else if (Subtarget.hasFPCVT() &&
6110 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6111 MachineMemOperand *MMO =
6112 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6113 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6114 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6115 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6116 DAG.getVTList(MVT::f64, MVT::Other),
6117 Ops, MVT::i32, MMO);
6118 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6119 } else if (((Subtarget.hasLFIWAX() &&
6120 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6121 (Subtarget.hasFPCVT() &&
6122 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6123 SINT.getOperand(0).getValueType() == MVT::i32) {
6124 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6125 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6127 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6128 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6131 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6132 MachinePointerInfo::getFixedStack(FrameIdx),
6135 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6136 "Expected an i32 store");
6140 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6143 MachineMemOperand *MMO =
6144 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6145 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6146 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6147 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6148 PPCISD::LFIWZX : PPCISD::LFIWAX,
6149 dl, DAG.getVTList(MVT::f64, MVT::Other),
6150 Ops, MVT::i32, MMO);
6152 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6154 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6156 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6157 FP = DAG.getNode(ISD::FP_ROUND, dl,
6158 MVT::f32, FP, DAG.getIntPtrConstant(0));
6162 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6163 "Unhandled INT_TO_FP type in custom expander!");
6164 // Since we only generate this in 64-bit mode, we can take advantage of
6165 // 64-bit registers. In particular, sign extend the input value into the
6166 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6167 // then lfd it and fcfid it.
6168 MachineFunction &MF = DAG.getMachineFunction();
6169 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6170 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6173 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6176 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6178 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6179 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6181 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6182 MachinePointerInfo::getFixedStack(FrameIdx),
6185 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6186 "Expected an i32 store");
6190 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6194 MachineMemOperand *MMO =
6195 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6196 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6197 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6198 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6199 PPCISD::LFIWZX : PPCISD::LFIWAX,
6200 dl, DAG.getVTList(MVT::f64, MVT::Other),
6201 Ops, MVT::i32, MMO);
6203 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6205 assert(Subtarget.isPPC64() &&
6206 "i32->FP without LFIWAX supported only on PPC64");
6208 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6209 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6211 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6214 // STD the extended value into the stack slot.
6215 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6216 MachinePointerInfo::getFixedStack(FrameIdx),
6219 // Load the value as a double.
6220 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6221 MachinePointerInfo::getFixedStack(FrameIdx),
6222 false, false, false, 0);
6225 // FCFID it and return it.
6226 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6227 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6228 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6232 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6233 SelectionDAG &DAG) const {
6236 The rounding mode is in bits 30:31 of FPSR, and has the following
6243 FLT_ROUNDS, on the other hand, expects the following:
6250 To perform the conversion, we do:
6251 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6254 MachineFunction &MF = DAG.getMachineFunction();
6255 EVT VT = Op.getValueType();
6256 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6258 // Save FP Control Word to register
6260 MVT::f64, // return register
6261 MVT::Glue // unused in this context
6263 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6265 // Save FP register to stack slot
6266 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6267 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6268 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6269 StackSlot, MachinePointerInfo(), false, false,0);
6271 // Load FP Control Word from low 32 bits of stack slot.
6272 SDValue Four = DAG.getConstant(4, PtrVT);
6273 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6274 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6275 false, false, false, 0);
6277 // Transform as necessary
6279 DAG.getNode(ISD::AND, dl, MVT::i32,
6280 CWD, DAG.getConstant(3, MVT::i32));
6282 DAG.getNode(ISD::SRL, dl, MVT::i32,
6283 DAG.getNode(ISD::AND, dl, MVT::i32,
6284 DAG.getNode(ISD::XOR, dl, MVT::i32,
6285 CWD, DAG.getConstant(3, MVT::i32)),
6286 DAG.getConstant(3, MVT::i32)),
6287 DAG.getConstant(1, MVT::i32));
6290 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6292 return DAG.getNode((VT.getSizeInBits() < 16 ?
6293 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6296 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6297 EVT VT = Op.getValueType();
6298 unsigned BitWidth = VT.getSizeInBits();
6300 assert(Op.getNumOperands() == 3 &&
6301 VT == Op.getOperand(1).getValueType() &&
6304 // Expand into a bunch of logical ops. Note that these ops
6305 // depend on the PPC behavior for oversized shift amounts.
6306 SDValue Lo = Op.getOperand(0);
6307 SDValue Hi = Op.getOperand(1);
6308 SDValue Amt = Op.getOperand(2);
6309 EVT AmtVT = Amt.getValueType();
6311 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6312 DAG.getConstant(BitWidth, AmtVT), Amt);
6313 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6314 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6315 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6316 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6317 DAG.getConstant(-BitWidth, AmtVT));
6318 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6319 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6320 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6321 SDValue OutOps[] = { OutLo, OutHi };
6322 return DAG.getMergeValues(OutOps, dl);
6325 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6326 EVT VT = Op.getValueType();
6328 unsigned BitWidth = VT.getSizeInBits();
6329 assert(Op.getNumOperands() == 3 &&
6330 VT == Op.getOperand(1).getValueType() &&
6333 // Expand into a bunch of logical ops. Note that these ops
6334 // depend on the PPC behavior for oversized shift amounts.
6335 SDValue Lo = Op.getOperand(0);
6336 SDValue Hi = Op.getOperand(1);
6337 SDValue Amt = Op.getOperand(2);
6338 EVT AmtVT = Amt.getValueType();
6340 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6341 DAG.getConstant(BitWidth, AmtVT), Amt);
6342 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6343 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6344 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6345 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6346 DAG.getConstant(-BitWidth, AmtVT));
6347 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6348 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6349 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6350 SDValue OutOps[] = { OutLo, OutHi };
6351 return DAG.getMergeValues(OutOps, dl);
6354 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6356 EVT VT = Op.getValueType();
6357 unsigned BitWidth = VT.getSizeInBits();
6358 assert(Op.getNumOperands() == 3 &&
6359 VT == Op.getOperand(1).getValueType() &&
6362 // Expand into a bunch of logical ops, followed by a select_cc.
6363 SDValue Lo = Op.getOperand(0);
6364 SDValue Hi = Op.getOperand(1);
6365 SDValue Amt = Op.getOperand(2);
6366 EVT AmtVT = Amt.getValueType();
6368 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6369 DAG.getConstant(BitWidth, AmtVT), Amt);
6370 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6371 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6372 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6373 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6374 DAG.getConstant(-BitWidth, AmtVT));
6375 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6376 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6377 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6378 Tmp4, Tmp6, ISD::SETLE);
6379 SDValue OutOps[] = { OutLo, OutHi };
6380 return DAG.getMergeValues(OutOps, dl);
6383 //===----------------------------------------------------------------------===//
6384 // Vector related lowering.
6387 /// BuildSplatI - Build a canonical splati of Val with an element size of
6388 /// SplatSize. Cast the result to VT.
6389 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6390 SelectionDAG &DAG, SDLoc dl) {
6391 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6393 static const MVT VTys[] = { // canonical VT to use for each size.
6394 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6397 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6399 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6403 EVT CanonicalVT = VTys[SplatSize-1];
6405 // Build a canonical splat for this value.
6406 SDValue Elt = DAG.getConstant(Val, MVT::i32);
6407 SmallVector<SDValue, 8> Ops;
6408 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6409 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6410 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6413 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6414 /// specified intrinsic ID.
6415 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6416 SelectionDAG &DAG, SDLoc dl,
6417 EVT DestVT = MVT::Other) {
6418 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6419 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6420 DAG.getConstant(IID, MVT::i32), Op);
6423 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6424 /// specified intrinsic ID.
6425 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6426 SelectionDAG &DAG, SDLoc dl,
6427 EVT DestVT = MVT::Other) {
6428 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6429 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6430 DAG.getConstant(IID, MVT::i32), LHS, RHS);
6433 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6434 /// specified intrinsic ID.
6435 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6436 SDValue Op2, SelectionDAG &DAG,
6437 SDLoc dl, EVT DestVT = MVT::Other) {
6438 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6439 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6440 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6444 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6445 /// amount. The result has the specified value type.
6446 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6447 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6448 // Force LHS/RHS to be the right type.
6449 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6450 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6453 for (unsigned i = 0; i != 16; ++i)
6455 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6456 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6459 // If this is a case we can't handle, return null and let the default
6460 // expansion code take care of it. If we CAN select this case, and if it
6461 // selects to a single instruction, return Op. Otherwise, if we can codegen
6462 // this case more efficiently than a constant pool load, lower it to the
6463 // sequence of ops that should be used.
6464 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6465 SelectionDAG &DAG) const {
6467 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6468 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6470 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6471 // We first build an i32 vector, load it into a QPX register,
6472 // then convert it to a floating-point vector and compare it
6473 // to a zero vector to get the boolean result.
6474 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6475 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6476 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6477 EVT PtrVT = getPointerTy();
6478 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6480 assert(BVN->getNumOperands() == 4 &&
6481 "BUILD_VECTOR for v4i1 does not have 4 operands");
6483 bool IsConst = true;
6484 for (unsigned i = 0; i < 4; ++i) {
6485 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6486 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6494 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6496 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6498 SmallVector<Constant*, 4> CV(4, NegOne);
6499 for (unsigned i = 0; i < 4; ++i) {
6500 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6501 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6502 else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6503 getConstantIntValue()->isZero())
6509 Constant *CP = ConstantVector::get(CV);
6510 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6511 16 /* alignment */);
6513 SmallVector<SDValue, 2> Ops;
6514 Ops.push_back(DAG.getEntryNode());
6515 Ops.push_back(CPIdx);
6517 SmallVector<EVT, 2> ValueVTs;
6518 ValueVTs.push_back(MVT::v4i1);
6519 ValueVTs.push_back(MVT::Other); // chain
6520 SDVTList VTs = DAG.getVTList(ValueVTs);
6522 return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6523 dl, VTs, Ops, MVT::v4f32,
6524 MachinePointerInfo::getConstantPool());
6527 SmallVector<SDValue, 4> Stores;
6528 for (unsigned i = 0; i < 4; ++i) {
6529 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6531 unsigned Offset = 4*i;
6532 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6533 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6535 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6536 if (StoreSize > 4) {
6537 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6538 BVN->getOperand(i), Idx,
6539 PtrInfo.getWithOffset(Offset),
6540 MVT::i32, false, false, 0));
6542 SDValue StoreValue = BVN->getOperand(i);
6544 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6546 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6548 PtrInfo.getWithOffset(Offset),
6554 if (!Stores.empty())
6555 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6557 StoreChain = DAG.getEntryNode();
6559 // Now load from v4i32 into the QPX register; this will extend it to
6560 // v4i64 but not yet convert it to a floating point. Nevertheless, this
6561 // is typed as v4f64 because the QPX register integer states are not
6562 // explicitly represented.
6564 SmallVector<SDValue, 2> Ops;
6565 Ops.push_back(StoreChain);
6566 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6567 Ops.push_back(FIdx);
6569 SmallVector<EVT, 2> ValueVTs;
6570 ValueVTs.push_back(MVT::v4f64);
6571 ValueVTs.push_back(MVT::Other); // chain
6572 SDVTList VTs = DAG.getVTList(ValueVTs);
6574 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6575 dl, VTs, Ops, MVT::v4i32, PtrInfo);
6576 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6577 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6580 SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6581 FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6582 FPZeros, FPZeros, FPZeros, FPZeros);
6584 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6587 // All other QPX vectors are handled by generic code.
6588 if (Subtarget.hasQPX())
6591 // Check if this is a splat of a constant value.
6592 APInt APSplatBits, APSplatUndef;
6593 unsigned SplatBitSize;
6595 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6596 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6600 unsigned SplatBits = APSplatBits.getZExtValue();
6601 unsigned SplatUndef = APSplatUndef.getZExtValue();
6602 unsigned SplatSize = SplatBitSize / 8;
6604 // First, handle single instruction cases.
6607 if (SplatBits == 0) {
6608 // Canonicalize all zero vectors to be v4i32.
6609 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6610 SDValue Z = DAG.getConstant(0, MVT::i32);
6611 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6612 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6617 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6618 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6620 if (SextVal >= -16 && SextVal <= 15)
6621 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6624 // Two instruction sequences.
6626 // If this value is in the range [-32,30] and is even, use:
6627 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6628 // If this value is in the range [17,31] and is odd, use:
6629 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6630 // If this value is in the range [-31,-17] and is odd, use:
6631 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6632 // Note the last two are three-instruction sequences.
6633 if (SextVal >= -32 && SextVal <= 31) {
6634 // To avoid having these optimizations undone by constant folding,
6635 // we convert to a pseudo that will be expanded later into one of
6637 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6638 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6639 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6640 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6641 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6642 if (VT == Op.getValueType())
6645 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6648 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6649 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6651 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6652 // Make -1 and vspltisw -1:
6653 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6655 // Make the VSLW intrinsic, computing 0x8000_0000.
6656 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6659 // xor by OnesV to invert it.
6660 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6661 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6664 // Check to see if this is a wide variety of vsplti*, binop self cases.
6665 static const signed char SplatCsts[] = {
6666 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6667 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6670 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6671 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6672 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6673 int i = SplatCsts[idx];
6675 // Figure out what shift amount will be used by altivec if shifted by i in
6677 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6679 // vsplti + shl self.
6680 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6681 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6682 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6683 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6684 Intrinsic::ppc_altivec_vslw
6686 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6687 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6690 // vsplti + srl self.
6691 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6692 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6693 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6694 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6695 Intrinsic::ppc_altivec_vsrw
6697 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6698 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6701 // vsplti + sra self.
6702 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6703 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6704 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6705 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6706 Intrinsic::ppc_altivec_vsraw
6708 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6709 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6712 // vsplti + rol self.
6713 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6714 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6715 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6716 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6717 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6718 Intrinsic::ppc_altivec_vrlw
6720 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6721 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6724 // t = vsplti c, result = vsldoi t, t, 1
6725 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6726 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6727 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6729 // t = vsplti c, result = vsldoi t, t, 2
6730 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6731 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6732 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6734 // t = vsplti c, result = vsldoi t, t, 3
6735 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6736 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6737 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6744 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6745 /// the specified operations to build the shuffle.
6746 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6747 SDValue RHS, SelectionDAG &DAG,
6749 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6750 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6751 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6754 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6766 if (OpNum == OP_COPY) {
6767 if (LHSID == (1*9+2)*9+3) return LHS;
6768 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6772 SDValue OpLHS, OpRHS;
6773 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6774 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6778 default: llvm_unreachable("Unknown i32 permute!");
6780 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6781 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6782 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6783 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6786 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6787 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6788 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6789 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6792 for (unsigned i = 0; i != 16; ++i)
6793 ShufIdxs[i] = (i&3)+0;
6796 for (unsigned i = 0; i != 16; ++i)
6797 ShufIdxs[i] = (i&3)+4;
6800 for (unsigned i = 0; i != 16; ++i)
6801 ShufIdxs[i] = (i&3)+8;
6804 for (unsigned i = 0; i != 16; ++i)
6805 ShufIdxs[i] = (i&3)+12;
6808 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6810 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6812 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6814 EVT VT = OpLHS.getValueType();
6815 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6816 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6817 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6818 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6821 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6822 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6823 /// return the code it can be lowered into. Worst case, it can always be
6824 /// lowered into a vperm.
6825 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6826 SelectionDAG &DAG) const {
6828 SDValue V1 = Op.getOperand(0);
6829 SDValue V2 = Op.getOperand(1);
6830 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6831 EVT VT = Op.getValueType();
6832 bool isLittleEndian = Subtarget.isLittleEndian();
6834 if (Subtarget.hasQPX()) {
6835 if (VT.getVectorNumElements() != 4)
6838 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6840 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6841 if (AlignIdx != -1) {
6842 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6843 DAG.getConstant(AlignIdx, MVT::i32));
6844 } else if (SVOp->isSplat()) {
6845 int SplatIdx = SVOp->getSplatIndex();
6846 if (SplatIdx >= 4) {
6851 // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6854 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6855 DAG.getConstant(SplatIdx, MVT::i32));
6858 // Lower this into a qvgpci/qvfperm pair.
6860 // Compute the qvgpci literal
6862 for (unsigned i = 0; i < 4; ++i) {
6863 int m = SVOp->getMaskElt(i);
6864 unsigned mm = m >= 0 ? (unsigned) m : i;
6865 idx |= mm << (3-i)*3;
6868 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6869 DAG.getConstant(idx, MVT::i32));
6870 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6873 // Cases that are handled by instructions that take permute immediates
6874 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6875 // selected by the instruction selector.
6876 if (V2.getOpcode() == ISD::UNDEF) {
6877 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6878 PPC::isSplatShuffleMask(SVOp, 2) ||
6879 PPC::isSplatShuffleMask(SVOp, 4) ||
6880 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6881 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6882 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6883 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6884 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6885 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6886 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6887 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6888 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6893 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6894 // and produce a fixed permutation. If any of these match, do not lower to
6896 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6897 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6898 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6899 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6900 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6901 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6902 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6903 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6904 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6905 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6908 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6909 // perfect shuffle table to emit an optimal matching sequence.
6910 ArrayRef<int> PermMask = SVOp->getMask();
6912 unsigned PFIndexes[4];
6913 bool isFourElementShuffle = true;
6914 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6915 unsigned EltNo = 8; // Start out undef.
6916 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6917 if (PermMask[i*4+j] < 0)
6918 continue; // Undef, ignore it.
6920 unsigned ByteSource = PermMask[i*4+j];
6921 if ((ByteSource & 3) != j) {
6922 isFourElementShuffle = false;
6927 EltNo = ByteSource/4;
6928 } else if (EltNo != ByteSource/4) {
6929 isFourElementShuffle = false;
6933 PFIndexes[i] = EltNo;
6936 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6937 // perfect shuffle vector to determine if it is cost effective to do this as
6938 // discrete instructions, or whether we should use a vperm.
6939 // For now, we skip this for little endian until such time as we have a
6940 // little-endian perfect shuffle table.
6941 if (isFourElementShuffle && !isLittleEndian) {
6942 // Compute the index in the perfect shuffle table.
6943 unsigned PFTableIndex =
6944 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6946 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6947 unsigned Cost = (PFEntry >> 30);
6949 // Determining when to avoid vperm is tricky. Many things affect the cost
6950 // of vperm, particularly how many times the perm mask needs to be computed.
6951 // For example, if the perm mask can be hoisted out of a loop or is already
6952 // used (perhaps because there are multiple permutes with the same shuffle
6953 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6954 // the loop requires an extra register.
6956 // As a compromise, we only emit discrete instructions if the shuffle can be
6957 // generated in 3 or fewer operations. When we have loop information
6958 // available, if this block is within a loop, we should avoid using vperm
6959 // for 3-operation perms and use a constant pool load instead.
6961 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6964 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6965 // vector that will get spilled to the constant pool.
6966 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6968 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6969 // that it is in input element units, not in bytes. Convert now.
6971 // For little endian, the order of the input vectors is reversed, and
6972 // the permutation mask is complemented with respect to 31. This is
6973 // necessary to produce proper semantics with the big-endian-biased vperm
6975 EVT EltVT = V1.getValueType().getVectorElementType();
6976 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6978 SmallVector<SDValue, 16> ResultMask;
6979 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6980 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6982 for (unsigned j = 0; j != BytesPerElement; ++j)
6984 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6987 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6991 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6994 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6997 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7001 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7002 /// altivec comparison. If it is, return true and fill in Opc/isDot with
7003 /// information about the intrinsic.
7004 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7005 bool &isDot, const PPCSubtarget &Subtarget) {
7006 unsigned IntrinsicID =
7007 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7010 switch (IntrinsicID) {
7011 default: return false;
7012 // Comparison predicates.
7013 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
7014 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7015 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
7016 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
7017 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7018 case Intrinsic::ppc_altivec_vcmpequd_p:
7019 if (Subtarget.hasP8Altivec()) {
7027 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7028 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7029 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7030 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7031 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7032 case Intrinsic::ppc_altivec_vcmpgtsd_p:
7033 if (Subtarget.hasP8Altivec()) {
7041 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7042 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7043 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7044 case Intrinsic::ppc_altivec_vcmpgtud_p:
7045 if (Subtarget.hasP8Altivec()) {
7054 // Normal Comparisons.
7055 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
7056 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
7057 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
7058 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
7059 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
7060 case Intrinsic::ppc_altivec_vcmpequd:
7061 if (Subtarget.hasP8Altivec()) {
7069 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
7070 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
7071 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
7072 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
7073 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
7074 case Intrinsic::ppc_altivec_vcmpgtsd:
7075 if (Subtarget.hasP8Altivec()) {
7083 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
7084 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
7085 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
7086 case Intrinsic::ppc_altivec_vcmpgtud:
7087 if (Subtarget.hasP8Altivec()) {
7099 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7100 /// lower, do it, otherwise return null.
7101 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7102 SelectionDAG &DAG) const {
7103 // If this is a lowered altivec predicate compare, CompareOpc is set to the
7104 // opcode number of the comparison.
7108 if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7109 return SDValue(); // Don't custom lower most intrinsics.
7111 // If this is a non-dot comparison, make the VCMP node and we are done.
7113 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7114 Op.getOperand(1), Op.getOperand(2),
7115 DAG.getConstant(CompareOpc, MVT::i32));
7116 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7119 // Create the PPCISD altivec 'dot' comparison node.
7121 Op.getOperand(2), // LHS
7122 Op.getOperand(3), // RHS
7123 DAG.getConstant(CompareOpc, MVT::i32)
7125 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7126 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7128 // Now that we have the comparison, emit a copy from the CR to a GPR.
7129 // This is flagged to the above dot comparison.
7130 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7131 DAG.getRegister(PPC::CR6, MVT::i32),
7132 CompNode.getValue(1));
7134 // Unpack the result based on how the target uses it.
7135 unsigned BitNo; // Bit # of CR6.
7136 bool InvertBit; // Invert result?
7137 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7138 default: // Can't happen, don't crash on invalid number though.
7139 case 0: // Return the value of the EQ bit of CR6.
7140 BitNo = 0; InvertBit = false;
7142 case 1: // Return the inverted value of the EQ bit of CR6.
7143 BitNo = 0; InvertBit = true;
7145 case 2: // Return the value of the LT bit of CR6.
7146 BitNo = 2; InvertBit = false;
7148 case 3: // Return the inverted value of the LT bit of CR6.
7149 BitNo = 2; InvertBit = true;
7153 // Shift the bit into the low position.
7154 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7155 DAG.getConstant(8-(3-BitNo), MVT::i32));
7157 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7158 DAG.getConstant(1, MVT::i32));
7160 // If we are supposed to, toggle the bit.
7162 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7163 DAG.getConstant(1, MVT::i32));
7167 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7168 SelectionDAG &DAG) const {
7170 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7171 // instructions), but for smaller types, we need to first extend up to v2i32
7172 // before doing going farther.
7173 if (Op.getValueType() == MVT::v2i64) {
7174 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7175 if (ExtVT != MVT::v2i32) {
7176 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7177 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7178 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7179 ExtVT.getVectorElementType(), 4)));
7180 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7181 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7182 DAG.getValueType(MVT::v2i32));
7191 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7192 SelectionDAG &DAG) const {
7194 // Create a stack slot that is 16-byte aligned.
7195 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7196 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7197 EVT PtrVT = getPointerTy();
7198 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7200 // Store the input value into Value#0 of the stack slot.
7201 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7202 Op.getOperand(0), FIdx, MachinePointerInfo(),
7205 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7206 false, false, false, 0);
7209 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7210 SelectionDAG &DAG) const {
7212 SDNode *N = Op.getNode();
7214 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7215 "Unknown extract_vector_elt type");
7217 SDValue Value = N->getOperand(0);
7219 // The first part of this is like the store lowering except that we don't
7220 // need to track the chain.
7222 // The values are now known to be -1 (false) or 1 (true). To convert this
7223 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7224 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7225 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7227 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7228 // understand how to form the extending load.
7229 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7230 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7231 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7233 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7235 // Now convert to an integer and store.
7236 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7237 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7240 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7241 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7242 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7243 EVT PtrVT = getPointerTy();
7244 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7246 SDValue StoreChain = DAG.getEntryNode();
7247 SmallVector<SDValue, 2> Ops;
7248 Ops.push_back(StoreChain);
7249 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7250 Ops.push_back(Value);
7251 Ops.push_back(FIdx);
7253 SmallVector<EVT, 2> ValueVTs;
7254 ValueVTs.push_back(MVT::Other); // chain
7255 SDVTList VTs = DAG.getVTList(ValueVTs);
7257 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7258 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7260 // Extract the value requested.
7261 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7262 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7263 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7265 SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7266 PtrInfo.getWithOffset(Offset),
7267 false, false, false, 0);
7269 if (!Subtarget.useCRBits())
7272 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7275 /// Lowering for QPX v4i1 loads
7276 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7277 SelectionDAG &DAG) const {
7279 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7280 SDValue LoadChain = LN->getChain();
7281 SDValue BasePtr = LN->getBasePtr();
7283 if (Op.getValueType() == MVT::v4f64 ||
7284 Op.getValueType() == MVT::v4f32) {
7285 EVT MemVT = LN->getMemoryVT();
7286 unsigned Alignment = LN->getAlignment();
7288 // If this load is properly aligned, then it is legal.
7289 if (Alignment >= MemVT.getStoreSize())
7292 EVT ScalarVT = Op.getValueType().getScalarType(),
7293 ScalarMemVT = MemVT.getScalarType();
7294 unsigned Stride = ScalarMemVT.getStoreSize();
7296 SmallVector<SDValue, 8> Vals, LoadChains;
7297 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7299 if (ScalarVT != ScalarMemVT)
7301 DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7303 LN->getPointerInfo().getWithOffset(Idx*Stride),
7304 ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7305 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7309 DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7310 LN->getPointerInfo().getWithOffset(Idx*Stride),
7311 LN->isVolatile(), LN->isNonTemporal(),
7312 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7315 if (Idx == 0 && LN->isIndexed()) {
7316 assert(LN->getAddressingMode() == ISD::PRE_INC &&
7317 "Unknown addressing mode on vector load");
7318 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7319 LN->getAddressingMode());
7322 Vals.push_back(Load);
7323 LoadChains.push_back(Load.getValue(1));
7325 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7326 DAG.getConstant(Stride, BasePtr.getValueType()));
7329 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7330 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7331 Op.getValueType(), Vals);
7333 if (LN->isIndexed()) {
7334 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7335 return DAG.getMergeValues(RetOps, dl);
7338 SDValue RetOps[] = { Value, TF };
7339 return DAG.getMergeValues(RetOps, dl);
7342 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7343 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7345 // To lower v4i1 from a byte array, we load the byte elements of the
7346 // vector and then reuse the BUILD_VECTOR logic.
7348 SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7349 for (unsigned i = 0; i < 4; ++i) {
7350 SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7351 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7353 VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7354 dl, MVT::i32, LoadChain, Idx,
7355 LN->getPointerInfo().getWithOffset(i),
7356 MVT::i8 /* memory type */,
7357 LN->isVolatile(), LN->isNonTemporal(),
7359 1 /* alignment */, LN->getAAInfo()));
7360 VectElmtChains.push_back(VectElmts[i].getValue(1));
7363 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7364 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7366 SDValue RVals[] = { Value, LoadChain };
7367 return DAG.getMergeValues(RVals, dl);
7370 /// Lowering for QPX v4i1 stores
7371 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7372 SelectionDAG &DAG) const {
7374 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7375 SDValue StoreChain = SN->getChain();
7376 SDValue BasePtr = SN->getBasePtr();
7377 SDValue Value = SN->getValue();
7379 if (Value.getValueType() == MVT::v4f64 ||
7380 Value.getValueType() == MVT::v4f32) {
7381 EVT MemVT = SN->getMemoryVT();
7382 unsigned Alignment = SN->getAlignment();
7384 // If this store is properly aligned, then it is legal.
7385 if (Alignment >= MemVT.getStoreSize())
7388 EVT ScalarVT = Value.getValueType().getScalarType(),
7389 ScalarMemVT = MemVT.getScalarType();
7390 unsigned Stride = ScalarMemVT.getStoreSize();
7392 SmallVector<SDValue, 8> Stores;
7393 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7395 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7396 DAG.getConstant(Idx, getVectorIdxTy()));
7398 if (ScalarVT != ScalarMemVT)
7400 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7401 SN->getPointerInfo().getWithOffset(Idx*Stride),
7402 ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7403 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7406 DAG.getStore(StoreChain, dl, Ex, BasePtr,
7407 SN->getPointerInfo().getWithOffset(Idx*Stride),
7408 SN->isVolatile(), SN->isNonTemporal(),
7409 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7411 if (Idx == 0 && SN->isIndexed()) {
7412 assert(SN->getAddressingMode() == ISD::PRE_INC &&
7413 "Unknown addressing mode on vector store");
7414 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7415 SN->getAddressingMode());
7418 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7419 DAG.getConstant(Stride, BasePtr.getValueType()));
7420 Stores.push_back(Store);
7423 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7425 if (SN->isIndexed()) {
7426 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7427 return DAG.getMergeValues(RetOps, dl);
7433 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7434 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7436 // The values are now known to be -1 (false) or 1 (true). To convert this
7437 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7438 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7439 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7441 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7442 // understand how to form the extending load.
7443 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7444 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7445 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7447 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7449 // Now convert to an integer and store.
7450 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7451 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7454 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7455 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7456 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7457 EVT PtrVT = getPointerTy();
7458 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7460 SmallVector<SDValue, 2> Ops;
7461 Ops.push_back(StoreChain);
7462 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7463 Ops.push_back(Value);
7464 Ops.push_back(FIdx);
7466 SmallVector<EVT, 2> ValueVTs;
7467 ValueVTs.push_back(MVT::Other); // chain
7468 SDVTList VTs = DAG.getVTList(ValueVTs);
7470 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7471 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7473 // Move data into the byte array.
7474 SmallVector<SDValue, 4> Loads, LoadChains;
7475 for (unsigned i = 0; i < 4; ++i) {
7476 unsigned Offset = 4*i;
7477 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7478 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7480 Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7481 PtrInfo.getWithOffset(Offset),
7482 false, false, false, 0));
7483 LoadChains.push_back(Loads[i].getValue(1));
7486 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7488 SmallVector<SDValue, 4> Stores;
7489 for (unsigned i = 0; i < 4; ++i) {
7490 SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7491 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7493 Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7494 SN->getPointerInfo().getWithOffset(i),
7495 MVT::i8 /* memory type */,
7496 SN->isNonTemporal(), SN->isVolatile(),
7497 1 /* alignment */, SN->getAAInfo()));
7500 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7505 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7507 if (Op.getValueType() == MVT::v4i32) {
7508 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7510 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
7511 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7513 SDValue RHSSwap = // = vrlw RHS, 16
7514 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7516 // Shrinkify inputs to v8i16.
7517 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7518 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7519 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7521 // Low parts multiplied together, generating 32-bit results (we ignore the
7523 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7524 LHS, RHS, DAG, dl, MVT::v4i32);
7526 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7527 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7528 // Shift the high parts up 16 bits.
7529 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7531 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7532 } else if (Op.getValueType() == MVT::v8i16) {
7533 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7535 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7537 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7538 LHS, RHS, Zero, DAG, dl);
7539 } else if (Op.getValueType() == MVT::v16i8) {
7540 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7541 bool isLittleEndian = Subtarget.isLittleEndian();
7543 // Multiply the even 8-bit parts, producing 16-bit sums.
7544 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7545 LHS, RHS, DAG, dl, MVT::v8i16);
7546 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7548 // Multiply the odd 8-bit parts, producing 16-bit sums.
7549 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7550 LHS, RHS, DAG, dl, MVT::v8i16);
7551 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7553 // Merge the results together. Because vmuleub and vmuloub are
7554 // instructions with a big-endian bias, we must reverse the
7555 // element numbering and reverse the meaning of "odd" and "even"
7556 // when generating little endian code.
7558 for (unsigned i = 0; i != 8; ++i) {
7559 if (isLittleEndian) {
7561 Ops[i*2+1] = 2*i+16;
7564 Ops[i*2+1] = 2*i+1+16;
7568 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7570 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7572 llvm_unreachable("Unknown mul to lower!");
7576 /// LowerOperation - Provide custom lowering hooks for some operations.
7578 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7579 switch (Op.getOpcode()) {
7580 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7581 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7582 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7583 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7584 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7585 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7586 case ISD::SETCC: return LowerSETCC(Op, DAG);
7587 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
7588 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
7590 return LowerVASTART(Op, DAG, Subtarget);
7593 return LowerVAARG(Op, DAG, Subtarget);
7596 return LowerVACOPY(Op, DAG, Subtarget);
7598 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
7599 case ISD::DYNAMIC_STACKALLOC:
7600 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7602 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
7603 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
7605 case ISD::LOAD: return LowerLOAD(Op, DAG);
7606 case ISD::STORE: return LowerSTORE(Op, DAG);
7607 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
7608 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7609 case ISD::FP_TO_UINT:
7610 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
7612 case ISD::UINT_TO_FP:
7613 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7614 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7616 // Lower 64-bit shifts.
7617 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
7618 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
7619 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
7621 // Vector-related lowering.
7622 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7623 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7624 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7625 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7626 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
7627 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7628 case ISD::MUL: return LowerMUL(Op, DAG);
7630 // For counter-based loop handling.
7631 case ISD::INTRINSIC_W_CHAIN: return SDValue();
7633 // Frame & Return address.
7634 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7635 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7639 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7640 SmallVectorImpl<SDValue>&Results,
7641 SelectionDAG &DAG) const {
7643 switch (N->getOpcode()) {
7645 llvm_unreachable("Do not know how to custom type legalize this operation!");
7646 case ISD::READCYCLECOUNTER: {
7647 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7648 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7650 Results.push_back(RTB);
7651 Results.push_back(RTB.getValue(1));
7652 Results.push_back(RTB.getValue(2));
7655 case ISD::INTRINSIC_W_CHAIN: {
7656 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7657 Intrinsic::ppc_is_decremented_ctr_nonzero)
7660 assert(N->getValueType(0) == MVT::i1 &&
7661 "Unexpected result type for CTR decrement intrinsic");
7662 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7663 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7664 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7667 Results.push_back(NewInt);
7668 Results.push_back(NewInt.getValue(1));
7672 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7675 EVT VT = N->getValueType(0);
7677 if (VT == MVT::i64) {
7678 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7680 Results.push_back(NewNode);
7681 Results.push_back(NewNode.getValue(1));
7685 case ISD::FP_ROUND_INREG: {
7686 assert(N->getValueType(0) == MVT::ppcf128);
7687 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7688 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7689 MVT::f64, N->getOperand(0),
7690 DAG.getIntPtrConstant(0));
7691 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7692 MVT::f64, N->getOperand(0),
7693 DAG.getIntPtrConstant(1));
7695 // Add the two halves of the long double in round-to-zero mode.
7696 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7698 // We know the low half is about to be thrown away, so just use something
7700 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7704 case ISD::FP_TO_SINT:
7705 // LowerFP_TO_INT() can only handle f32 and f64.
7706 if (N->getOperand(0).getValueType() == MVT::ppcf128)
7708 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7714 //===----------------------------------------------------------------------===//
7715 // Other Lowering Code
7716 //===----------------------------------------------------------------------===//
7718 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7719 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7720 Function *Func = Intrinsic::getDeclaration(M, Id);
7721 return Builder.CreateCall(Func);
7724 // The mappings for emitLeading/TrailingFence is taken from
7725 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7726 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7727 AtomicOrdering Ord, bool IsStore,
7728 bool IsLoad) const {
7729 if (Ord == SequentiallyConsistent)
7730 return callIntrinsic(Builder, Intrinsic::ppc_sync);
7731 else if (isAtLeastRelease(Ord))
7732 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7737 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7738 AtomicOrdering Ord, bool IsStore,
7739 bool IsLoad) const {
7740 if (IsLoad && isAtLeastAcquire(Ord))
7741 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7742 // FIXME: this is too conservative, a dependent branch + isync is enough.
7743 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7744 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7745 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7751 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7752 unsigned AtomicSize,
7753 unsigned BinOpcode) const {
7754 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7755 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7757 auto LoadMnemonic = PPC::LDARX;
7758 auto StoreMnemonic = PPC::STDCX;
7759 switch (AtomicSize) {
7761 llvm_unreachable("Unexpected size of atomic entity");
7763 LoadMnemonic = PPC::LBARX;
7764 StoreMnemonic = PPC::STBCX;
7765 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7768 LoadMnemonic = PPC::LHARX;
7769 StoreMnemonic = PPC::STHCX;
7770 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7773 LoadMnemonic = PPC::LWARX;
7774 StoreMnemonic = PPC::STWCX;
7777 LoadMnemonic = PPC::LDARX;
7778 StoreMnemonic = PPC::STDCX;
7782 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7783 MachineFunction *F = BB->getParent();
7784 MachineFunction::iterator It = BB;
7787 unsigned dest = MI->getOperand(0).getReg();
7788 unsigned ptrA = MI->getOperand(1).getReg();
7789 unsigned ptrB = MI->getOperand(2).getReg();
7790 unsigned incr = MI->getOperand(3).getReg();
7791 DebugLoc dl = MI->getDebugLoc();
7793 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7794 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7795 F->insert(It, loopMBB);
7796 F->insert(It, exitMBB);
7797 exitMBB->splice(exitMBB->begin(), BB,
7798 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7799 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7801 MachineRegisterInfo &RegInfo = F->getRegInfo();
7802 unsigned TmpReg = (!BinOpcode) ? incr :
7803 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7804 : &PPC::GPRCRegClass);
7808 // fallthrough --> loopMBB
7809 BB->addSuccessor(loopMBB);
7812 // l[wd]arx dest, ptr
7813 // add r0, dest, incr
7814 // st[wd]cx. r0, ptr
7816 // fallthrough --> exitMBB
7818 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7819 .addReg(ptrA).addReg(ptrB);
7821 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7822 BuildMI(BB, dl, TII->get(StoreMnemonic))
7823 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7824 BuildMI(BB, dl, TII->get(PPC::BCC))
7825 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7826 BB->addSuccessor(loopMBB);
7827 BB->addSuccessor(exitMBB);
7836 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7837 MachineBasicBlock *BB,
7838 bool is8bit, // operation
7839 unsigned BinOpcode) const {
7840 // If we support part-word atomic mnemonics, just use them
7841 if (Subtarget.hasPartwordAtomics())
7842 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
7844 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7845 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7846 // In 64 bit mode we have to use 64 bits for addresses, even though the
7847 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
7848 // registers without caring whether they're 32 or 64, but here we're
7849 // doing actual arithmetic on the addresses.
7850 bool is64bit = Subtarget.isPPC64();
7851 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7853 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7854 MachineFunction *F = BB->getParent();
7855 MachineFunction::iterator It = BB;
7858 unsigned dest = MI->getOperand(0).getReg();
7859 unsigned ptrA = MI->getOperand(1).getReg();
7860 unsigned ptrB = MI->getOperand(2).getReg();
7861 unsigned incr = MI->getOperand(3).getReg();
7862 DebugLoc dl = MI->getDebugLoc();
7864 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7865 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7866 F->insert(It, loopMBB);
7867 F->insert(It, exitMBB);
7868 exitMBB->splice(exitMBB->begin(), BB,
7869 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7870 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7872 MachineRegisterInfo &RegInfo = F->getRegInfo();
7873 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7874 : &PPC::GPRCRegClass;
7875 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7876 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7877 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7878 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7879 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7880 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7881 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7882 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7883 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7884 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7885 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7887 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7891 // fallthrough --> loopMBB
7892 BB->addSuccessor(loopMBB);
7894 // The 4-byte load must be aligned, while a char or short may be
7895 // anywhere in the word. Hence all this nasty bookkeeping code.
7896 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7897 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7898 // xori shift, shift1, 24 [16]
7899 // rlwinm ptr, ptr1, 0, 0, 29
7900 // slw incr2, incr, shift
7901 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7902 // slw mask, mask2, shift
7904 // lwarx tmpDest, ptr
7905 // add tmp, tmpDest, incr2
7906 // andc tmp2, tmpDest, mask
7907 // and tmp3, tmp, mask
7908 // or tmp4, tmp3, tmp2
7911 // fallthrough --> exitMBB
7912 // srw dest, tmpDest, shift
7913 if (ptrA != ZeroReg) {
7914 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7915 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7916 .addReg(ptrA).addReg(ptrB);
7920 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7921 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7922 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7923 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7925 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7926 .addReg(Ptr1Reg).addImm(0).addImm(61);
7928 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7929 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7930 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7931 .addReg(incr).addReg(ShiftReg);
7933 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7935 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7936 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7938 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7939 .addReg(Mask2Reg).addReg(ShiftReg);
7942 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7943 .addReg(ZeroReg).addReg(PtrReg);
7945 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7946 .addReg(Incr2Reg).addReg(TmpDestReg);
7947 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7948 .addReg(TmpDestReg).addReg(MaskReg);
7949 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7950 .addReg(TmpReg).addReg(MaskReg);
7951 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7952 .addReg(Tmp3Reg).addReg(Tmp2Reg);
7953 BuildMI(BB, dl, TII->get(PPC::STWCX))
7954 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7955 BuildMI(BB, dl, TII->get(PPC::BCC))
7956 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7957 BB->addSuccessor(loopMBB);
7958 BB->addSuccessor(exitMBB);
7963 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7968 llvm::MachineBasicBlock*
7969 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7970 MachineBasicBlock *MBB) const {
7971 DebugLoc DL = MI->getDebugLoc();
7972 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7974 MachineFunction *MF = MBB->getParent();
7975 MachineRegisterInfo &MRI = MF->getRegInfo();
7977 const BasicBlock *BB = MBB->getBasicBlock();
7978 MachineFunction::iterator I = MBB;
7982 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7983 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7985 unsigned DstReg = MI->getOperand(0).getReg();
7986 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7987 assert(RC->hasType(MVT::i32) && "Invalid destination!");
7988 unsigned mainDstReg = MRI.createVirtualRegister(RC);
7989 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7991 MVT PVT = getPointerTy();
7992 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7993 "Invalid Pointer Size!");
7994 // For v = setjmp(buf), we generate
7997 // SjLjSetup mainMBB
8003 // buf[LabelOffset] = LR
8007 // v = phi(main, restore)
8010 MachineBasicBlock *thisMBB = MBB;
8011 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8012 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8013 MF->insert(I, mainMBB);
8014 MF->insert(I, sinkMBB);
8016 MachineInstrBuilder MIB;
8018 // Transfer the remainder of BB and its successor edges to sinkMBB.
8019 sinkMBB->splice(sinkMBB->begin(), MBB,
8020 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8021 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8023 // Note that the structure of the jmp_buf used here is not compatible
8024 // with that used by libc, and is not designed to be. Specifically, it
8025 // stores only those 'reserved' registers that LLVM does not otherwise
8026 // understand how to spill. Also, by convention, by the time this
8027 // intrinsic is called, Clang has already stored the frame address in the
8028 // first slot of the buffer and stack address in the third. Following the
8029 // X86 target code, we'll store the jump address in the second slot. We also
8030 // need to save the TOC pointer (R2) to handle jumps between shared
8031 // libraries, and that will be stored in the fourth slot. The thread
8032 // identifier (R13) is not affected.
8035 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8036 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8037 const int64_t BPOffset = 4 * PVT.getStoreSize();
8039 // Prepare IP either in reg.
8040 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8041 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8042 unsigned BufReg = MI->getOperand(1).getReg();
8044 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8045 setUsesTOCBasePtr(*MBB->getParent());
8046 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8050 MIB.setMemRefs(MMOBegin, MMOEnd);
8053 // Naked functions never have a base pointer, and so we use r1. For all
8054 // other functions, this decision must be delayed until during PEI.
8056 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8057 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8059 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8061 MIB = BuildMI(*thisMBB, MI, DL,
8062 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8066 MIB.setMemRefs(MMOBegin, MMOEnd);
8069 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8070 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8071 MIB.addRegMask(TRI->getNoPreservedMask());
8073 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8075 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8077 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8079 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8080 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8085 BuildMI(mainMBB, DL,
8086 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8089 if (Subtarget.isPPC64()) {
8090 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8092 .addImm(LabelOffset)
8095 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8097 .addImm(LabelOffset)
8101 MIB.setMemRefs(MMOBegin, MMOEnd);
8103 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8104 mainMBB->addSuccessor(sinkMBB);
8107 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8108 TII->get(PPC::PHI), DstReg)
8109 .addReg(mainDstReg).addMBB(mainMBB)
8110 .addReg(restoreDstReg).addMBB(thisMBB);
8112 MI->eraseFromParent();
8117 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8118 MachineBasicBlock *MBB) const {
8119 DebugLoc DL = MI->getDebugLoc();
8120 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8122 MachineFunction *MF = MBB->getParent();
8123 MachineRegisterInfo &MRI = MF->getRegInfo();
8126 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8127 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8129 MVT PVT = getPointerTy();
8130 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8131 "Invalid Pointer Size!");
8133 const TargetRegisterClass *RC =
8134 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8135 unsigned Tmp = MRI.createVirtualRegister(RC);
8136 // Since FP is only updated here but NOT referenced, it's treated as GPR.
8137 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8138 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8142 : (Subtarget.isSVR4ABI() &&
8143 MF->getTarget().getRelocationModel() == Reloc::PIC_
8147 MachineInstrBuilder MIB;
8149 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8150 const int64_t SPOffset = 2 * PVT.getStoreSize();
8151 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8152 const int64_t BPOffset = 4 * PVT.getStoreSize();
8154 unsigned BufReg = MI->getOperand(0).getReg();
8156 // Reload FP (the jumped-to function may not have had a
8157 // frame pointer, and if so, then its r31 will be restored
8159 if (PVT == MVT::i64) {
8160 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8164 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8168 MIB.setMemRefs(MMOBegin, MMOEnd);
8171 if (PVT == MVT::i64) {
8172 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8173 .addImm(LabelOffset)
8176 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8177 .addImm(LabelOffset)
8180 MIB.setMemRefs(MMOBegin, MMOEnd);
8183 if (PVT == MVT::i64) {
8184 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8188 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8192 MIB.setMemRefs(MMOBegin, MMOEnd);
8195 if (PVT == MVT::i64) {
8196 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8200 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8204 MIB.setMemRefs(MMOBegin, MMOEnd);
8207 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8208 setUsesTOCBasePtr(*MBB->getParent());
8209 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8213 MIB.setMemRefs(MMOBegin, MMOEnd);
8217 BuildMI(*MBB, MI, DL,
8218 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8219 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8221 MI->eraseFromParent();
8226 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8227 MachineBasicBlock *BB) const {
8228 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8229 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8230 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8231 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8232 // Call lowering should have added an r2 operand to indicate a dependence
8233 // on the TOC base pointer value. It can't however, because there is no
8234 // way to mark the dependence as implicit there, and so the stackmap code
8235 // will confuse it with a regular operand. Instead, add the dependence
8237 setUsesTOCBasePtr(*BB->getParent());
8238 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8241 return emitPatchPoint(MI, BB);
8244 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8245 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8246 return emitEHSjLjSetJmp(MI, BB);
8247 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8248 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8249 return emitEHSjLjLongJmp(MI, BB);
8252 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8254 // To "insert" these instructions we actually have to insert their
8255 // control-flow patterns.
8256 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8257 MachineFunction::iterator It = BB;
8260 MachineFunction *F = BB->getParent();
8262 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8263 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8264 MI->getOpcode() == PPC::SELECT_I4 ||
8265 MI->getOpcode() == PPC::SELECT_I8)) {
8266 SmallVector<MachineOperand, 2> Cond;
8267 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8268 MI->getOpcode() == PPC::SELECT_CC_I8)
8269 Cond.push_back(MI->getOperand(4));
8271 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8272 Cond.push_back(MI->getOperand(1));
8274 DebugLoc dl = MI->getDebugLoc();
8275 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8276 Cond, MI->getOperand(2).getReg(),
8277 MI->getOperand(3).getReg());
8278 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8279 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8280 MI->getOpcode() == PPC::SELECT_CC_F4 ||
8281 MI->getOpcode() == PPC::SELECT_CC_F8 ||
8282 MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8283 MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8284 MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8285 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8286 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8287 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8288 MI->getOpcode() == PPC::SELECT_I4 ||
8289 MI->getOpcode() == PPC::SELECT_I8 ||
8290 MI->getOpcode() == PPC::SELECT_F4 ||
8291 MI->getOpcode() == PPC::SELECT_F8 ||
8292 MI->getOpcode() == PPC::SELECT_QFRC ||
8293 MI->getOpcode() == PPC::SELECT_QSRC ||
8294 MI->getOpcode() == PPC::SELECT_QBRC ||
8295 MI->getOpcode() == PPC::SELECT_VRRC ||
8296 MI->getOpcode() == PPC::SELECT_VSFRC ||
8297 MI->getOpcode() == PPC::SELECT_VSRC) {
8298 // The incoming instruction knows the destination vreg to set, the
8299 // condition code register to branch on, the true/false values to
8300 // select between, and a branch opcode to use.
8305 // cmpTY ccX, r1, r2
8307 // fallthrough --> copy0MBB
8308 MachineBasicBlock *thisMBB = BB;
8309 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8310 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8311 DebugLoc dl = MI->getDebugLoc();
8312 F->insert(It, copy0MBB);
8313 F->insert(It, sinkMBB);
8315 // Transfer the remainder of BB and its successor edges to sinkMBB.
8316 sinkMBB->splice(sinkMBB->begin(), BB,
8317 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8318 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8320 // Next, add the true and fallthrough blocks as its successors.
8321 BB->addSuccessor(copy0MBB);
8322 BB->addSuccessor(sinkMBB);
8324 if (MI->getOpcode() == PPC::SELECT_I4 ||
8325 MI->getOpcode() == PPC::SELECT_I8 ||
8326 MI->getOpcode() == PPC::SELECT_F4 ||
8327 MI->getOpcode() == PPC::SELECT_F8 ||
8328 MI->getOpcode() == PPC::SELECT_QFRC ||
8329 MI->getOpcode() == PPC::SELECT_QSRC ||
8330 MI->getOpcode() == PPC::SELECT_QBRC ||
8331 MI->getOpcode() == PPC::SELECT_VRRC ||
8332 MI->getOpcode() == PPC::SELECT_VSFRC ||
8333 MI->getOpcode() == PPC::SELECT_VSRC) {
8334 BuildMI(BB, dl, TII->get(PPC::BC))
8335 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8337 unsigned SelectPred = MI->getOperand(4).getImm();
8338 BuildMI(BB, dl, TII->get(PPC::BCC))
8339 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8343 // %FalseValue = ...
8344 // # fallthrough to sinkMBB
8347 // Update machine-CFG edges
8348 BB->addSuccessor(sinkMBB);
8351 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8354 BuildMI(*BB, BB->begin(), dl,
8355 TII->get(PPC::PHI), MI->getOperand(0).getReg())
8356 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8357 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8358 } else if (MI->getOpcode() == PPC::ReadTB) {
8359 // To read the 64-bit time-base register on a 32-bit target, we read the
8360 // two halves. Should the counter have wrapped while it was being read, we
8361 // need to try again.
8364 // mfspr Rx,TBU # load from TBU
8365 // mfspr Ry,TB # load from TB
8366 // mfspr Rz,TBU # load from TBU
8367 // cmpw crX,Rx,Rz # check if ‘old’=’new’
8368 // bne readLoop # branch if they're not equal
8371 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8372 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8373 DebugLoc dl = MI->getDebugLoc();
8374 F->insert(It, readMBB);
8375 F->insert(It, sinkMBB);
8377 // Transfer the remainder of BB and its successor edges to sinkMBB.
8378 sinkMBB->splice(sinkMBB->begin(), BB,
8379 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8380 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8382 BB->addSuccessor(readMBB);
8385 MachineRegisterInfo &RegInfo = F->getRegInfo();
8386 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8387 unsigned LoReg = MI->getOperand(0).getReg();
8388 unsigned HiReg = MI->getOperand(1).getReg();
8390 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8391 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8392 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8394 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8396 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8397 .addReg(HiReg).addReg(ReadAgainReg);
8398 BuildMI(BB, dl, TII->get(PPC::BCC))
8399 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8401 BB->addSuccessor(readMBB);
8402 BB->addSuccessor(sinkMBB);
8404 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8405 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8406 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8407 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8408 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8409 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8410 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8411 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8413 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8414 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8415 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8416 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8417 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8418 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8419 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8420 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8422 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8423 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8424 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8425 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8426 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8427 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8428 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8429 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8431 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8432 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8433 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8434 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8435 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8436 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8437 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8438 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8440 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8441 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8442 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8443 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8444 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8445 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8446 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8447 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8449 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8450 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8451 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8452 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8453 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8454 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8455 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8456 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8458 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8459 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8460 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8461 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8462 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8463 BB = EmitAtomicBinary(MI, BB, 4, 0);
8464 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8465 BB = EmitAtomicBinary(MI, BB, 8, 0);
8467 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8468 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8469 (Subtarget.hasPartwordAtomics() &&
8470 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8471 (Subtarget.hasPartwordAtomics() &&
8472 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8473 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8475 auto LoadMnemonic = PPC::LDARX;
8476 auto StoreMnemonic = PPC::STDCX;
8477 switch(MI->getOpcode()) {
8479 llvm_unreachable("Compare and swap of unknown size");
8480 case PPC::ATOMIC_CMP_SWAP_I8:
8481 LoadMnemonic = PPC::LBARX;
8482 StoreMnemonic = PPC::STBCX;
8483 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8485 case PPC::ATOMIC_CMP_SWAP_I16:
8486 LoadMnemonic = PPC::LHARX;
8487 StoreMnemonic = PPC::STHCX;
8488 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8490 case PPC::ATOMIC_CMP_SWAP_I32:
8491 LoadMnemonic = PPC::LWARX;
8492 StoreMnemonic = PPC::STWCX;
8494 case PPC::ATOMIC_CMP_SWAP_I64:
8495 LoadMnemonic = PPC::LDARX;
8496 StoreMnemonic = PPC::STDCX;
8499 unsigned dest = MI->getOperand(0).getReg();
8500 unsigned ptrA = MI->getOperand(1).getReg();
8501 unsigned ptrB = MI->getOperand(2).getReg();
8502 unsigned oldval = MI->getOperand(3).getReg();
8503 unsigned newval = MI->getOperand(4).getReg();
8504 DebugLoc dl = MI->getDebugLoc();
8506 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8507 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8508 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8509 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8510 F->insert(It, loop1MBB);
8511 F->insert(It, loop2MBB);
8512 F->insert(It, midMBB);
8513 F->insert(It, exitMBB);
8514 exitMBB->splice(exitMBB->begin(), BB,
8515 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8516 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8520 // fallthrough --> loopMBB
8521 BB->addSuccessor(loop1MBB);
8524 // l[bhwd]arx dest, ptr
8525 // cmp[wd] dest, oldval
8528 // st[bhwd]cx. newval, ptr
8532 // st[bhwd]cx. dest, ptr
8535 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8536 .addReg(ptrA).addReg(ptrB);
8537 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8538 .addReg(oldval).addReg(dest);
8539 BuildMI(BB, dl, TII->get(PPC::BCC))
8540 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8541 BB->addSuccessor(loop2MBB);
8542 BB->addSuccessor(midMBB);
8545 BuildMI(BB, dl, TII->get(StoreMnemonic))
8546 .addReg(newval).addReg(ptrA).addReg(ptrB);
8547 BuildMI(BB, dl, TII->get(PPC::BCC))
8548 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8549 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8550 BB->addSuccessor(loop1MBB);
8551 BB->addSuccessor(exitMBB);
8554 BuildMI(BB, dl, TII->get(StoreMnemonic))
8555 .addReg(dest).addReg(ptrA).addReg(ptrB);
8556 BB->addSuccessor(exitMBB);
8561 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8562 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8563 // We must use 64-bit registers for addresses when targeting 64-bit,
8564 // since we're actually doing arithmetic on them. Other registers
8566 bool is64bit = Subtarget.isPPC64();
8567 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8569 unsigned dest = MI->getOperand(0).getReg();
8570 unsigned ptrA = MI->getOperand(1).getReg();
8571 unsigned ptrB = MI->getOperand(2).getReg();
8572 unsigned oldval = MI->getOperand(3).getReg();
8573 unsigned newval = MI->getOperand(4).getReg();
8574 DebugLoc dl = MI->getDebugLoc();
8576 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8577 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8578 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8579 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8580 F->insert(It, loop1MBB);
8581 F->insert(It, loop2MBB);
8582 F->insert(It, midMBB);
8583 F->insert(It, exitMBB);
8584 exitMBB->splice(exitMBB->begin(), BB,
8585 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8586 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8588 MachineRegisterInfo &RegInfo = F->getRegInfo();
8589 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8590 : &PPC::GPRCRegClass;
8591 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8592 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8593 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8594 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8595 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8596 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8597 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8598 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8599 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8600 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8601 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8602 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8603 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8605 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8606 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8609 // fallthrough --> loopMBB
8610 BB->addSuccessor(loop1MBB);
8612 // The 4-byte load must be aligned, while a char or short may be
8613 // anywhere in the word. Hence all this nasty bookkeeping code.
8614 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8615 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8616 // xori shift, shift1, 24 [16]
8617 // rlwinm ptr, ptr1, 0, 0, 29
8618 // slw newval2, newval, shift
8619 // slw oldval2, oldval,shift
8620 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8621 // slw mask, mask2, shift
8622 // and newval3, newval2, mask
8623 // and oldval3, oldval2, mask
8625 // lwarx tmpDest, ptr
8626 // and tmp, tmpDest, mask
8627 // cmpw tmp, oldval3
8630 // andc tmp2, tmpDest, mask
8631 // or tmp4, tmp2, newval3
8636 // stwcx. tmpDest, ptr
8638 // srw dest, tmpDest, shift
8639 if (ptrA != ZeroReg) {
8640 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8641 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8642 .addReg(ptrA).addReg(ptrB);
8646 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8647 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8648 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8649 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8651 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8652 .addReg(Ptr1Reg).addImm(0).addImm(61);
8654 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8655 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8656 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8657 .addReg(newval).addReg(ShiftReg);
8658 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8659 .addReg(oldval).addReg(ShiftReg);
8661 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8663 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8664 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8665 .addReg(Mask3Reg).addImm(65535);
8667 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8668 .addReg(Mask2Reg).addReg(ShiftReg);
8669 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8670 .addReg(NewVal2Reg).addReg(MaskReg);
8671 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8672 .addReg(OldVal2Reg).addReg(MaskReg);
8675 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8676 .addReg(ZeroReg).addReg(PtrReg);
8677 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8678 .addReg(TmpDestReg).addReg(MaskReg);
8679 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8680 .addReg(TmpReg).addReg(OldVal3Reg);
8681 BuildMI(BB, dl, TII->get(PPC::BCC))
8682 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8683 BB->addSuccessor(loop2MBB);
8684 BB->addSuccessor(midMBB);
8687 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8688 .addReg(TmpDestReg).addReg(MaskReg);
8689 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8690 .addReg(Tmp2Reg).addReg(NewVal3Reg);
8691 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8692 .addReg(ZeroReg).addReg(PtrReg);
8693 BuildMI(BB, dl, TII->get(PPC::BCC))
8694 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8695 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8696 BB->addSuccessor(loop1MBB);
8697 BB->addSuccessor(exitMBB);
8700 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8701 .addReg(ZeroReg).addReg(PtrReg);
8702 BB->addSuccessor(exitMBB);
8707 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8709 } else if (MI->getOpcode() == PPC::FADDrtz) {
8710 // This pseudo performs an FADD with rounding mode temporarily forced
8711 // to round-to-zero. We emit this via custom inserter since the FPSCR
8712 // is not modeled at the SelectionDAG level.
8713 unsigned Dest = MI->getOperand(0).getReg();
8714 unsigned Src1 = MI->getOperand(1).getReg();
8715 unsigned Src2 = MI->getOperand(2).getReg();
8716 DebugLoc dl = MI->getDebugLoc();
8718 MachineRegisterInfo &RegInfo = F->getRegInfo();
8719 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8721 // Save FPSCR value.
8722 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8724 // Set rounding mode to round-to-zero.
8725 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8726 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8728 // Perform addition.
8729 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8731 // Restore FPSCR value.
8732 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8733 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8734 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8735 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8736 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8737 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8738 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8739 PPC::ANDIo8 : PPC::ANDIo;
8740 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8741 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8743 MachineRegisterInfo &RegInfo = F->getRegInfo();
8744 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8745 &PPC::GPRCRegClass :
8746 &PPC::G8RCRegClass);
8748 DebugLoc dl = MI->getDebugLoc();
8749 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8750 .addReg(MI->getOperand(1).getReg()).addImm(1);
8751 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8752 MI->getOperand(0).getReg())
8753 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8754 } else if (MI->getOpcode() == PPC::TCHECK_RET) {
8755 DebugLoc Dl = MI->getDebugLoc();
8756 MachineRegisterInfo &RegInfo = F->getRegInfo();
8757 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8758 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
8761 llvm_unreachable("Unexpected instr type to insert");
8764 MI->eraseFromParent(); // The pseudo instruction is gone now.
8768 //===----------------------------------------------------------------------===//
8769 // Target Optimization Hooks
8770 //===----------------------------------------------------------------------===//
8772 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8773 DAGCombinerInfo &DCI,
8774 unsigned &RefinementSteps,
8775 bool &UseOneConstNR) const {
8776 EVT VT = Operand.getValueType();
8777 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8778 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8779 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8780 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8781 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8782 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8783 // Convergence is quadratic, so we essentially double the number of digits
8784 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8785 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8786 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8787 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8788 if (VT.getScalarType() == MVT::f64)
8790 UseOneConstNR = true;
8791 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8796 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8797 DAGCombinerInfo &DCI,
8798 unsigned &RefinementSteps) const {
8799 EVT VT = Operand.getValueType();
8800 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8801 (VT == MVT::f64 && Subtarget.hasFRE()) ||
8802 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8803 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8804 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8805 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8806 // Convergence is quadratic, so we essentially double the number of digits
8807 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8808 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8809 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8810 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8811 if (VT.getScalarType() == MVT::f64)
8813 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8818 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8819 // Note: This functionality is used only when unsafe-fp-math is enabled, and
8820 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8821 // enabled for division), this functionality is redundant with the default
8822 // combiner logic (once the division -> reciprocal/multiply transformation
8823 // has taken place). As a result, this matters more for older cores than for
8826 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8827 // reciprocal if there are two or more FDIVs (for embedded cores with only
8828 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8829 switch (Subtarget.getDarwinDirective()) {
8831 return NumUsers > 2;
8834 case PPC::DIR_E500mc:
8835 case PPC::DIR_E5500:
8836 return NumUsers > 1;
8840 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8841 unsigned Bytes, int Dist,
8842 SelectionDAG &DAG) {
8843 if (VT.getSizeInBits() / 8 != Bytes)
8846 SDValue BaseLoc = Base->getBasePtr();
8847 if (Loc.getOpcode() == ISD::FrameIndex) {
8848 if (BaseLoc.getOpcode() != ISD::FrameIndex)
8850 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8851 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
8852 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8853 int FS = MFI->getObjectSize(FI);
8854 int BFS = MFI->getObjectSize(BFI);
8855 if (FS != BFS || FS != (int)Bytes) return false;
8856 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8860 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8861 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8864 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8865 const GlobalValue *GV1 = nullptr;
8866 const GlobalValue *GV2 = nullptr;
8867 int64_t Offset1 = 0;
8868 int64_t Offset2 = 0;
8869 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8870 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8871 if (isGA1 && isGA2 && GV1 == GV2)
8872 return Offset1 == (Offset2 + Dist*Bytes);
8876 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8877 // not enforce equality of the chain operands.
8878 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8879 unsigned Bytes, int Dist,
8880 SelectionDAG &DAG) {
8881 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8882 EVT VT = LS->getMemoryVT();
8883 SDValue Loc = LS->getBasePtr();
8884 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8887 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8889 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8890 default: return false;
8891 case Intrinsic::ppc_qpx_qvlfd:
8892 case Intrinsic::ppc_qpx_qvlfda:
8895 case Intrinsic::ppc_qpx_qvlfs:
8896 case Intrinsic::ppc_qpx_qvlfsa:
8899 case Intrinsic::ppc_qpx_qvlfcd:
8900 case Intrinsic::ppc_qpx_qvlfcda:
8903 case Intrinsic::ppc_qpx_qvlfcs:
8904 case Intrinsic::ppc_qpx_qvlfcsa:
8907 case Intrinsic::ppc_qpx_qvlfiwa:
8908 case Intrinsic::ppc_qpx_qvlfiwz:
8909 case Intrinsic::ppc_altivec_lvx:
8910 case Intrinsic::ppc_altivec_lvxl:
8911 case Intrinsic::ppc_vsx_lxvw4x:
8914 case Intrinsic::ppc_vsx_lxvd2x:
8917 case Intrinsic::ppc_altivec_lvebx:
8920 case Intrinsic::ppc_altivec_lvehx:
8923 case Intrinsic::ppc_altivec_lvewx:
8928 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8931 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8933 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8934 default: return false;
8935 case Intrinsic::ppc_qpx_qvstfd:
8936 case Intrinsic::ppc_qpx_qvstfda:
8939 case Intrinsic::ppc_qpx_qvstfs:
8940 case Intrinsic::ppc_qpx_qvstfsa:
8943 case Intrinsic::ppc_qpx_qvstfcd:
8944 case Intrinsic::ppc_qpx_qvstfcda:
8947 case Intrinsic::ppc_qpx_qvstfcs:
8948 case Intrinsic::ppc_qpx_qvstfcsa:
8951 case Intrinsic::ppc_qpx_qvstfiw:
8952 case Intrinsic::ppc_qpx_qvstfiwa:
8953 case Intrinsic::ppc_altivec_stvx:
8954 case Intrinsic::ppc_altivec_stvxl:
8955 case Intrinsic::ppc_vsx_stxvw4x:
8958 case Intrinsic::ppc_vsx_stxvd2x:
8961 case Intrinsic::ppc_altivec_stvebx:
8964 case Intrinsic::ppc_altivec_stvehx:
8967 case Intrinsic::ppc_altivec_stvewx:
8972 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8978 // Return true is there is a nearyby consecutive load to the one provided
8979 // (regardless of alignment). We search up and down the chain, looking though
8980 // token factors and other loads (but nothing else). As a result, a true result
8981 // indicates that it is safe to create a new consecutive load adjacent to the
8983 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8984 SDValue Chain = LD->getChain();
8985 EVT VT = LD->getMemoryVT();
8987 SmallSet<SDNode *, 16> LoadRoots;
8988 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8989 SmallSet<SDNode *, 16> Visited;
8991 // First, search up the chain, branching to follow all token-factor operands.
8992 // If we find a consecutive load, then we're done, otherwise, record all
8993 // nodes just above the top-level loads and token factors.
8994 while (!Queue.empty()) {
8995 SDNode *ChainNext = Queue.pop_back_val();
8996 if (!Visited.insert(ChainNext).second)
8999 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9000 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9003 if (!Visited.count(ChainLD->getChain().getNode()))
9004 Queue.push_back(ChainLD->getChain().getNode());
9005 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9006 for (const SDUse &O : ChainNext->ops())
9007 if (!Visited.count(O.getNode()))
9008 Queue.push_back(O.getNode());
9010 LoadRoots.insert(ChainNext);
9013 // Second, search down the chain, starting from the top-level nodes recorded
9014 // in the first phase. These top-level nodes are the nodes just above all
9015 // loads and token factors. Starting with their uses, recursively look though
9016 // all loads (just the chain uses) and token factors to find a consecutive
9021 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9022 IE = LoadRoots.end(); I != IE; ++I) {
9023 Queue.push_back(*I);
9025 while (!Queue.empty()) {
9026 SDNode *LoadRoot = Queue.pop_back_val();
9027 if (!Visited.insert(LoadRoot).second)
9030 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9031 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9034 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9035 UE = LoadRoot->use_end(); UI != UE; ++UI)
9036 if (((isa<MemSDNode>(*UI) &&
9037 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9038 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9039 Queue.push_back(*UI);
9046 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9047 DAGCombinerInfo &DCI) const {
9048 SelectionDAG &DAG = DCI.DAG;
9051 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9052 // If we're tracking CR bits, we need to be careful that we don't have:
9053 // trunc(binary-ops(zext(x), zext(y)))
9055 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9056 // such that we're unnecessarily moving things into GPRs when it would be
9057 // better to keep them in CR bits.
9059 // Note that trunc here can be an actual i1 trunc, or can be the effective
9060 // truncation that comes from a setcc or select_cc.
9061 if (N->getOpcode() == ISD::TRUNCATE &&
9062 N->getValueType(0) != MVT::i1)
9065 if (N->getOperand(0).getValueType() != MVT::i32 &&
9066 N->getOperand(0).getValueType() != MVT::i64)
9069 if (N->getOpcode() == ISD::SETCC ||
9070 N->getOpcode() == ISD::SELECT_CC) {
9071 // If we're looking at a comparison, then we need to make sure that the
9072 // high bits (all except for the first) don't matter the result.
9074 cast<CondCodeSDNode>(N->getOperand(
9075 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9076 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9078 if (ISD::isSignedIntSetCC(CC)) {
9079 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9080 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9082 } else if (ISD::isUnsignedIntSetCC(CC)) {
9083 if (!DAG.MaskedValueIsZero(N->getOperand(0),
9084 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9085 !DAG.MaskedValueIsZero(N->getOperand(1),
9086 APInt::getHighBitsSet(OpBits, OpBits-1)))
9089 // This is neither a signed nor an unsigned comparison, just make sure
9090 // that the high bits are equal.
9091 APInt Op1Zero, Op1One;
9092 APInt Op2Zero, Op2One;
9093 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9094 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9096 // We don't really care about what is known about the first bit (if
9097 // anything), so clear it in all masks prior to comparing them.
9098 Op1Zero.clearBit(0); Op1One.clearBit(0);
9099 Op2Zero.clearBit(0); Op2One.clearBit(0);
9101 if (Op1Zero != Op2Zero || Op1One != Op2One)
9106 // We now know that the higher-order bits are irrelevant, we just need to
9107 // make sure that all of the intermediate operations are bit operations, and
9108 // all inputs are extensions.
9109 if (N->getOperand(0).getOpcode() != ISD::AND &&
9110 N->getOperand(0).getOpcode() != ISD::OR &&
9111 N->getOperand(0).getOpcode() != ISD::XOR &&
9112 N->getOperand(0).getOpcode() != ISD::SELECT &&
9113 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9114 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9115 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9116 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9117 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9120 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9121 N->getOperand(1).getOpcode() != ISD::AND &&
9122 N->getOperand(1).getOpcode() != ISD::OR &&
9123 N->getOperand(1).getOpcode() != ISD::XOR &&
9124 N->getOperand(1).getOpcode() != ISD::SELECT &&
9125 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9126 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9127 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9128 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9129 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9132 SmallVector<SDValue, 4> Inputs;
9133 SmallVector<SDValue, 8> BinOps, PromOps;
9134 SmallPtrSet<SDNode *, 16> Visited;
9136 for (unsigned i = 0; i < 2; ++i) {
9137 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9138 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9139 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9140 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9141 isa<ConstantSDNode>(N->getOperand(i)))
9142 Inputs.push_back(N->getOperand(i));
9144 BinOps.push_back(N->getOperand(i));
9146 if (N->getOpcode() == ISD::TRUNCATE)
9150 // Visit all inputs, collect all binary operations (and, or, xor and
9151 // select) that are all fed by extensions.
9152 while (!BinOps.empty()) {
9153 SDValue BinOp = BinOps.back();
9156 if (!Visited.insert(BinOp.getNode()).second)
9159 PromOps.push_back(BinOp);
9161 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9162 // The condition of the select is not promoted.
9163 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9165 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9168 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9169 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9170 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9171 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9172 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9173 Inputs.push_back(BinOp.getOperand(i));
9174 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9175 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9176 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9177 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9178 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9179 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9180 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9181 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9182 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9183 BinOps.push_back(BinOp.getOperand(i));
9185 // We have an input that is not an extension or another binary
9186 // operation; we'll abort this transformation.
9192 // Make sure that this is a self-contained cluster of operations (which
9193 // is not quite the same thing as saying that everything has only one
9195 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9196 if (isa<ConstantSDNode>(Inputs[i]))
9199 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9200 UE = Inputs[i].getNode()->use_end();
9203 if (User != N && !Visited.count(User))
9206 // Make sure that we're not going to promote the non-output-value
9207 // operand(s) or SELECT or SELECT_CC.
9208 // FIXME: Although we could sometimes handle this, and it does occur in
9209 // practice that one of the condition inputs to the select is also one of
9210 // the outputs, we currently can't deal with this.
9211 if (User->getOpcode() == ISD::SELECT) {
9212 if (User->getOperand(0) == Inputs[i])
9214 } else if (User->getOpcode() == ISD::SELECT_CC) {
9215 if (User->getOperand(0) == Inputs[i] ||
9216 User->getOperand(1) == Inputs[i])
9222 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9223 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9224 UE = PromOps[i].getNode()->use_end();
9227 if (User != N && !Visited.count(User))
9230 // Make sure that we're not going to promote the non-output-value
9231 // operand(s) or SELECT or SELECT_CC.
9232 // FIXME: Although we could sometimes handle this, and it does occur in
9233 // practice that one of the condition inputs to the select is also one of
9234 // the outputs, we currently can't deal with this.
9235 if (User->getOpcode() == ISD::SELECT) {
9236 if (User->getOperand(0) == PromOps[i])
9238 } else if (User->getOpcode() == ISD::SELECT_CC) {
9239 if (User->getOperand(0) == PromOps[i] ||
9240 User->getOperand(1) == PromOps[i])
9246 // Replace all inputs with the extension operand.
9247 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9248 // Constants may have users outside the cluster of to-be-promoted nodes,
9249 // and so we need to replace those as we do the promotions.
9250 if (isa<ConstantSDNode>(Inputs[i]))
9253 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9256 // Replace all operations (these are all the same, but have a different
9257 // (i1) return type). DAG.getNode will validate that the types of
9258 // a binary operator match, so go through the list in reverse so that
9259 // we've likely promoted both operands first. Any intermediate truncations or
9260 // extensions disappear.
9261 while (!PromOps.empty()) {
9262 SDValue PromOp = PromOps.back();
9265 if (PromOp.getOpcode() == ISD::TRUNCATE ||
9266 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9267 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9268 PromOp.getOpcode() == ISD::ANY_EXTEND) {
9269 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9270 PromOp.getOperand(0).getValueType() != MVT::i1) {
9271 // The operand is not yet ready (see comment below).
9272 PromOps.insert(PromOps.begin(), PromOp);
9276 SDValue RepValue = PromOp.getOperand(0);
9277 if (isa<ConstantSDNode>(RepValue))
9278 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9280 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9285 switch (PromOp.getOpcode()) {
9286 default: C = 0; break;
9287 case ISD::SELECT: C = 1; break;
9288 case ISD::SELECT_CC: C = 2; break;
9291 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9292 PromOp.getOperand(C).getValueType() != MVT::i1) ||
9293 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9294 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9295 // The to-be-promoted operands of this node have not yet been
9296 // promoted (this should be rare because we're going through the
9297 // list backward, but if one of the operands has several users in
9298 // this cluster of to-be-promoted nodes, it is possible).
9299 PromOps.insert(PromOps.begin(), PromOp);
9303 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9304 PromOp.getNode()->op_end());
9306 // If there are any constant inputs, make sure they're replaced now.
9307 for (unsigned i = 0; i < 2; ++i)
9308 if (isa<ConstantSDNode>(Ops[C+i]))
9309 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9311 DAG.ReplaceAllUsesOfValueWith(PromOp,
9312 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9315 // Now we're left with the initial truncation itself.
9316 if (N->getOpcode() == ISD::TRUNCATE)
9317 return N->getOperand(0);
9319 // Otherwise, this is a comparison. The operands to be compared have just
9320 // changed type (to i1), but everything else is the same.
9321 return SDValue(N, 0);
9324 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9325 DAGCombinerInfo &DCI) const {
9326 SelectionDAG &DAG = DCI.DAG;
9329 // If we're tracking CR bits, we need to be careful that we don't have:
9330 // zext(binary-ops(trunc(x), trunc(y)))
9332 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9333 // such that we're unnecessarily moving things into CR bits that can more
9334 // efficiently stay in GPRs. Note that if we're not certain that the high
9335 // bits are set as required by the final extension, we still may need to do
9336 // some masking to get the proper behavior.
9338 // This same functionality is important on PPC64 when dealing with
9339 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9340 // the return values of functions. Because it is so similar, it is handled
9343 if (N->getValueType(0) != MVT::i32 &&
9344 N->getValueType(0) != MVT::i64)
9347 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9348 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9351 if (N->getOperand(0).getOpcode() != ISD::AND &&
9352 N->getOperand(0).getOpcode() != ISD::OR &&
9353 N->getOperand(0).getOpcode() != ISD::XOR &&
9354 N->getOperand(0).getOpcode() != ISD::SELECT &&
9355 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9358 SmallVector<SDValue, 4> Inputs;
9359 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9360 SmallPtrSet<SDNode *, 16> Visited;
9362 // Visit all inputs, collect all binary operations (and, or, xor and
9363 // select) that are all fed by truncations.
9364 while (!BinOps.empty()) {
9365 SDValue BinOp = BinOps.back();
9368 if (!Visited.insert(BinOp.getNode()).second)
9371 PromOps.push_back(BinOp);
9373 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9374 // The condition of the select is not promoted.
9375 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9377 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9380 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9381 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9382 Inputs.push_back(BinOp.getOperand(i));
9383 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9384 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9385 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9386 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9387 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9388 BinOps.push_back(BinOp.getOperand(i));
9390 // We have an input that is not a truncation or another binary
9391 // operation; we'll abort this transformation.
9397 // The operands of a select that must be truncated when the select is
9398 // promoted because the operand is actually part of the to-be-promoted set.
9399 DenseMap<SDNode *, EVT> SelectTruncOp[2];
9401 // Make sure that this is a self-contained cluster of operations (which
9402 // is not quite the same thing as saying that everything has only one
9404 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9405 if (isa<ConstantSDNode>(Inputs[i]))
9408 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9409 UE = Inputs[i].getNode()->use_end();
9412 if (User != N && !Visited.count(User))
9415 // If we're going to promote the non-output-value operand(s) or SELECT or
9416 // SELECT_CC, record them for truncation.
9417 if (User->getOpcode() == ISD::SELECT) {
9418 if (User->getOperand(0) == Inputs[i])
9419 SelectTruncOp[0].insert(std::make_pair(User,
9420 User->getOperand(0).getValueType()));
9421 } else if (User->getOpcode() == ISD::SELECT_CC) {
9422 if (User->getOperand(0) == Inputs[i])
9423 SelectTruncOp[0].insert(std::make_pair(User,
9424 User->getOperand(0).getValueType()));
9425 if (User->getOperand(1) == Inputs[i])
9426 SelectTruncOp[1].insert(std::make_pair(User,
9427 User->getOperand(1).getValueType()));
9432 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9433 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9434 UE = PromOps[i].getNode()->use_end();
9437 if (User != N && !Visited.count(User))
9440 // If we're going to promote the non-output-value operand(s) or SELECT or
9441 // SELECT_CC, record them for truncation.
9442 if (User->getOpcode() == ISD::SELECT) {
9443 if (User->getOperand(0) == PromOps[i])
9444 SelectTruncOp[0].insert(std::make_pair(User,
9445 User->getOperand(0).getValueType()));
9446 } else if (User->getOpcode() == ISD::SELECT_CC) {
9447 if (User->getOperand(0) == PromOps[i])
9448 SelectTruncOp[0].insert(std::make_pair(User,
9449 User->getOperand(0).getValueType()));
9450 if (User->getOperand(1) == PromOps[i])
9451 SelectTruncOp[1].insert(std::make_pair(User,
9452 User->getOperand(1).getValueType()));
9457 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9458 bool ReallyNeedsExt = false;
9459 if (N->getOpcode() != ISD::ANY_EXTEND) {
9460 // If all of the inputs are not already sign/zero extended, then
9461 // we'll still need to do that at the end.
9462 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9463 if (isa<ConstantSDNode>(Inputs[i]))
9467 Inputs[i].getOperand(0).getValueSizeInBits();
9468 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9470 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9471 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9472 APInt::getHighBitsSet(OpBits,
9473 OpBits-PromBits))) ||
9474 (N->getOpcode() == ISD::SIGN_EXTEND &&
9475 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9476 (OpBits-(PromBits-1)))) {
9477 ReallyNeedsExt = true;
9483 // Replace all inputs, either with the truncation operand, or a
9484 // truncation or extension to the final output type.
9485 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9486 // Constant inputs need to be replaced with the to-be-promoted nodes that
9487 // use them because they might have users outside of the cluster of
9489 if (isa<ConstantSDNode>(Inputs[i]))
9492 SDValue InSrc = Inputs[i].getOperand(0);
9493 if (Inputs[i].getValueType() == N->getValueType(0))
9494 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9495 else if (N->getOpcode() == ISD::SIGN_EXTEND)
9496 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9497 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9498 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9499 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9500 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9502 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9503 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9506 // Replace all operations (these are all the same, but have a different
9507 // (promoted) return type). DAG.getNode will validate that the types of
9508 // a binary operator match, so go through the list in reverse so that
9509 // we've likely promoted both operands first.
9510 while (!PromOps.empty()) {
9511 SDValue PromOp = PromOps.back();
9515 switch (PromOp.getOpcode()) {
9516 default: C = 0; break;
9517 case ISD::SELECT: C = 1; break;
9518 case ISD::SELECT_CC: C = 2; break;
9521 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9522 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9523 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9524 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9525 // The to-be-promoted operands of this node have not yet been
9526 // promoted (this should be rare because we're going through the
9527 // list backward, but if one of the operands has several users in
9528 // this cluster of to-be-promoted nodes, it is possible).
9529 PromOps.insert(PromOps.begin(), PromOp);
9533 // For SELECT and SELECT_CC nodes, we do a similar check for any
9534 // to-be-promoted comparison inputs.
9535 if (PromOp.getOpcode() == ISD::SELECT ||
9536 PromOp.getOpcode() == ISD::SELECT_CC) {
9537 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9538 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9539 (SelectTruncOp[1].count(PromOp.getNode()) &&
9540 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9541 PromOps.insert(PromOps.begin(), PromOp);
9546 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9547 PromOp.getNode()->op_end());
9549 // If this node has constant inputs, then they'll need to be promoted here.
9550 for (unsigned i = 0; i < 2; ++i) {
9551 if (!isa<ConstantSDNode>(Ops[C+i]))
9553 if (Ops[C+i].getValueType() == N->getValueType(0))
9556 if (N->getOpcode() == ISD::SIGN_EXTEND)
9557 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9558 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9559 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9561 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9564 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9565 // truncate them again to the original value type.
9566 if (PromOp.getOpcode() == ISD::SELECT ||
9567 PromOp.getOpcode() == ISD::SELECT_CC) {
9568 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9569 if (SI0 != SelectTruncOp[0].end())
9570 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9571 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9572 if (SI1 != SelectTruncOp[1].end())
9573 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9576 DAG.ReplaceAllUsesOfValueWith(PromOp,
9577 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9580 // Now we're left with the initial extension itself.
9581 if (!ReallyNeedsExt)
9582 return N->getOperand(0);
9584 // To zero extend, just mask off everything except for the first bit (in the
9586 if (N->getOpcode() == ISD::ZERO_EXTEND)
9587 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9588 DAG.getConstant(APInt::getLowBitsSet(
9589 N->getValueSizeInBits(0), PromBits),
9590 N->getValueType(0)));
9592 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9593 "Invalid extension type");
9594 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9596 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9597 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
9598 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9599 N->getOperand(0), ShiftCst), ShiftCst);
9602 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9603 DAGCombinerInfo &DCI) const {
9604 assert((N->getOpcode() == ISD::SINT_TO_FP ||
9605 N->getOpcode() == ISD::UINT_TO_FP) &&
9606 "Need an int -> FP conversion node here");
9608 if (!Subtarget.has64BitSupport())
9611 SelectionDAG &DAG = DCI.DAG;
9615 // Don't handle ppc_fp128 here or i1 conversions.
9616 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9618 if (Op.getOperand(0).getValueType() == MVT::i1)
9621 // For i32 intermediate values, unfortunately, the conversion functions
9622 // leave the upper 32 bits of the value are undefined. Within the set of
9623 // scalar instructions, we have no method for zero- or sign-extending the
9624 // value. Thus, we cannot handle i32 intermediate values here.
9625 if (Op.getOperand(0).getValueType() == MVT::i32)
9628 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9629 "UINT_TO_FP is supported only with FPCVT");
9631 // If we have FCFIDS, then use it when converting to single-precision.
9632 // Otherwise, convert to double-precision and then round.
9633 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9634 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9636 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9638 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9642 // If we're converting from a float, to an int, and back to a float again,
9643 // then we don't need the store/load pair at all.
9644 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9645 Subtarget.hasFPCVT()) ||
9646 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9647 SDValue Src = Op.getOperand(0).getOperand(0);
9648 if (Src.getValueType() == MVT::f32) {
9649 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9650 DCI.AddToWorklist(Src.getNode());
9654 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9657 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9658 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9660 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9661 FP = DAG.getNode(ISD::FP_ROUND, dl,
9662 MVT::f32, FP, DAG.getIntPtrConstant(0));
9663 DCI.AddToWorklist(FP.getNode());
9672 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9673 // builtins) into loads with swaps.
9674 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9675 DAGCombinerInfo &DCI) const {
9676 SelectionDAG &DAG = DCI.DAG;
9680 MachineMemOperand *MMO;
9682 switch (N->getOpcode()) {
9684 llvm_unreachable("Unexpected opcode for little endian VSX load");
9686 LoadSDNode *LD = cast<LoadSDNode>(N);
9687 Chain = LD->getChain();
9688 Base = LD->getBasePtr();
9689 MMO = LD->getMemOperand();
9690 // If the MMO suggests this isn't a load of a full vector, leave
9691 // things alone. For a built-in, we have to make the change for
9692 // correctness, so if there is a size problem that will be a bug.
9693 if (MMO->getSize() < 16)
9697 case ISD::INTRINSIC_W_CHAIN: {
9698 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9699 Chain = Intrin->getChain();
9700 Base = Intrin->getBasePtr();
9701 MMO = Intrin->getMemOperand();
9706 MVT VecTy = N->getValueType(0).getSimpleVT();
9707 SDValue LoadOps[] = { Chain, Base };
9708 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9709 DAG.getVTList(VecTy, MVT::Other),
9710 LoadOps, VecTy, MMO);
9711 DCI.AddToWorklist(Load.getNode());
9712 Chain = Load.getValue(1);
9713 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9714 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9715 DCI.AddToWorklist(Swap.getNode());
9719 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9720 // builtins) into stores with swaps.
9721 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9722 DAGCombinerInfo &DCI) const {
9723 SelectionDAG &DAG = DCI.DAG;
9728 MachineMemOperand *MMO;
9730 switch (N->getOpcode()) {
9732 llvm_unreachable("Unexpected opcode for little endian VSX store");
9734 StoreSDNode *ST = cast<StoreSDNode>(N);
9735 Chain = ST->getChain();
9736 Base = ST->getBasePtr();
9737 MMO = ST->getMemOperand();
9739 // If the MMO suggests this isn't a store of a full vector, leave
9740 // things alone. For a built-in, we have to make the change for
9741 // correctness, so if there is a size problem that will be a bug.
9742 if (MMO->getSize() < 16)
9746 case ISD::INTRINSIC_VOID: {
9747 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9748 Chain = Intrin->getChain();
9749 // Intrin->getBasePtr() oddly does not get what we want.
9750 Base = Intrin->getOperand(3);
9751 MMO = Intrin->getMemOperand();
9757 SDValue Src = N->getOperand(SrcOpnd);
9758 MVT VecTy = Src.getValueType().getSimpleVT();
9759 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9760 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9761 DCI.AddToWorklist(Swap.getNode());
9762 Chain = Swap.getValue(1);
9763 SDValue StoreOps[] = { Chain, Swap, Base };
9764 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9765 DAG.getVTList(MVT::Other),
9766 StoreOps, VecTy, MMO);
9767 DCI.AddToWorklist(Store.getNode());
9771 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9772 DAGCombinerInfo &DCI) const {
9773 SelectionDAG &DAG = DCI.DAG;
9775 switch (N->getOpcode()) {
9778 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9779 if (C->isNullValue()) // 0 << V -> 0.
9780 return N->getOperand(0);
9784 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9785 if (C->isNullValue()) // 0 >>u V -> 0.
9786 return N->getOperand(0);
9790 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9791 if (C->isNullValue() || // 0 >>s V -> 0.
9792 C->isAllOnesValue()) // -1 >>s V -> -1.
9793 return N->getOperand(0);
9796 case ISD::SIGN_EXTEND:
9797 case ISD::ZERO_EXTEND:
9798 case ISD::ANY_EXTEND:
9799 return DAGCombineExtBoolTrunc(N, DCI);
9802 case ISD::SELECT_CC:
9803 return DAGCombineTruncBoolExt(N, DCI);
9804 case ISD::SINT_TO_FP:
9805 case ISD::UINT_TO_FP:
9806 return combineFPToIntToFP(N, DCI);
9808 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9809 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9810 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9811 N->getOperand(1).getValueType() == MVT::i32 &&
9812 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9813 SDValue Val = N->getOperand(1).getOperand(0);
9814 if (Val.getValueType() == MVT::f32) {
9815 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9816 DCI.AddToWorklist(Val.getNode());
9818 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9819 DCI.AddToWorklist(Val.getNode());
9822 N->getOperand(0), Val, N->getOperand(2),
9823 DAG.getValueType(N->getOperand(1).getValueType())
9826 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9827 DAG.getVTList(MVT::Other), Ops,
9828 cast<StoreSDNode>(N)->getMemoryVT(),
9829 cast<StoreSDNode>(N)->getMemOperand());
9830 DCI.AddToWorklist(Val.getNode());
9834 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9835 if (cast<StoreSDNode>(N)->isUnindexed() &&
9836 N->getOperand(1).getOpcode() == ISD::BSWAP &&
9837 N->getOperand(1).getNode()->hasOneUse() &&
9838 (N->getOperand(1).getValueType() == MVT::i32 ||
9839 N->getOperand(1).getValueType() == MVT::i16 ||
9840 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9841 N->getOperand(1).getValueType() == MVT::i64))) {
9842 SDValue BSwapOp = N->getOperand(1).getOperand(0);
9843 // Do an any-extend to 32-bits if this is a half-word input.
9844 if (BSwapOp.getValueType() == MVT::i16)
9845 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9848 N->getOperand(0), BSwapOp, N->getOperand(2),
9849 DAG.getValueType(N->getOperand(1).getValueType())
9852 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9853 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9854 cast<StoreSDNode>(N)->getMemOperand());
9857 // For little endian, VSX stores require generating xxswapd/lxvd2x.
9858 EVT VT = N->getOperand(1).getValueType();
9859 if (VT.isSimple()) {
9860 MVT StoreVT = VT.getSimpleVT();
9861 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9862 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9863 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9864 return expandVSXStoreForLE(N, DCI);
9869 LoadSDNode *LD = cast<LoadSDNode>(N);
9870 EVT VT = LD->getValueType(0);
9872 // For little endian, VSX loads require generating lxvd2x/xxswapd.
9873 if (VT.isSimple()) {
9874 MVT LoadVT = VT.getSimpleVT();
9875 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9876 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9877 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9878 return expandVSXLoadForLE(N, DCI);
9881 EVT MemVT = LD->getMemoryVT();
9882 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9883 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9884 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9885 unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9886 if (LD->isUnindexed() && VT.isVector() &&
9887 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9888 // P8 and later hardware should just use LOAD.
9889 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9890 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9891 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9892 LD->getAlignment() >= ScalarABIAlignment)) &&
9893 LD->getAlignment() < ABIAlignment) {
9894 // This is a type-legal unaligned Altivec or QPX load.
9895 SDValue Chain = LD->getChain();
9896 SDValue Ptr = LD->getBasePtr();
9897 bool isLittleEndian = Subtarget.isLittleEndian();
9899 // This implements the loading of unaligned vectors as described in
9900 // the venerable Apple Velocity Engine overview. Specifically:
9901 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9902 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9904 // The general idea is to expand a sequence of one or more unaligned
9905 // loads into an alignment-based permutation-control instruction (lvsl
9906 // or lvsr), a series of regular vector loads (which always truncate
9907 // their input address to an aligned address), and a series of
9908 // permutations. The results of these permutations are the requested
9909 // loaded values. The trick is that the last "extra" load is not taken
9910 // from the address you might suspect (sizeof(vector) bytes after the
9911 // last requested load), but rather sizeof(vector) - 1 bytes after the
9912 // last requested vector. The point of this is to avoid a page fault if
9913 // the base address happened to be aligned. This works because if the
9914 // base address is aligned, then adding less than a full vector length
9915 // will cause the last vector in the sequence to be (re)loaded.
9916 // Otherwise, the next vector will be fetched as you might suspect was
9919 // We might be able to reuse the permutation generation from
9920 // a different base address offset from this one by an aligned amount.
9921 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9922 // optimization later.
9923 Intrinsic::ID Intr, IntrLD, IntrPerm;
9924 MVT PermCntlTy, PermTy, LDTy;
9925 if (Subtarget.hasAltivec()) {
9926 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
9927 Intrinsic::ppc_altivec_lvsl;
9928 IntrLD = Intrinsic::ppc_altivec_lvx;
9929 IntrPerm = Intrinsic::ppc_altivec_vperm;
9930 PermCntlTy = MVT::v16i8;
9931 PermTy = MVT::v4i32;
9934 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
9935 Intrinsic::ppc_qpx_qvlpcls;
9936 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
9937 Intrinsic::ppc_qpx_qvlfs;
9938 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
9939 PermCntlTy = MVT::v4f64;
9940 PermTy = MVT::v4f64;
9941 LDTy = MemVT.getSimpleVT();
9944 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
9946 // Create the new MMO for the new base load. It is like the original MMO,
9947 // but represents an area in memory almost twice the vector size centered
9948 // on the original address. If the address is unaligned, we might start
9949 // reading up to (sizeof(vector)-1) bytes below the address of the
9950 // original unaligned load.
9951 MachineFunction &MF = DAG.getMachineFunction();
9952 MachineMemOperand *BaseMMO =
9953 MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
9954 2*MemVT.getStoreSize()-1);
9956 // Create the new base load.
9957 SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
9958 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9960 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9961 DAG.getVTList(PermTy, MVT::Other),
9962 BaseLoadOps, LDTy, BaseMMO);
9964 // Note that the value of IncOffset (which is provided to the next
9965 // load's pointer info offset value, and thus used to calculate the
9966 // alignment), and the value of IncValue (which is actually used to
9967 // increment the pointer value) are different! This is because we
9968 // require the next load to appear to be aligned, even though it
9969 // is actually offset from the base pointer by a lesser amount.
9970 int IncOffset = VT.getSizeInBits() / 8;
9971 int IncValue = IncOffset;
9973 // Walk (both up and down) the chain looking for another load at the real
9974 // (aligned) offset (the alignment of the other load does not matter in
9975 // this case). If found, then do not use the offset reduction trick, as
9976 // that will prevent the loads from being later combined (as they would
9977 // otherwise be duplicates).
9978 if (!findConsecutiveLoad(LD, DAG))
9981 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9982 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9984 MachineMemOperand *ExtraMMO =
9985 MF.getMachineMemOperand(LD->getMemOperand(),
9986 1, 2*MemVT.getStoreSize()-1);
9987 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9989 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9990 DAG.getVTList(PermTy, MVT::Other),
9991 ExtraLoadOps, LDTy, ExtraMMO);
9993 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9994 BaseLoad.getValue(1), ExtraLoad.getValue(1));
9996 // Because vperm has a big-endian bias, we must reverse the order
9997 // of the input vectors and complement the permute control vector
9998 // when generating little endian code. We have already handled the
9999 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10000 // and ExtraLoad here.
10002 if (isLittleEndian)
10003 Perm = BuildIntrinsicOp(IntrPerm,
10004 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10006 Perm = BuildIntrinsicOp(IntrPerm,
10007 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10010 Perm = Subtarget.hasAltivec() ?
10011 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10012 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10013 DAG.getTargetConstant(1, MVT::i64));
10014 // second argument is 1 because this rounding
10015 // is always exact.
10017 // The output of the permutation is our loaded result, the TokenFactor is
10019 DCI.CombineTo(N, Perm, TF);
10020 return SDValue(N, 0);
10024 case ISD::INTRINSIC_WO_CHAIN: {
10025 bool isLittleEndian = Subtarget.isLittleEndian();
10026 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10027 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10028 : Intrinsic::ppc_altivec_lvsl);
10029 if ((IID == Intr ||
10030 IID == Intrinsic::ppc_qpx_qvlpcld ||
10031 IID == Intrinsic::ppc_qpx_qvlpcls) &&
10032 N->getOperand(1)->getOpcode() == ISD::ADD) {
10033 SDValue Add = N->getOperand(1);
10035 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10036 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10038 if (DAG.MaskedValueIsZero(
10039 Add->getOperand(1),
10040 APInt::getAllOnesValue(Bits /* alignment */)
10042 Add.getValueType().getScalarType().getSizeInBits()))) {
10043 SDNode *BasePtr = Add->getOperand(0).getNode();
10044 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10045 UE = BasePtr->use_end();
10047 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10048 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10049 // We've found another LVSL/LVSR, and this address is an aligned
10050 // multiple of that one. The results will be the same, so use the
10051 // one we've just found instead.
10053 return SDValue(*UI, 0);
10058 if (isa<ConstantSDNode>(Add->getOperand(1))) {
10059 SDNode *BasePtr = Add->getOperand(0).getNode();
10060 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10061 UE = BasePtr->use_end(); UI != UE; ++UI) {
10062 if (UI->getOpcode() == ISD::ADD &&
10063 isa<ConstantSDNode>(UI->getOperand(1)) &&
10064 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10065 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10066 (1ULL << Bits) == 0) {
10067 SDNode *OtherAdd = *UI;
10068 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10069 VE = OtherAdd->use_end(); VI != VE; ++VI) {
10070 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10071 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10072 return SDValue(*VI, 0);
10082 case ISD::INTRINSIC_W_CHAIN: {
10083 // For little endian, VSX loads require generating lxvd2x/xxswapd.
10084 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10085 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10088 case Intrinsic::ppc_vsx_lxvw4x:
10089 case Intrinsic::ppc_vsx_lxvd2x:
10090 return expandVSXLoadForLE(N, DCI);
10095 case ISD::INTRINSIC_VOID: {
10096 // For little endian, VSX stores require generating xxswapd/stxvd2x.
10097 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10098 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10101 case Intrinsic::ppc_vsx_stxvw4x:
10102 case Intrinsic::ppc_vsx_stxvd2x:
10103 return expandVSXStoreForLE(N, DCI);
10109 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10110 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10111 N->getOperand(0).hasOneUse() &&
10112 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10113 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10114 N->getValueType(0) == MVT::i64))) {
10115 SDValue Load = N->getOperand(0);
10116 LoadSDNode *LD = cast<LoadSDNode>(Load);
10117 // Create the byte-swapping load.
10119 LD->getChain(), // Chain
10120 LD->getBasePtr(), // Ptr
10121 DAG.getValueType(N->getValueType(0)) // VT
10124 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10125 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10126 MVT::i64 : MVT::i32, MVT::Other),
10127 Ops, LD->getMemoryVT(), LD->getMemOperand());
10129 // If this is an i16 load, insert the truncate.
10130 SDValue ResVal = BSLoad;
10131 if (N->getValueType(0) == MVT::i16)
10132 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10134 // First, combine the bswap away. This makes the value produced by the
10136 DCI.CombineTo(N, ResVal);
10138 // Next, combine the load away, we give it a bogus result value but a real
10139 // chain result. The result value is dead because the bswap is dead.
10140 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10142 // Return N so it doesn't get rechecked!
10143 return SDValue(N, 0);
10147 case PPCISD::VCMP: {
10148 // If a VCMPo node already exists with exactly the same operands as this
10149 // node, use its result instead of this node (VCMPo computes both a CR6 and
10150 // a normal output).
10152 if (!N->getOperand(0).hasOneUse() &&
10153 !N->getOperand(1).hasOneUse() &&
10154 !N->getOperand(2).hasOneUse()) {
10156 // Scan all of the users of the LHS, looking for VCMPo's that match.
10157 SDNode *VCMPoNode = nullptr;
10159 SDNode *LHSN = N->getOperand(0).getNode();
10160 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10162 if (UI->getOpcode() == PPCISD::VCMPo &&
10163 UI->getOperand(1) == N->getOperand(1) &&
10164 UI->getOperand(2) == N->getOperand(2) &&
10165 UI->getOperand(0) == N->getOperand(0)) {
10170 // If there is no VCMPo node, or if the flag value has a single use, don't
10172 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10175 // Look at the (necessarily single) use of the flag value. If it has a
10176 // chain, this transformation is more complex. Note that multiple things
10177 // could use the value result, which we should ignore.
10178 SDNode *FlagUser = nullptr;
10179 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10180 FlagUser == nullptr; ++UI) {
10181 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10182 SDNode *User = *UI;
10183 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10184 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10191 // If the user is a MFOCRF instruction, we know this is safe.
10192 // Otherwise we give up for right now.
10193 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10194 return SDValue(VCMPoNode, 0);
10198 case ISD::BRCOND: {
10199 SDValue Cond = N->getOperand(1);
10200 SDValue Target = N->getOperand(2);
10202 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10203 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10204 Intrinsic::ppc_is_decremented_ctr_nonzero) {
10206 // We now need to make the intrinsic dead (it cannot be instruction
10208 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10209 assert(Cond.getNode()->hasOneUse() &&
10210 "Counter decrement has more than one use");
10212 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10213 N->getOperand(0), Target);
10218 // If this is a branch on an altivec predicate comparison, lower this so
10219 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
10220 // lowering is done pre-legalize, because the legalizer lowers the predicate
10221 // compare down to code that is difficult to reassemble.
10222 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10223 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10225 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10226 // value. If so, pass-through the AND to get to the intrinsic.
10227 if (LHS.getOpcode() == ISD::AND &&
10228 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10229 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10230 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10231 isa<ConstantSDNode>(LHS.getOperand(1)) &&
10232 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10234 LHS = LHS.getOperand(0);
10236 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10237 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10238 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10239 isa<ConstantSDNode>(RHS)) {
10240 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10241 "Counter decrement comparison is not EQ or NE");
10243 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10244 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10245 (CC == ISD::SETNE && !Val);
10247 // We now need to make the intrinsic dead (it cannot be instruction
10249 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10250 assert(LHS.getNode()->hasOneUse() &&
10251 "Counter decrement has more than one use");
10253 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10254 N->getOperand(0), N->getOperand(4));
10260 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10261 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10262 getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10263 assert(isDot && "Can't compare against a vector result!");
10265 // If this is a comparison against something other than 0/1, then we know
10266 // that the condition is never/always true.
10267 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10268 if (Val != 0 && Val != 1) {
10269 if (CC == ISD::SETEQ) // Cond never true, remove branch.
10270 return N->getOperand(0);
10271 // Always !=, turn it into an unconditional branch.
10272 return DAG.getNode(ISD::BR, dl, MVT::Other,
10273 N->getOperand(0), N->getOperand(4));
10276 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10278 // Create the PPCISD altivec 'dot' comparison node.
10280 LHS.getOperand(2), // LHS of compare
10281 LHS.getOperand(3), // RHS of compare
10282 DAG.getConstant(CompareOpc, MVT::i32)
10284 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10285 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10287 // Unpack the result based on how the target uses it.
10288 PPC::Predicate CompOpc;
10289 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10290 default: // Can't happen, don't crash on invalid number though.
10291 case 0: // Branch on the value of the EQ bit of CR6.
10292 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10294 case 1: // Branch on the inverted value of the EQ bit of CR6.
10295 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10297 case 2: // Branch on the value of the LT bit of CR6.
10298 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10300 case 3: // Branch on the inverted value of the LT bit of CR6.
10301 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10305 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10306 DAG.getConstant(CompOpc, MVT::i32),
10307 DAG.getRegister(PPC::CR6, MVT::i32),
10308 N->getOperand(4), CompNode.getValue(1));
10318 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10320 std::vector<SDNode *> *Created) const {
10321 // fold (sdiv X, pow2)
10322 EVT VT = N->getValueType(0);
10323 if (VT == MVT::i64 && !Subtarget.isPPC64())
10325 if ((VT != MVT::i32 && VT != MVT::i64) ||
10326 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10330 SDValue N0 = N->getOperand(0);
10332 bool IsNegPow2 = (-Divisor).isPowerOf2();
10333 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10334 SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10336 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10338 Created->push_back(Op.getNode());
10341 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10343 Created->push_back(Op.getNode());
10349 //===----------------------------------------------------------------------===//
10350 // Inline Assembly Support
10351 //===----------------------------------------------------------------------===//
10353 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10356 const SelectionDAG &DAG,
10357 unsigned Depth) const {
10358 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10359 switch (Op.getOpcode()) {
10361 case PPCISD::LBRX: {
10362 // lhbrx is known to have the top bits cleared out.
10363 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10364 KnownZero = 0xFFFF0000;
10367 case ISD::INTRINSIC_WO_CHAIN: {
10368 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10370 case Intrinsic::ppc_altivec_vcmpbfp_p:
10371 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10372 case Intrinsic::ppc_altivec_vcmpequb_p:
10373 case Intrinsic::ppc_altivec_vcmpequh_p:
10374 case Intrinsic::ppc_altivec_vcmpequw_p:
10375 case Intrinsic::ppc_altivec_vcmpequd_p:
10376 case Intrinsic::ppc_altivec_vcmpgefp_p:
10377 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10378 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10379 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10380 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10381 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10382 case Intrinsic::ppc_altivec_vcmpgtub_p:
10383 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10384 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10385 case Intrinsic::ppc_altivec_vcmpgtud_p:
10386 KnownZero = ~1U; // All bits but the low one are known to be zero.
10393 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10394 switch (Subtarget.getDarwinDirective()) {
10397 case PPC::DIR_PWR4:
10398 case PPC::DIR_PWR5:
10399 case PPC::DIR_PWR5X:
10400 case PPC::DIR_PWR6:
10401 case PPC::DIR_PWR6X:
10402 case PPC::DIR_PWR7:
10403 case PPC::DIR_PWR8: {
10407 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10409 // For small loops (between 5 and 8 instructions), align to a 32-byte
10410 // boundary so that the entire loop fits in one instruction-cache line.
10411 uint64_t LoopSize = 0;
10412 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10413 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10414 LoopSize += TII->GetInstSizeInBytes(J);
10416 if (LoopSize > 16 && LoopSize <= 32)
10423 return TargetLowering::getPrefLoopAlignment(ML);
10426 /// getConstraintType - Given a constraint, return the type of
10427 /// constraint it is for this target.
10428 PPCTargetLowering::ConstraintType
10429 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10430 if (Constraint.size() == 1) {
10431 switch (Constraint[0]) {
10438 return C_RegisterClass;
10440 // FIXME: While Z does indicate a memory constraint, it specifically
10441 // indicates an r+r address (used in conjunction with the 'y' modifier
10442 // in the replacement string). Currently, we're forcing the base
10443 // register to be r0 in the asm printer (which is interpreted as zero)
10444 // and forming the complete address in the second register. This is
10448 } else if (Constraint == "wc") { // individual CR bits.
10449 return C_RegisterClass;
10450 } else if (Constraint == "wa" || Constraint == "wd" ||
10451 Constraint == "wf" || Constraint == "ws") {
10452 return C_RegisterClass; // VSX registers.
10454 return TargetLowering::getConstraintType(Constraint);
10457 /// Examine constraint type and operand type and determine a weight value.
10458 /// This object must already have been set up with the operand type
10459 /// and the current alternative constraint selected.
10460 TargetLowering::ConstraintWeight
10461 PPCTargetLowering::getSingleConstraintMatchWeight(
10462 AsmOperandInfo &info, const char *constraint) const {
10463 ConstraintWeight weight = CW_Invalid;
10464 Value *CallOperandVal = info.CallOperandVal;
10465 // If we don't have a value, we can't do a match,
10466 // but allow it at the lowest weight.
10467 if (!CallOperandVal)
10469 Type *type = CallOperandVal->getType();
10471 // Look at the constraint type.
10472 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10473 return CW_Register; // an individual CR bit.
10474 else if ((StringRef(constraint) == "wa" ||
10475 StringRef(constraint) == "wd" ||
10476 StringRef(constraint) == "wf") &&
10477 type->isVectorTy())
10478 return CW_Register;
10479 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10480 return CW_Register;
10482 switch (*constraint) {
10484 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10487 if (type->isIntegerTy())
10488 weight = CW_Register;
10491 if (type->isFloatTy())
10492 weight = CW_Register;
10495 if (type->isDoubleTy())
10496 weight = CW_Register;
10499 if (type->isVectorTy())
10500 weight = CW_Register;
10503 weight = CW_Register;
10506 weight = CW_Memory;
10512 std::pair<unsigned, const TargetRegisterClass *>
10513 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10514 const std::string &Constraint,
10516 if (Constraint.size() == 1) {
10517 // GCC RS6000 Constraint Letters
10518 switch (Constraint[0]) {
10519 case 'b': // R1-R31
10520 if (VT == MVT::i64 && Subtarget.isPPC64())
10521 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10522 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10523 case 'r': // R0-R31
10524 if (VT == MVT::i64 && Subtarget.isPPC64())
10525 return std::make_pair(0U, &PPC::G8RCRegClass);
10526 return std::make_pair(0U, &PPC::GPRCRegClass);
10528 if (VT == MVT::f32 || VT == MVT::i32)
10529 return std::make_pair(0U, &PPC::F4RCRegClass);
10530 if (VT == MVT::f64 || VT == MVT::i64)
10531 return std::make_pair(0U, &PPC::F8RCRegClass);
10532 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10533 return std::make_pair(0U, &PPC::QFRCRegClass);
10534 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10535 return std::make_pair(0U, &PPC::QSRCRegClass);
10538 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10539 return std::make_pair(0U, &PPC::QFRCRegClass);
10540 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10541 return std::make_pair(0U, &PPC::QSRCRegClass);
10542 return std::make_pair(0U, &PPC::VRRCRegClass);
10544 return std::make_pair(0U, &PPC::CRRCRegClass);
10546 } else if (Constraint == "wc") { // an individual CR bit.
10547 return std::make_pair(0U, &PPC::CRBITRCRegClass);
10548 } else if (Constraint == "wa" || Constraint == "wd" ||
10549 Constraint == "wf") {
10550 return std::make_pair(0U, &PPC::VSRCRegClass);
10551 } else if (Constraint == "ws") {
10552 return std::make_pair(0U, &PPC::VSFRCRegClass);
10555 std::pair<unsigned, const TargetRegisterClass *> R =
10556 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10558 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10559 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10560 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10562 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10563 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10564 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10565 PPC::GPRCRegClass.contains(R.first))
10566 return std::make_pair(TRI->getMatchingSuperReg(R.first,
10567 PPC::sub_32, &PPC::G8RCRegClass),
10568 &PPC::G8RCRegClass);
10570 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10571 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10572 R.first = PPC::CR0;
10573 R.second = &PPC::CRRCRegClass;
10580 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10581 /// vector. If it is invalid, don't add anything to Ops.
10582 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10583 std::string &Constraint,
10584 std::vector<SDValue>&Ops,
10585 SelectionDAG &DAG) const {
10588 // Only support length 1 constraints.
10589 if (Constraint.length() > 1) return;
10591 char Letter = Constraint[0];
10602 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10603 if (!CST) return; // Must be an immediate to match.
10604 int64_t Value = CST->getSExtValue();
10605 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10606 // numbers are printed as such.
10608 default: llvm_unreachable("Unknown constraint letter!");
10609 case 'I': // "I" is a signed 16-bit constant.
10610 if (isInt<16>(Value))
10611 Result = DAG.getTargetConstant(Value, TCVT);
10613 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
10614 if (isShiftedUInt<16, 16>(Value))
10615 Result = DAG.getTargetConstant(Value, TCVT);
10617 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
10618 if (isShiftedInt<16, 16>(Value))
10619 Result = DAG.getTargetConstant(Value, TCVT);
10621 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
10622 if (isUInt<16>(Value))
10623 Result = DAG.getTargetConstant(Value, TCVT);
10625 case 'M': // "M" is a constant that is greater than 31.
10627 Result = DAG.getTargetConstant(Value, TCVT);
10629 case 'N': // "N" is a positive constant that is an exact power of two.
10630 if (Value > 0 && isPowerOf2_64(Value))
10631 Result = DAG.getTargetConstant(Value, TCVT);
10633 case 'O': // "O" is the constant zero.
10635 Result = DAG.getTargetConstant(Value, TCVT);
10637 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
10638 if (isInt<16>(-Value))
10639 Result = DAG.getTargetConstant(Value, TCVT);
10646 if (Result.getNode()) {
10647 Ops.push_back(Result);
10651 // Handle standard constraint letters.
10652 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10655 // isLegalAddressingMode - Return true if the addressing mode represented
10656 // by AM is legal for this target, for a load/store of the specified type.
10657 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10659 // PPC does not allow r+i addressing modes for vectors!
10660 if (Ty->isVectorTy() && AM.BaseOffs != 0)
10663 // PPC allows a sign-extended 16-bit immediate field.
10664 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10667 // No global is ever allowed as a base.
10671 // PPC only support r+r,
10672 switch (AM.Scale) {
10673 case 0: // "r+i" or just "i", depending on HasBaseReg.
10676 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
10678 // Otherwise we have r+r or r+i.
10681 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
10683 // Allow 2*r as r+r.
10686 // No other scales are supported.
10693 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10694 SelectionDAG &DAG) const {
10695 MachineFunction &MF = DAG.getMachineFunction();
10696 MachineFrameInfo *MFI = MF.getFrameInfo();
10697 MFI->setReturnAddressIsTaken(true);
10699 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10703 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10705 // Make sure the function does not optimize away the store of the RA to
10707 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10708 FuncInfo->setLRStoreRequired();
10709 bool isPPC64 = Subtarget.isPPC64();
10712 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10714 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10715 isPPC64 ? MVT::i64 : MVT::i32);
10716 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10717 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10718 FrameAddr, Offset),
10719 MachinePointerInfo(), false, false, false, 0);
10722 // Just load the return address off the stack.
10723 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10724 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10725 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10728 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10729 SelectionDAG &DAG) const {
10731 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10733 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10734 bool isPPC64 = PtrVT == MVT::i64;
10736 MachineFunction &MF = DAG.getMachineFunction();
10737 MachineFrameInfo *MFI = MF.getFrameInfo();
10738 MFI->setFrameAddressIsTaken(true);
10740 // Naked functions never have a frame pointer, and so we use r1. For all
10741 // other functions, this decision must be delayed until during PEI.
10743 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10744 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10746 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10748 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10751 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10752 FrameAddr, MachinePointerInfo(), false, false,
10757 // FIXME? Maybe this could be a TableGen attribute on some registers and
10758 // this table could be generated automatically from RegInfo.
10759 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10761 bool isPPC64 = Subtarget.isPPC64();
10762 bool isDarwinABI = Subtarget.isDarwinABI();
10764 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10765 (!isPPC64 && VT != MVT::i32))
10766 report_fatal_error("Invalid register global variable type");
10768 bool is64Bit = isPPC64 && VT == MVT::i64;
10769 unsigned Reg = StringSwitch<unsigned>(RegName)
10770 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10771 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10772 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10773 (is64Bit ? PPC::X13 : PPC::R13))
10778 report_fatal_error("Invalid register name global variable");
10782 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10783 // The PowerPC target isn't yet aware of offsets.
10787 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10789 unsigned Intrinsic) const {
10791 switch (Intrinsic) {
10792 case Intrinsic::ppc_qpx_qvlfd:
10793 case Intrinsic::ppc_qpx_qvlfs:
10794 case Intrinsic::ppc_qpx_qvlfcd:
10795 case Intrinsic::ppc_qpx_qvlfcs:
10796 case Intrinsic::ppc_qpx_qvlfiwa:
10797 case Intrinsic::ppc_qpx_qvlfiwz:
10798 case Intrinsic::ppc_altivec_lvx:
10799 case Intrinsic::ppc_altivec_lvxl:
10800 case Intrinsic::ppc_altivec_lvebx:
10801 case Intrinsic::ppc_altivec_lvehx:
10802 case Intrinsic::ppc_altivec_lvewx:
10803 case Intrinsic::ppc_vsx_lxvd2x:
10804 case Intrinsic::ppc_vsx_lxvw4x: {
10806 switch (Intrinsic) {
10807 case Intrinsic::ppc_altivec_lvebx:
10810 case Intrinsic::ppc_altivec_lvehx:
10813 case Intrinsic::ppc_altivec_lvewx:
10816 case Intrinsic::ppc_vsx_lxvd2x:
10819 case Intrinsic::ppc_qpx_qvlfd:
10822 case Intrinsic::ppc_qpx_qvlfs:
10825 case Intrinsic::ppc_qpx_qvlfcd:
10828 case Intrinsic::ppc_qpx_qvlfcs:
10836 Info.opc = ISD::INTRINSIC_W_CHAIN;
10838 Info.ptrVal = I.getArgOperand(0);
10839 Info.offset = -VT.getStoreSize()+1;
10840 Info.size = 2*VT.getStoreSize()-1;
10843 Info.readMem = true;
10844 Info.writeMem = false;
10847 case Intrinsic::ppc_qpx_qvlfda:
10848 case Intrinsic::ppc_qpx_qvlfsa:
10849 case Intrinsic::ppc_qpx_qvlfcda:
10850 case Intrinsic::ppc_qpx_qvlfcsa:
10851 case Intrinsic::ppc_qpx_qvlfiwaa:
10852 case Intrinsic::ppc_qpx_qvlfiwza: {
10854 switch (Intrinsic) {
10855 case Intrinsic::ppc_qpx_qvlfda:
10858 case Intrinsic::ppc_qpx_qvlfsa:
10861 case Intrinsic::ppc_qpx_qvlfcda:
10864 case Intrinsic::ppc_qpx_qvlfcsa:
10872 Info.opc = ISD::INTRINSIC_W_CHAIN;
10874 Info.ptrVal = I.getArgOperand(0);
10876 Info.size = VT.getStoreSize();
10879 Info.readMem = true;
10880 Info.writeMem = false;
10883 case Intrinsic::ppc_qpx_qvstfd:
10884 case Intrinsic::ppc_qpx_qvstfs:
10885 case Intrinsic::ppc_qpx_qvstfcd:
10886 case Intrinsic::ppc_qpx_qvstfcs:
10887 case Intrinsic::ppc_qpx_qvstfiw:
10888 case Intrinsic::ppc_altivec_stvx:
10889 case Intrinsic::ppc_altivec_stvxl:
10890 case Intrinsic::ppc_altivec_stvebx:
10891 case Intrinsic::ppc_altivec_stvehx:
10892 case Intrinsic::ppc_altivec_stvewx:
10893 case Intrinsic::ppc_vsx_stxvd2x:
10894 case Intrinsic::ppc_vsx_stxvw4x: {
10896 switch (Intrinsic) {
10897 case Intrinsic::ppc_altivec_stvebx:
10900 case Intrinsic::ppc_altivec_stvehx:
10903 case Intrinsic::ppc_altivec_stvewx:
10906 case Intrinsic::ppc_vsx_stxvd2x:
10909 case Intrinsic::ppc_qpx_qvstfd:
10912 case Intrinsic::ppc_qpx_qvstfs:
10915 case Intrinsic::ppc_qpx_qvstfcd:
10918 case Intrinsic::ppc_qpx_qvstfcs:
10926 Info.opc = ISD::INTRINSIC_VOID;
10928 Info.ptrVal = I.getArgOperand(1);
10929 Info.offset = -VT.getStoreSize()+1;
10930 Info.size = 2*VT.getStoreSize()-1;
10933 Info.readMem = false;
10934 Info.writeMem = true;
10937 case Intrinsic::ppc_qpx_qvstfda:
10938 case Intrinsic::ppc_qpx_qvstfsa:
10939 case Intrinsic::ppc_qpx_qvstfcda:
10940 case Intrinsic::ppc_qpx_qvstfcsa:
10941 case Intrinsic::ppc_qpx_qvstfiwa: {
10943 switch (Intrinsic) {
10944 case Intrinsic::ppc_qpx_qvstfda:
10947 case Intrinsic::ppc_qpx_qvstfsa:
10950 case Intrinsic::ppc_qpx_qvstfcda:
10953 case Intrinsic::ppc_qpx_qvstfcsa:
10961 Info.opc = ISD::INTRINSIC_VOID;
10963 Info.ptrVal = I.getArgOperand(1);
10965 Info.size = VT.getStoreSize();
10968 Info.readMem = false;
10969 Info.writeMem = true;
10979 /// getOptimalMemOpType - Returns the target specific optimal type for load
10980 /// and store operations as a result of memset, memcpy, and memmove
10981 /// lowering. If DstAlign is zero that means it's safe to destination
10982 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
10983 /// means there isn't a need to check it against alignment requirement,
10984 /// probably because the source does not need to be loaded. If 'IsMemset' is
10985 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
10986 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
10987 /// source is constant so it does not need to be loaded.
10988 /// It returns EVT::Other if the type should be determined using generic
10989 /// target-independent logic.
10990 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
10991 unsigned DstAlign, unsigned SrcAlign,
10992 bool IsMemset, bool ZeroMemset,
10994 MachineFunction &MF) const {
10995 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
10996 const Function *F = MF.getFunction();
10997 // When expanding a memset, require at least two QPX instructions to cover
10998 // the cost of loading the value to be stored from the constant pool.
10999 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11000 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11001 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11005 // We should use Altivec/VSX loads and stores when available. For unaligned
11006 // addresses, unaligned VSX loads are only fast starting with the P8.
11007 if (Subtarget.hasAltivec() && Size >= 16 &&
11008 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11009 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11013 if (Subtarget.isPPC64()) {
11020 /// \brief Returns true if it is beneficial to convert a load of a constant
11021 /// to just the constant itself.
11022 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11024 assert(Ty->isIntegerTy());
11026 unsigned BitSize = Ty->getPrimitiveSizeInBits();
11027 if (BitSize == 0 || BitSize > 64)
11032 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11033 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11035 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11036 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11037 return NumBits1 == 64 && NumBits2 == 32;
11040 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11041 if (!VT1.isInteger() || !VT2.isInteger())
11043 unsigned NumBits1 = VT1.getSizeInBits();
11044 unsigned NumBits2 = VT2.getSizeInBits();
11045 return NumBits1 == 64 && NumBits2 == 32;
11048 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11049 // Generally speaking, zexts are not free, but they are free when they can be
11050 // folded with other operations.
11051 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11052 EVT MemVT = LD->getMemoryVT();
11053 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11054 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11055 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11056 LD->getExtensionType() == ISD::ZEXTLOAD))
11060 // FIXME: Add other cases...
11061 // - 32-bit shifts with a zext to i64
11062 // - zext after ctlz, bswap, etc.
11063 // - zext after and by a constant mask
11065 return TargetLowering::isZExtFree(Val, VT2);
11068 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11069 assert(VT.isFloatingPoint());
11073 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11074 return isInt<16>(Imm) || isUInt<16>(Imm);
11077 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11078 return isInt<16>(Imm) || isUInt<16>(Imm);
11081 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11084 bool *Fast) const {
11085 if (DisablePPCUnaligned)
11088 // PowerPC supports unaligned memory access for simple non-vector types.
11089 // Although accessing unaligned addresses is not as efficient as accessing
11090 // aligned addresses, it is generally more efficient than manual expansion,
11091 // and generally only traps for software emulation when crossing page
11094 if (!VT.isSimple())
11097 if (VT.getSimpleVT().isVector()) {
11098 if (Subtarget.hasVSX()) {
11099 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11100 VT != MVT::v4f32 && VT != MVT::v4i32)
11107 if (VT == MVT::ppcf128)
11116 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11117 VT = VT.getScalarType();
11119 if (!VT.isSimple())
11122 switch (VT.getSimpleVT().SimpleTy) {
11134 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11135 // LR is a callee-save register, but we must treat it as clobbered by any call
11136 // site. Hence we include LR in the scratch registers, which are in turn added
11137 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11138 // to CTR, which is used by any indirect call.
11139 static const MCPhysReg ScratchRegs[] = {
11140 PPC::X12, PPC::LR8, PPC::CTR8, 0
11143 return ScratchRegs;
11147 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11148 EVT VT , unsigned DefinedValues) const {
11149 if (VT == MVT::v2i64)
11152 if (Subtarget.hasQPX()) {
11153 if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11157 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11160 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11161 if (DisableILPPref || Subtarget.enableMachineScheduler())
11162 return TargetLowering::getSchedulingPreference(N);
11167 // Create a fast isel object.
11169 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11170 const TargetLibraryInfo *LibInfo) const {
11171 return PPC::createFastISel(FuncInfo, LibInfo);