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"
45 // FIXME: Remove this once soft-float is supported.
46 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
47 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
49 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
50 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
52 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
53 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
55 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
56 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
58 // FIXME: Remove this once the bug has been fixed!
59 extern cl::opt<bool> ANDIGlueBug;
61 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
62 const PPCSubtarget &STI)
63 : TargetLowering(TM), Subtarget(STI) {
64 // Use _setjmp/_longjmp instead of setjmp/longjmp.
65 setUseUnderscoreSetJmp(true);
66 setUseUnderscoreLongJmp(true);
68 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
69 // arguments are at least 4/8 bytes aligned.
70 bool isPPC64 = Subtarget.isPPC64();
71 setMinStackArgumentAlignment(isPPC64 ? 8:4);
73 // Set up the register classes.
74 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
75 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
76 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
78 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
79 for (MVT VT : MVT::integer_valuetypes()) {
80 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
81 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
84 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
86 // PowerPC has pre-inc load and store's.
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
93 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
100 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
102 if (Subtarget.useCRBits()) {
103 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
105 if (isPPC64 || Subtarget.hasFPCVT()) {
106 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
107 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
108 isPPC64 ? MVT::i64 : MVT::i32);
109 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
110 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
111 isPPC64 ? MVT::i64 : MVT::i32);
113 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
114 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
117 // PowerPC does not support direct load / store of condition registers
118 setOperationAction(ISD::LOAD, MVT::i1, Custom);
119 setOperationAction(ISD::STORE, MVT::i1, Custom);
121 // FIXME: Remove this once the ANDI glue bug is fixed:
123 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
125 for (MVT VT : MVT::integer_valuetypes()) {
126 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
127 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
128 setTruncStoreAction(VT, MVT::i1, Expand);
131 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
134 // This is used in the ppcf128->int sequence. Note it has different semantics
135 // from FP_ROUND: that rounds to nearest, this rounds to zero.
136 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
138 // We do not currently implement these libm ops for PowerPC.
139 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
144 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
146 // PowerPC has no SREM/UREM instructions
147 setOperationAction(ISD::SREM, MVT::i32, Expand);
148 setOperationAction(ISD::UREM, MVT::i32, Expand);
149 setOperationAction(ISD::SREM, MVT::i64, Expand);
150 setOperationAction(ISD::UREM, MVT::i64, Expand);
152 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
153 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
155 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
157 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
159 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
160 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
162 // We don't support sin/cos/sqrt/fmod/pow
163 setOperationAction(ISD::FSIN , MVT::f64, Expand);
164 setOperationAction(ISD::FCOS , MVT::f64, Expand);
165 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
166 setOperationAction(ISD::FREM , MVT::f64, Expand);
167 setOperationAction(ISD::FPOW , MVT::f64, Expand);
168 setOperationAction(ISD::FMA , MVT::f64, Legal);
169 setOperationAction(ISD::FSIN , MVT::f32, Expand);
170 setOperationAction(ISD::FCOS , MVT::f32, Expand);
171 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
172 setOperationAction(ISD::FREM , MVT::f32, Expand);
173 setOperationAction(ISD::FPOW , MVT::f32, Expand);
174 setOperationAction(ISD::FMA , MVT::f32, Legal);
176 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
178 // If we're enabling GP optimizations, use hardware square root
179 if (!Subtarget.hasFSQRT() &&
180 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
182 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
184 if (!Subtarget.hasFSQRT() &&
185 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
186 Subtarget.hasFRES()))
187 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
189 if (Subtarget.hasFCPSGN()) {
190 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
191 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
194 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
197 if (Subtarget.hasFPRND()) {
198 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
199 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
200 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
201 setOperationAction(ISD::FROUND, MVT::f64, Legal);
203 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
204 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
205 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
206 setOperationAction(ISD::FROUND, MVT::f32, Legal);
209 // PowerPC does not have BSWAP, CTPOP or CTTZ
210 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
212 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
214 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
216 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
217 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
219 if (Subtarget.hasPOPCNTD()) {
220 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
221 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
223 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
224 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
227 // PowerPC does not have ROTR
228 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
229 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
231 if (!Subtarget.useCRBits()) {
232 // PowerPC does not have Select
233 setOperationAction(ISD::SELECT, MVT::i32, Expand);
234 setOperationAction(ISD::SELECT, MVT::i64, Expand);
235 setOperationAction(ISD::SELECT, MVT::f32, Expand);
236 setOperationAction(ISD::SELECT, MVT::f64, Expand);
239 // PowerPC wants to turn select_cc of FP into fsel when possible.
240 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
243 // PowerPC wants to optimize integer setcc a bit
244 if (!Subtarget.useCRBits())
245 setOperationAction(ISD::SETCC, MVT::i32, Custom);
247 // PowerPC does not have BRCOND which requires SetCC
248 if (!Subtarget.useCRBits())
249 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
251 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
253 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
254 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
256 // PowerPC does not have [U|S]INT_TO_FP
257 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
258 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
262 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
263 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
265 // We cannot sextinreg(i1). Expand to shifts.
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
268 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
269 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
270 // support continuation, user-level threading, and etc.. As a result, no
271 // other SjLj exception interfaces are implemented and please don't build
272 // your own exception handling based on them.
273 // LLVM/Clang supports zero-cost DWARF exception handling.
274 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
275 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
277 // We want to legalize GlobalAddress and ConstantPool nodes into the
278 // appropriate instructions to materialize the address.
279 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
280 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
281 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
282 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
283 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
284 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
287 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
288 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
291 setOperationAction(ISD::TRAP, MVT::Other, Legal);
293 // TRAMPOLINE is custom lowered.
294 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
295 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
297 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
298 setOperationAction(ISD::VASTART , MVT::Other, Custom);
300 if (Subtarget.isSVR4ABI()) {
302 // VAARG always uses double-word chunks, so promote anything smaller.
303 setOperationAction(ISD::VAARG, MVT::i1, Promote);
304 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
305 setOperationAction(ISD::VAARG, MVT::i8, Promote);
306 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
307 setOperationAction(ISD::VAARG, MVT::i16, Promote);
308 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
309 setOperationAction(ISD::VAARG, MVT::i32, Promote);
310 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
311 setOperationAction(ISD::VAARG, MVT::Other, Expand);
313 // VAARG is custom lowered with the 32-bit SVR4 ABI.
314 setOperationAction(ISD::VAARG, MVT::Other, Custom);
315 setOperationAction(ISD::VAARG, MVT::i64, Custom);
318 setOperationAction(ISD::VAARG, MVT::Other, Expand);
320 if (Subtarget.isSVR4ABI() && !isPPC64)
321 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
322 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
324 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
326 // Use the default implementation.
327 setOperationAction(ISD::VAEND , MVT::Other, Expand);
328 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
329 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
331 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
332 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
333 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
335 // We want to custom lower some of our intrinsics.
336 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
338 // To handle counter-based loop conditions.
339 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
341 // Comparisons that require checking two conditions.
342 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
343 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
344 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
345 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
346 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
347 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
348 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
349 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
350 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
351 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
352 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
353 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
355 if (Subtarget.has64BitSupport()) {
356 // They also have instructions for converting between i64 and fp.
357 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
358 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
359 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
360 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
361 // This is just the low 32 bits of a (signed) fp->i64 conversion.
362 // We cannot do this with Promote because i64 is not a legal type.
363 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
365 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
366 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
368 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
369 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
372 // With the instructions enabled under FPCVT, we can do everything.
373 if (Subtarget.hasFPCVT()) {
374 if (Subtarget.has64BitSupport()) {
375 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
376 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
377 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
378 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
381 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
382 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
383 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
384 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
387 if (Subtarget.use64BitRegs()) {
388 // 64-bit PowerPC implementations can support i64 types directly
389 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
390 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
391 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
392 // 64-bit PowerPC wants to expand i128 shifts itself.
393 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
394 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
395 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
397 // 32-bit PowerPC wants to expand i64 shifts itself.
398 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
399 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
400 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
403 if (Subtarget.hasAltivec()) {
404 // First set operation action for all vector types to expand. Then we
405 // will selectively turn on ones that can be effectively codegen'd.
406 for (MVT VT : MVT::vector_valuetypes()) {
407 // add/sub are legal for all supported vector VT's.
408 setOperationAction(ISD::ADD, VT, Legal);
409 setOperationAction(ISD::SUB, VT, Legal);
411 // Vector instructions introduced in P8
412 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
413 setOperationAction(ISD::CTPOP, VT, Legal);
414 setOperationAction(ISD::CTLZ, VT, Legal);
417 setOperationAction(ISD::CTPOP, VT, Expand);
418 setOperationAction(ISD::CTLZ, VT, Expand);
421 // We promote all shuffles to v16i8.
422 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
423 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
425 // We promote all non-typed operations to v4i32.
426 setOperationAction(ISD::AND , VT, Promote);
427 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
428 setOperationAction(ISD::OR , VT, Promote);
429 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
430 setOperationAction(ISD::XOR , VT, Promote);
431 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
432 setOperationAction(ISD::LOAD , VT, Promote);
433 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
434 setOperationAction(ISD::SELECT, VT, Promote);
435 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
436 setOperationAction(ISD::SELECT_CC, VT, Promote);
437 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
438 setOperationAction(ISD::STORE, VT, Promote);
439 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
441 // No other operations are legal.
442 setOperationAction(ISD::MUL , VT, Expand);
443 setOperationAction(ISD::SDIV, VT, Expand);
444 setOperationAction(ISD::SREM, VT, Expand);
445 setOperationAction(ISD::UDIV, VT, Expand);
446 setOperationAction(ISD::UREM, VT, Expand);
447 setOperationAction(ISD::FDIV, VT, Expand);
448 setOperationAction(ISD::FREM, VT, Expand);
449 setOperationAction(ISD::FNEG, VT, Expand);
450 setOperationAction(ISD::FSQRT, VT, Expand);
451 setOperationAction(ISD::FLOG, VT, Expand);
452 setOperationAction(ISD::FLOG10, VT, Expand);
453 setOperationAction(ISD::FLOG2, VT, Expand);
454 setOperationAction(ISD::FEXP, VT, Expand);
455 setOperationAction(ISD::FEXP2, VT, Expand);
456 setOperationAction(ISD::FSIN, VT, Expand);
457 setOperationAction(ISD::FCOS, VT, Expand);
458 setOperationAction(ISD::FABS, VT, Expand);
459 setOperationAction(ISD::FPOWI, VT, Expand);
460 setOperationAction(ISD::FFLOOR, VT, Expand);
461 setOperationAction(ISD::FCEIL, VT, Expand);
462 setOperationAction(ISD::FTRUNC, VT, Expand);
463 setOperationAction(ISD::FRINT, VT, Expand);
464 setOperationAction(ISD::FNEARBYINT, VT, Expand);
465 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
466 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
467 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
468 setOperationAction(ISD::MULHU, VT, Expand);
469 setOperationAction(ISD::MULHS, VT, Expand);
470 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
471 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
472 setOperationAction(ISD::UDIVREM, VT, Expand);
473 setOperationAction(ISD::SDIVREM, VT, Expand);
474 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
475 setOperationAction(ISD::FPOW, VT, Expand);
476 setOperationAction(ISD::BSWAP, VT, Expand);
477 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
478 setOperationAction(ISD::CTTZ, VT, Expand);
479 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
480 setOperationAction(ISD::VSELECT, VT, Expand);
481 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
483 for (MVT InnerVT : MVT::vector_valuetypes()) {
484 setTruncStoreAction(VT, InnerVT, Expand);
485 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
486 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
487 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
491 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
492 // with merges, splats, etc.
493 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
495 setOperationAction(ISD::AND , MVT::v4i32, Legal);
496 setOperationAction(ISD::OR , MVT::v4i32, Legal);
497 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
498 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
499 setOperationAction(ISD::SELECT, MVT::v4i32,
500 Subtarget.useCRBits() ? Legal : Expand);
501 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
502 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
503 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
504 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
505 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
506 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
507 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
508 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
509 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
511 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
512 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
513 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
514 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
516 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
517 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
519 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
520 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
521 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
524 if (Subtarget.hasP8Altivec())
525 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
527 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
529 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
530 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
532 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
533 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
535 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
536 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
537 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
538 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
540 // Altivec does not contain unordered floating-point compare instructions
541 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
542 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
543 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
544 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
546 if (Subtarget.hasVSX()) {
547 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
548 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
549 if (Subtarget.hasP8Vector()) {
550 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
551 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
553 if (Subtarget.hasDirectMove()) {
554 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
555 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
556 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
557 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
558 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
559 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
560 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
561 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
563 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
565 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
566 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
567 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
568 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
569 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
571 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
573 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
574 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
576 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
577 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
579 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
580 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
581 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
582 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
583 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
585 // Share the Altivec comparison restrictions.
586 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
587 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
588 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
589 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
591 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
592 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
594 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
596 if (Subtarget.hasP8Vector())
597 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
599 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
601 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
602 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
603 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
605 if (Subtarget.hasP8Altivec()) {
606 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
607 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
608 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
610 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
613 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
614 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
615 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
617 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
619 // VSX v2i64 only supports non-arithmetic operations.
620 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
621 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
624 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
625 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
626 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
627 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
629 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
631 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
632 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
633 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
634 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
636 // Vector operation legalization checks the result type of
637 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
638 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
639 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
640 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
641 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
643 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
646 if (Subtarget.hasP8Altivec()) {
647 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
648 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
652 if (Subtarget.hasQPX()) {
653 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
654 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
655 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
656 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
658 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
659 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
661 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
662 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
664 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
665 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
667 if (!Subtarget.useCRBits())
668 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
669 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
671 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
672 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
673 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
674 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
675 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
676 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
677 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
679 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
680 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
682 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
683 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
684 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
686 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
687 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
688 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
689 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
690 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
691 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
692 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
693 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
694 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
695 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
696 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
698 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
699 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
701 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
702 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
704 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
706 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
707 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
708 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
709 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
711 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
712 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
714 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
715 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
717 if (!Subtarget.useCRBits())
718 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
719 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
721 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
722 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
723 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
724 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
725 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
726 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
727 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
729 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
730 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
732 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
733 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
734 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
735 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
736 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
737 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
738 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
739 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
740 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
741 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
742 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
744 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
745 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
747 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
748 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
750 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
752 setOperationAction(ISD::AND , MVT::v4i1, Legal);
753 setOperationAction(ISD::OR , MVT::v4i1, Legal);
754 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
756 if (!Subtarget.useCRBits())
757 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
758 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
760 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
761 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
763 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
764 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
765 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
766 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
767 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
768 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
769 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
771 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
772 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
774 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
776 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
777 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
778 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
779 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
781 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
782 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
783 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
784 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
786 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
787 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
789 // These need to set FE_INEXACT, and so cannot be vectorized here.
790 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
791 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
793 if (TM.Options.UnsafeFPMath) {
794 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
795 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
797 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
798 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
800 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
801 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
803 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
804 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
808 if (Subtarget.has64BitSupport())
809 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
811 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
814 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
815 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
818 setBooleanContents(ZeroOrOneBooleanContent);
820 if (Subtarget.hasAltivec()) {
821 // Altivec instructions set fields to all zeros or all ones.
822 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
826 // These libcalls are not available in 32-bit.
827 setLibcallName(RTLIB::SHL_I128, nullptr);
828 setLibcallName(RTLIB::SRL_I128, nullptr);
829 setLibcallName(RTLIB::SRA_I128, nullptr);
832 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
834 // We have target-specific dag combine patterns for the following nodes:
835 setTargetDAGCombine(ISD::SINT_TO_FP);
836 if (Subtarget.hasFPCVT())
837 setTargetDAGCombine(ISD::UINT_TO_FP);
838 setTargetDAGCombine(ISD::LOAD);
839 setTargetDAGCombine(ISD::STORE);
840 setTargetDAGCombine(ISD::BR_CC);
841 if (Subtarget.useCRBits())
842 setTargetDAGCombine(ISD::BRCOND);
843 setTargetDAGCombine(ISD::BSWAP);
844 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
845 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
846 setTargetDAGCombine(ISD::INTRINSIC_VOID);
848 setTargetDAGCombine(ISD::SIGN_EXTEND);
849 setTargetDAGCombine(ISD::ZERO_EXTEND);
850 setTargetDAGCombine(ISD::ANY_EXTEND);
852 if (Subtarget.useCRBits()) {
853 setTargetDAGCombine(ISD::TRUNCATE);
854 setTargetDAGCombine(ISD::SETCC);
855 setTargetDAGCombine(ISD::SELECT_CC);
858 // Use reciprocal estimates.
859 if (TM.Options.UnsafeFPMath) {
860 setTargetDAGCombine(ISD::FDIV);
861 setTargetDAGCombine(ISD::FSQRT);
864 // Darwin long double math library functions have $LDBL128 appended.
865 if (Subtarget.isDarwin()) {
866 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
867 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
868 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
869 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
870 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
871 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
872 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
873 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
874 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
875 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
878 // With 32 condition bits, we don't need to sink (and duplicate) compares
879 // aggressively in CodeGenPrep.
880 if (Subtarget.useCRBits()) {
881 setHasMultipleConditionRegisters();
882 setJumpIsExpensive();
885 setMinFunctionAlignment(2);
886 if (Subtarget.isDarwin())
887 setPrefFunctionAlignment(4);
889 switch (Subtarget.getDarwinDirective()) {
893 case PPC::DIR_E500mc:
902 setPrefFunctionAlignment(4);
903 setPrefLoopAlignment(4);
907 setInsertFencesForAtomic(true);
909 if (Subtarget.enableMachineScheduler())
910 setSchedulingPreference(Sched::Source);
912 setSchedulingPreference(Sched::Hybrid);
914 computeRegisterProperties(STI.getRegisterInfo());
916 // The Freescale cores do better with aggressive inlining of memcpy and
917 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
918 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
919 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
920 MaxStoresPerMemset = 32;
921 MaxStoresPerMemsetOptSize = 16;
922 MaxStoresPerMemcpy = 32;
923 MaxStoresPerMemcpyOptSize = 8;
924 MaxStoresPerMemmove = 32;
925 MaxStoresPerMemmoveOptSize = 8;
926 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
927 // The A2 also benefits from (very) aggressive inlining of memcpy and
928 // friends. The overhead of a the function call, even when warm, can be
929 // over one hundred cycles.
930 MaxStoresPerMemset = 128;
931 MaxStoresPerMemcpy = 128;
932 MaxStoresPerMemmove = 128;
936 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
937 /// the desired ByVal argument alignment.
938 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
939 unsigned MaxMaxAlign) {
940 if (MaxAlign == MaxMaxAlign)
942 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
943 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
945 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
947 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
948 unsigned EltAlign = 0;
949 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
950 if (EltAlign > MaxAlign)
952 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
953 for (auto *EltTy : STy->elements()) {
954 unsigned EltAlign = 0;
955 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
956 if (EltAlign > MaxAlign)
958 if (MaxAlign == MaxMaxAlign)
964 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
965 /// function arguments in the caller parameter area.
966 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
967 const DataLayout &DL) const {
968 // Darwin passes everything on 4 byte boundary.
969 if (Subtarget.isDarwin())
972 // 16byte and wider vectors are passed on 16byte boundary.
973 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
974 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
975 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
976 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
980 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
981 switch ((PPCISD::NodeType)Opcode) {
982 case PPCISD::FIRST_NUMBER: break;
983 case PPCISD::FSEL: return "PPCISD::FSEL";
984 case PPCISD::FCFID: return "PPCISD::FCFID";
985 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
986 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
987 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
988 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
989 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
990 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
991 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
992 case PPCISD::FRE: return "PPCISD::FRE";
993 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
994 case PPCISD::STFIWX: return "PPCISD::STFIWX";
995 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
996 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
997 case PPCISD::VPERM: return "PPCISD::VPERM";
998 case PPCISD::CMPB: return "PPCISD::CMPB";
999 case PPCISD::Hi: return "PPCISD::Hi";
1000 case PPCISD::Lo: return "PPCISD::Lo";
1001 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1002 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1003 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1004 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1005 case PPCISD::SRL: return "PPCISD::SRL";
1006 case PPCISD::SRA: return "PPCISD::SRA";
1007 case PPCISD::SHL: return "PPCISD::SHL";
1008 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1009 case PPCISD::CALL: return "PPCISD::CALL";
1010 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1011 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1012 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1013 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1014 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1015 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1016 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1017 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1018 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1019 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1020 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1021 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1022 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1023 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1024 case PPCISD::VCMP: return "PPCISD::VCMP";
1025 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1026 case PPCISD::LBRX: return "PPCISD::LBRX";
1027 case PPCISD::STBRX: return "PPCISD::STBRX";
1028 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1029 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1030 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1031 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1032 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1033 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1034 case PPCISD::BDZ: return "PPCISD::BDZ";
1035 case PPCISD::MFFS: return "PPCISD::MFFS";
1036 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1037 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1038 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1039 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1040 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1041 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1042 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1043 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1044 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1045 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1046 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1047 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1048 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1049 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1050 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1051 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1052 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1053 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1054 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1055 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1056 case PPCISD::SC: return "PPCISD::SC";
1057 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1058 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1059 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1060 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1061 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1062 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1063 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1064 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1065 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1066 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1071 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1074 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1076 if (Subtarget.hasQPX())
1077 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1079 return VT.changeVectorElementTypeToInteger();
1082 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1083 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1087 //===----------------------------------------------------------------------===//
1088 // Node matching predicates, for use by the tblgen matching code.
1089 //===----------------------------------------------------------------------===//
1091 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1092 static bool isFloatingPointZero(SDValue Op) {
1093 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1094 return CFP->getValueAPF().isZero();
1095 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1096 // Maybe this has already been legalized into the constant pool?
1097 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1098 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1099 return CFP->getValueAPF().isZero();
1104 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1105 /// true if Op is undef or if it matches the specified value.
1106 static bool isConstantOrUndef(int Op, int Val) {
1107 return Op < 0 || Op == Val;
1110 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1111 /// VPKUHUM instruction.
1112 /// The ShuffleKind distinguishes between big-endian operations with
1113 /// two different inputs (0), either-endian operations with two identical
1114 /// inputs (1), and little-endian operations with two different inputs (2).
1115 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1116 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1117 SelectionDAG &DAG) {
1118 bool IsLE = DAG.getDataLayout().isLittleEndian();
1119 if (ShuffleKind == 0) {
1122 for (unsigned i = 0; i != 16; ++i)
1123 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1125 } else if (ShuffleKind == 2) {
1128 for (unsigned i = 0; i != 16; ++i)
1129 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1131 } else if (ShuffleKind == 1) {
1132 unsigned j = IsLE ? 0 : 1;
1133 for (unsigned i = 0; i != 8; ++i)
1134 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1135 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1141 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1142 /// VPKUWUM instruction.
1143 /// The ShuffleKind distinguishes between big-endian operations with
1144 /// two different inputs (0), either-endian operations with two identical
1145 /// inputs (1), and little-endian operations with two different inputs (2).
1146 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1147 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1148 SelectionDAG &DAG) {
1149 bool IsLE = DAG.getDataLayout().isLittleEndian();
1150 if (ShuffleKind == 0) {
1153 for (unsigned i = 0; i != 16; i += 2)
1154 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1155 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1157 } else if (ShuffleKind == 2) {
1160 for (unsigned i = 0; i != 16; i += 2)
1161 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1162 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1164 } else if (ShuffleKind == 1) {
1165 unsigned j = IsLE ? 0 : 2;
1166 for (unsigned i = 0; i != 8; i += 2)
1167 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1168 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1169 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1170 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1176 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1177 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1178 /// current subtarget.
1180 /// The ShuffleKind distinguishes between big-endian operations with
1181 /// two different inputs (0), either-endian operations with two identical
1182 /// inputs (1), and little-endian operations with two different inputs (2).
1183 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1184 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1185 SelectionDAG &DAG) {
1186 const PPCSubtarget& Subtarget =
1187 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1188 if (!Subtarget.hasP8Vector())
1191 bool IsLE = DAG.getDataLayout().isLittleEndian();
1192 if (ShuffleKind == 0) {
1195 for (unsigned i = 0; i != 16; i += 4)
1196 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1197 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1198 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1199 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1201 } else if (ShuffleKind == 2) {
1204 for (unsigned i = 0; i != 16; i += 4)
1205 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1206 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1207 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1208 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1210 } else if (ShuffleKind == 1) {
1211 unsigned j = IsLE ? 0 : 4;
1212 for (unsigned i = 0; i != 8; i += 4)
1213 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1214 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1215 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1216 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1217 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1218 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1219 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1220 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1226 /// isVMerge - Common function, used to match vmrg* shuffles.
1228 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1229 unsigned LHSStart, unsigned RHSStart) {
1230 if (N->getValueType(0) != MVT::v16i8)
1232 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1233 "Unsupported merge size!");
1235 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1236 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1237 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1238 LHSStart+j+i*UnitSize) ||
1239 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1240 RHSStart+j+i*UnitSize))
1246 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1247 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1248 /// The ShuffleKind distinguishes between big-endian merges with two
1249 /// different inputs (0), either-endian merges with two identical inputs (1),
1250 /// and little-endian merges with two different inputs (2). For the latter,
1251 /// the input operands are swapped (see PPCInstrAltivec.td).
1252 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1253 unsigned ShuffleKind, SelectionDAG &DAG) {
1254 if (DAG.getDataLayout().isLittleEndian()) {
1255 if (ShuffleKind == 1) // unary
1256 return isVMerge(N, UnitSize, 0, 0);
1257 else if (ShuffleKind == 2) // swapped
1258 return isVMerge(N, UnitSize, 0, 16);
1262 if (ShuffleKind == 1) // unary
1263 return isVMerge(N, UnitSize, 8, 8);
1264 else if (ShuffleKind == 0) // normal
1265 return isVMerge(N, UnitSize, 8, 24);
1271 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1272 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1273 /// The ShuffleKind distinguishes between big-endian merges with two
1274 /// different inputs (0), either-endian merges with two identical inputs (1),
1275 /// and little-endian merges with two different inputs (2). For the latter,
1276 /// the input operands are swapped (see PPCInstrAltivec.td).
1277 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1278 unsigned ShuffleKind, SelectionDAG &DAG) {
1279 if (DAG.getDataLayout().isLittleEndian()) {
1280 if (ShuffleKind == 1) // unary
1281 return isVMerge(N, UnitSize, 8, 8);
1282 else if (ShuffleKind == 2) // swapped
1283 return isVMerge(N, UnitSize, 8, 24);
1287 if (ShuffleKind == 1) // unary
1288 return isVMerge(N, UnitSize, 0, 0);
1289 else if (ShuffleKind == 0) // normal
1290 return isVMerge(N, UnitSize, 0, 16);
1297 * \brief Common function used to match vmrgew and vmrgow shuffles
1299 * The indexOffset determines whether to look for even or odd words in
1300 * the shuffle mask. This is based on the of the endianness of the target
1303 * - Use offset of 0 to check for odd elements
1304 * - Use offset of 4 to check for even elements
1306 * - Use offset of 0 to check for even elements
1307 * - Use offset of 4 to check for odd elements
1308 * A detailed description of the vector element ordering for little endian and
1309 * big endian can be found at
1310 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1311 * Targeting your applications - what little endian and big endian IBM XL C/C++
1312 * compiler differences mean to you
1314 * The mask to the shuffle vector instruction specifies the indices of the
1315 * elements from the two input vectors to place in the result. The elements are
1316 * numbered in array-access order, starting with the first vector. These vectors
1317 * are always of type v16i8, thus each vector will contain 16 elements of size
1318 * 8. More info on the shuffle vector can be found in the
1319 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1320 * Language Reference.
1322 * The RHSStartValue indicates whether the same input vectors are used (unary)
1323 * or two different input vectors are used, based on the following:
1324 * - If the instruction uses the same vector for both inputs, the range of the
1325 * indices will be 0 to 15. In this case, the RHSStart value passed should
1327 * - If the instruction has two different vectors then the range of the
1328 * indices will be 0 to 31. In this case, the RHSStart value passed should
1329 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1330 * to 31 specify elements in the second vector).
1332 * \param[in] N The shuffle vector SD Node to analyze
1333 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1334 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1335 * vector to the shuffle_vector instruction
1336 * \return true iff this shuffle vector represents an even or odd word merge
1338 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1339 unsigned RHSStartValue) {
1340 if (N->getValueType(0) != MVT::v16i8)
1343 for (unsigned i = 0; i < 2; ++i)
1344 for (unsigned j = 0; j < 4; ++j)
1345 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1346 i*RHSStartValue+j+IndexOffset) ||
1347 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1348 i*RHSStartValue+j+IndexOffset+8))
1354 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1355 * vmrgow instructions.
1357 * \param[in] N The shuffle vector SD Node to analyze
1358 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1359 * \param[in] ShuffleKind Identify the type of merge:
1360 * - 0 = big-endian merge with two different inputs;
1361 * - 1 = either-endian merge with two identical inputs;
1362 * - 2 = little-endian merge with two different inputs (inputs are swapped for
1363 * little-endian merges).
1364 * \param[in] DAG The current SelectionDAG
1365 * \return true iff this shuffle mask
1367 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1368 unsigned ShuffleKind, SelectionDAG &DAG) {
1369 if (DAG.getDataLayout().isLittleEndian()) {
1370 unsigned indexOffset = CheckEven ? 4 : 0;
1371 if (ShuffleKind == 1) // Unary
1372 return isVMerge(N, indexOffset, 0);
1373 else if (ShuffleKind == 2) // swapped
1374 return isVMerge(N, indexOffset, 16);
1379 unsigned indexOffset = CheckEven ? 0 : 4;
1380 if (ShuffleKind == 1) // Unary
1381 return isVMerge(N, indexOffset, 0);
1382 else if (ShuffleKind == 0) // Normal
1383 return isVMerge(N, indexOffset, 16);
1390 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1391 /// amount, otherwise return -1.
1392 /// The ShuffleKind distinguishes between big-endian operations with two
1393 /// different inputs (0), either-endian operations with two identical inputs
1394 /// (1), and little-endian operations with two different inputs (2). For the
1395 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1396 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1397 SelectionDAG &DAG) {
1398 if (N->getValueType(0) != MVT::v16i8)
1401 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1403 // Find the first non-undef value in the shuffle mask.
1405 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1408 if (i == 16) return -1; // all undef.
1410 // Otherwise, check to see if the rest of the elements are consecutively
1411 // numbered from this value.
1412 unsigned ShiftAmt = SVOp->getMaskElt(i);
1413 if (ShiftAmt < i) return -1;
1416 bool isLE = DAG.getDataLayout().isLittleEndian();
1418 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1419 // Check the rest of the elements to see if they are consecutive.
1420 for (++i; i != 16; ++i)
1421 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1423 } else if (ShuffleKind == 1) {
1424 // Check the rest of the elements to see if they are consecutive.
1425 for (++i; i != 16; ++i)
1426 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1432 ShiftAmt = 16 - ShiftAmt;
1437 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1438 /// specifies a splat of a single element that is suitable for input to
1439 /// VSPLTB/VSPLTH/VSPLTW.
1440 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1441 assert(N->getValueType(0) == MVT::v16i8 &&
1442 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1444 // The consecutive indices need to specify an element, not part of two
1445 // different elements. So abandon ship early if this isn't the case.
1446 if (N->getMaskElt(0) % EltSize != 0)
1449 // This is a splat operation if each element of the permute is the same, and
1450 // if the value doesn't reference the second vector.
1451 unsigned ElementBase = N->getMaskElt(0);
1453 // FIXME: Handle UNDEF elements too!
1454 if (ElementBase >= 16)
1457 // Check that the indices are consecutive, in the case of a multi-byte element
1458 // splatted with a v16i8 mask.
1459 for (unsigned i = 1; i != EltSize; ++i)
1460 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1463 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1464 if (N->getMaskElt(i) < 0) continue;
1465 for (unsigned j = 0; j != EltSize; ++j)
1466 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1472 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1473 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1474 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1475 SelectionDAG &DAG) {
1476 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1477 assert(isSplatShuffleMask(SVOp, EltSize));
1478 if (DAG.getDataLayout().isLittleEndian())
1479 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1481 return SVOp->getMaskElt(0) / EltSize;
1484 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1485 /// by using a vspltis[bhw] instruction of the specified element size, return
1486 /// the constant being splatted. The ByteSize field indicates the number of
1487 /// bytes of each element [124] -> [bhw].
1488 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1489 SDValue OpVal(nullptr, 0);
1491 // If ByteSize of the splat is bigger than the element size of the
1492 // build_vector, then we have a case where we are checking for a splat where
1493 // multiple elements of the buildvector are folded together into a single
1494 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1495 unsigned EltSize = 16/N->getNumOperands();
1496 if (EltSize < ByteSize) {
1497 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1498 SDValue UniquedVals[4];
1499 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1501 // See if all of the elements in the buildvector agree across.
1502 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1503 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1504 // If the element isn't a constant, bail fully out.
1505 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1508 if (!UniquedVals[i&(Multiple-1)].getNode())
1509 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1510 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1511 return SDValue(); // no match.
1514 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1515 // either constant or undef values that are identical for each chunk. See
1516 // if these chunks can form into a larger vspltis*.
1518 // Check to see if all of the leading entries are either 0 or -1. If
1519 // neither, then this won't fit into the immediate field.
1520 bool LeadingZero = true;
1521 bool LeadingOnes = true;
1522 for (unsigned i = 0; i != Multiple-1; ++i) {
1523 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1525 LeadingZero &= isNullConstant(UniquedVals[i]);
1526 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1528 // Finally, check the least significant entry.
1530 if (!UniquedVals[Multiple-1].getNode())
1531 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
1532 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1533 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
1534 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1537 if (!UniquedVals[Multiple-1].getNode())
1538 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1539 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1540 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1541 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1547 // Check to see if this buildvec has a single non-undef value in its elements.
1548 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1549 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1550 if (!OpVal.getNode())
1551 OpVal = N->getOperand(i);
1552 else if (OpVal != N->getOperand(i))
1556 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1558 unsigned ValSizeInBytes = EltSize;
1560 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1561 Value = CN->getZExtValue();
1562 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1563 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1564 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1567 // If the splat value is larger than the element value, then we can never do
1568 // this splat. The only case that we could fit the replicated bits into our
1569 // immediate field for would be zero, and we prefer to use vxor for it.
1570 if (ValSizeInBytes < ByteSize) return SDValue();
1572 // If the element value is larger than the splat value, check if it consists
1573 // of a repeated bit pattern of size ByteSize.
1574 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1577 // Properly sign extend the value.
1578 int MaskVal = SignExtend32(Value, ByteSize * 8);
1580 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1581 if (MaskVal == 0) return SDValue();
1583 // Finally, if this value fits in a 5 bit sext field, return it
1584 if (SignExtend32<5>(MaskVal) == MaskVal)
1585 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1589 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1590 /// amount, otherwise return -1.
1591 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1592 EVT VT = N->getValueType(0);
1593 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1596 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1598 // Find the first non-undef value in the shuffle mask.
1600 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1603 if (i == 4) return -1; // all undef.
1605 // Otherwise, check to see if the rest of the elements are consecutively
1606 // numbered from this value.
1607 unsigned ShiftAmt = SVOp->getMaskElt(i);
1608 if (ShiftAmt < i) return -1;
1611 // Check the rest of the elements to see if they are consecutive.
1612 for (++i; i != 4; ++i)
1613 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1619 //===----------------------------------------------------------------------===//
1620 // Addressing Mode Selection
1621 //===----------------------------------------------------------------------===//
1623 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1624 /// or 64-bit immediate, and if the value can be accurately represented as a
1625 /// sign extension from a 16-bit value. If so, this returns true and the
1627 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1628 if (!isa<ConstantSDNode>(N))
1631 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1632 if (N->getValueType(0) == MVT::i32)
1633 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1635 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1637 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1638 return isIntS16Immediate(Op.getNode(), Imm);
1641 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1642 /// can be represented as an indexed [r+r] operation. Returns false if it
1643 /// can be more efficiently represented with [r+imm].
1644 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1646 SelectionDAG &DAG) const {
1648 if (N.getOpcode() == ISD::ADD) {
1649 if (isIntS16Immediate(N.getOperand(1), imm))
1650 return false; // r+i
1651 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1652 return false; // r+i
1654 Base = N.getOperand(0);
1655 Index = N.getOperand(1);
1657 } else if (N.getOpcode() == ISD::OR) {
1658 if (isIntS16Immediate(N.getOperand(1), imm))
1659 return false; // r+i can fold it if we can.
1661 // If this is an or of disjoint bitfields, we can codegen this as an add
1662 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1664 APInt LHSKnownZero, LHSKnownOne;
1665 APInt RHSKnownZero, RHSKnownOne;
1666 DAG.computeKnownBits(N.getOperand(0),
1667 LHSKnownZero, LHSKnownOne);
1669 if (LHSKnownZero.getBoolValue()) {
1670 DAG.computeKnownBits(N.getOperand(1),
1671 RHSKnownZero, RHSKnownOne);
1672 // If all of the bits are known zero on the LHS or RHS, the add won't
1674 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1675 Base = N.getOperand(0);
1676 Index = N.getOperand(1);
1685 // If we happen to be doing an i64 load or store into a stack slot that has
1686 // less than a 4-byte alignment, then the frame-index elimination may need to
1687 // use an indexed load or store instruction (because the offset may not be a
1688 // multiple of 4). The extra register needed to hold the offset comes from the
1689 // register scavenger, and it is possible that the scavenger will need to use
1690 // an emergency spill slot. As a result, we need to make sure that a spill slot
1691 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1693 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1694 // FIXME: This does not handle the LWA case.
1698 // NOTE: We'll exclude negative FIs here, which come from argument
1699 // lowering, because there are no known test cases triggering this problem
1700 // using packed structures (or similar). We can remove this exclusion if
1701 // we find such a test case. The reason why this is so test-case driven is
1702 // because this entire 'fixup' is only to prevent crashes (from the
1703 // register scavenger) on not-really-valid inputs. For example, if we have:
1705 // %b = bitcast i1* %a to i64*
1706 // store i64* a, i64 b
1707 // then the store should really be marked as 'align 1', but is not. If it
1708 // were marked as 'align 1' then the indexed form would have been
1709 // instruction-selected initially, and the problem this 'fixup' is preventing
1710 // won't happen regardless.
1714 MachineFunction &MF = DAG.getMachineFunction();
1715 MachineFrameInfo *MFI = MF.getFrameInfo();
1717 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1721 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1722 FuncInfo->setHasNonRISpills();
1725 /// Returns true if the address N can be represented by a base register plus
1726 /// a signed 16-bit displacement [r+imm], and if it is not better
1727 /// represented as reg+reg. If Aligned is true, only accept displacements
1728 /// suitable for STD and friends, i.e. multiples of 4.
1729 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1732 bool Aligned) const {
1733 // FIXME dl should come from parent load or store, not from address
1735 // If this can be more profitably realized as r+r, fail.
1736 if (SelectAddressRegReg(N, Disp, Base, DAG))
1739 if (N.getOpcode() == ISD::ADD) {
1741 if (isIntS16Immediate(N.getOperand(1), imm) &&
1742 (!Aligned || (imm & 3) == 0)) {
1743 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1744 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1745 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1746 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1748 Base = N.getOperand(0);
1750 return true; // [r+i]
1751 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1752 // Match LOAD (ADD (X, Lo(G))).
1753 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1754 && "Cannot handle constant offsets yet!");
1755 Disp = N.getOperand(1).getOperand(0); // The global address.
1756 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1757 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1758 Disp.getOpcode() == ISD::TargetConstantPool ||
1759 Disp.getOpcode() == ISD::TargetJumpTable);
1760 Base = N.getOperand(0);
1761 return true; // [&g+r]
1763 } else if (N.getOpcode() == ISD::OR) {
1765 if (isIntS16Immediate(N.getOperand(1), imm) &&
1766 (!Aligned || (imm & 3) == 0)) {
1767 // If this is an or of disjoint bitfields, we can codegen this as an add
1768 // (for better address arithmetic) if the LHS and RHS of the OR are
1769 // provably disjoint.
1770 APInt LHSKnownZero, LHSKnownOne;
1771 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1773 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1774 // If all of the bits are known zero on the LHS or RHS, the add won't
1776 if (FrameIndexSDNode *FI =
1777 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1778 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1779 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1781 Base = N.getOperand(0);
1783 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1787 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1788 // Loading from a constant address.
1790 // If this address fits entirely in a 16-bit sext immediate field, codegen
1793 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1794 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1795 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1796 CN->getValueType(0));
1800 // Handle 32-bit sext immediates with LIS + addr mode.
1801 if ((CN->getValueType(0) == MVT::i32 ||
1802 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1803 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1804 int Addr = (int)CN->getZExtValue();
1806 // Otherwise, break this down into an LIS + disp.
1807 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1809 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1811 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1812 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1817 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1818 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1819 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1820 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1823 return true; // [r+0]
1826 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1827 /// represented as an indexed [r+r] operation.
1828 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1830 SelectionDAG &DAG) const {
1831 // Check to see if we can easily represent this as an [r+r] address. This
1832 // will fail if it thinks that the address is more profitably represented as
1833 // reg+imm, e.g. where imm = 0.
1834 if (SelectAddressRegReg(N, Base, Index, DAG))
1837 // If the operand is an addition, always emit this as [r+r], since this is
1838 // better (for code size, and execution, as the memop does the add for free)
1839 // than emitting an explicit add.
1840 if (N.getOpcode() == ISD::ADD) {
1841 Base = N.getOperand(0);
1842 Index = N.getOperand(1);
1846 // Otherwise, do it the hard way, using R0 as the base register.
1847 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1853 /// getPreIndexedAddressParts - returns true by value, base pointer and
1854 /// offset pointer and addressing mode by reference if the node's address
1855 /// can be legally represented as pre-indexed load / store address.
1856 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1858 ISD::MemIndexedMode &AM,
1859 SelectionDAG &DAG) const {
1860 if (DisablePPCPreinc) return false;
1866 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1867 Ptr = LD->getBasePtr();
1868 VT = LD->getMemoryVT();
1869 Alignment = LD->getAlignment();
1870 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1871 Ptr = ST->getBasePtr();
1872 VT = ST->getMemoryVT();
1873 Alignment = ST->getAlignment();
1878 // PowerPC doesn't have preinc load/store instructions for vectors (except
1879 // for QPX, which does have preinc r+r forms).
1880 if (VT.isVector()) {
1881 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1883 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1889 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1891 // Common code will reject creating a pre-inc form if the base pointer
1892 // is a frame index, or if N is a store and the base pointer is either
1893 // the same as or a predecessor of the value being stored. Check for
1894 // those situations here, and try with swapped Base/Offset instead.
1897 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1900 SDValue Val = cast<StoreSDNode>(N)->getValue();
1901 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1906 std::swap(Base, Offset);
1912 // LDU/STU can only handle immediates that are a multiple of 4.
1913 if (VT != MVT::i64) {
1914 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1917 // LDU/STU need an address with at least 4-byte alignment.
1921 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1925 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1926 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1927 // sext i32 to i64 when addr mode is r+i.
1928 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1929 LD->getExtensionType() == ISD::SEXTLOAD &&
1930 isa<ConstantSDNode>(Offset))
1938 //===----------------------------------------------------------------------===//
1939 // LowerOperation implementation
1940 //===----------------------------------------------------------------------===//
1942 /// GetLabelAccessInfo - Return true if we should reference labels using a
1943 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1944 static bool GetLabelAccessInfo(const TargetMachine &TM,
1945 const PPCSubtarget &Subtarget,
1946 unsigned &HiOpFlags, unsigned &LoOpFlags,
1947 const GlobalValue *GV = nullptr) {
1948 HiOpFlags = PPCII::MO_HA;
1949 LoOpFlags = PPCII::MO_LO;
1951 // Don't use the pic base if not in PIC relocation model.
1952 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1955 HiOpFlags |= PPCII::MO_PIC_FLAG;
1956 LoOpFlags |= PPCII::MO_PIC_FLAG;
1959 // If this is a reference to a global value that requires a non-lazy-ptr, make
1960 // sure that instruction lowering adds it.
1961 if (GV && Subtarget.hasLazyResolverStub(GV)) {
1962 HiOpFlags |= PPCII::MO_NLP_FLAG;
1963 LoOpFlags |= PPCII::MO_NLP_FLAG;
1965 if (GV->hasHiddenVisibility()) {
1966 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1967 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1974 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1975 SelectionDAG &DAG) {
1977 EVT PtrVT = HiPart.getValueType();
1978 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1980 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1981 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1983 // With PIC, the first instruction is actually "GR+hi(&G)".
1985 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1986 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1988 // Generate non-pic code that has direct accesses to the constant pool.
1989 // The address of the global is just (hi(&g)+lo(&g)).
1990 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1993 static void setUsesTOCBasePtr(MachineFunction &MF) {
1994 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1995 FuncInfo->setUsesTOCBasePtr();
1998 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1999 setUsesTOCBasePtr(DAG.getMachineFunction());
2002 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
2004 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2005 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2006 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2008 SDValue Ops[] = { GA, Reg };
2009 return DAG.getMemIntrinsicNode(
2010 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2011 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2015 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2016 SelectionDAG &DAG) const {
2017 EVT PtrVT = Op.getValueType();
2018 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2019 const Constant *C = CP->getConstVal();
2021 // 64-bit SVR4 ABI code is always position-independent.
2022 // The actual address of the GlobalValue is stored in the TOC.
2023 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2024 setUsesTOCBasePtr(DAG);
2025 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2026 return getTOCEntry(DAG, SDLoc(CP), true, GA);
2029 unsigned MOHiFlag, MOLoFlag;
2031 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2033 if (isPIC && Subtarget.isSVR4ABI()) {
2034 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2035 PPCII::MO_PIC_FLAG);
2036 return getTOCEntry(DAG, SDLoc(CP), false, GA);
2040 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2042 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2043 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
2046 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2047 EVT PtrVT = Op.getValueType();
2048 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2050 // 64-bit SVR4 ABI code is always position-independent.
2051 // The actual address of the GlobalValue is stored in the TOC.
2052 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2053 setUsesTOCBasePtr(DAG);
2054 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2055 return getTOCEntry(DAG, SDLoc(JT), true, GA);
2058 unsigned MOHiFlag, MOLoFlag;
2060 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2062 if (isPIC && Subtarget.isSVR4ABI()) {
2063 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2064 PPCII::MO_PIC_FLAG);
2065 return getTOCEntry(DAG, SDLoc(GA), false, GA);
2068 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2069 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2070 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
2073 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2074 SelectionDAG &DAG) const {
2075 EVT PtrVT = Op.getValueType();
2076 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2077 const BlockAddress *BA = BASDN->getBlockAddress();
2079 // 64-bit SVR4 ABI code is always position-independent.
2080 // The actual BlockAddress is stored in the TOC.
2081 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2082 setUsesTOCBasePtr(DAG);
2083 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2084 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2087 unsigned MOHiFlag, MOLoFlag;
2089 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2090 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2091 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2092 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
2095 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2096 SelectionDAG &DAG) const {
2098 // FIXME: TLS addresses currently use medium model code sequences,
2099 // which is the most useful form. Eventually support for small and
2100 // large models could be added if users need it, at the cost of
2101 // additional complexity.
2102 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2103 if (DAG.getTarget().Options.EmulatedTLS)
2104 return LowerToTLSEmulatedModel(GA, DAG);
2107 const GlobalValue *GV = GA->getGlobal();
2108 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2109 bool is64bit = Subtarget.isPPC64();
2110 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2111 PICLevel::Level picLevel = M->getPICLevel();
2113 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2115 if (Model == TLSModel::LocalExec) {
2116 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2117 PPCII::MO_TPREL_HA);
2118 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2119 PPCII::MO_TPREL_LO);
2120 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2121 is64bit ? MVT::i64 : MVT::i32);
2122 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2123 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2126 if (Model == TLSModel::InitialExec) {
2127 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2128 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2132 setUsesTOCBasePtr(DAG);
2133 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2134 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2135 PtrVT, GOTReg, TGA);
2137 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2138 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2139 PtrVT, TGA, GOTPtr);
2140 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2143 if (Model == TLSModel::GeneralDynamic) {
2144 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2147 setUsesTOCBasePtr(DAG);
2148 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2149 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2152 if (picLevel == PICLevel::Small)
2153 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2155 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2157 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2161 if (Model == TLSModel::LocalDynamic) {
2162 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2165 setUsesTOCBasePtr(DAG);
2166 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2167 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2170 if (picLevel == PICLevel::Small)
2171 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2173 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2175 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2176 PtrVT, GOTPtr, TGA, TGA);
2177 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2178 PtrVT, TLSAddr, TGA);
2179 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2182 llvm_unreachable("Unknown TLS model!");
2185 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2186 SelectionDAG &DAG) const {
2187 EVT PtrVT = Op.getValueType();
2188 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2190 const GlobalValue *GV = GSDN->getGlobal();
2192 // 64-bit SVR4 ABI code is always position-independent.
2193 // The actual address of the GlobalValue is stored in the TOC.
2194 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2195 setUsesTOCBasePtr(DAG);
2196 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2197 return getTOCEntry(DAG, DL, true, GA);
2200 unsigned MOHiFlag, MOLoFlag;
2202 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2204 if (isPIC && Subtarget.isSVR4ABI()) {
2205 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2207 PPCII::MO_PIC_FLAG);
2208 return getTOCEntry(DAG, DL, false, GA);
2212 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2214 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2216 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2218 // If the global reference is actually to a non-lazy-pointer, we have to do an
2219 // extra load to get the address of the global.
2220 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2221 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2222 false, false, false, 0);
2226 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2227 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2230 if (Op.getValueType() == MVT::v2i64) {
2231 // When the operands themselves are v2i64 values, we need to do something
2232 // special because VSX has no underlying comparison operations for these.
2233 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2234 // Equality can be handled by casting to the legal type for Altivec
2235 // comparisons, everything else needs to be expanded.
2236 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2237 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2238 DAG.getSetCC(dl, MVT::v4i32,
2239 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2240 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2247 // We handle most of these in the usual way.
2251 // If we're comparing for equality to zero, expose the fact that this is
2252 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2253 // fold the new nodes.
2254 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2255 if (C->isNullValue() && CC == ISD::SETEQ) {
2256 EVT VT = Op.getOperand(0).getValueType();
2257 SDValue Zext = Op.getOperand(0);
2258 if (VT.bitsLT(MVT::i32)) {
2260 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2262 unsigned Log2b = Log2_32(VT.getSizeInBits());
2263 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2264 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2265 DAG.getConstant(Log2b, dl, MVT::i32));
2266 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2268 // Leave comparisons against 0 and -1 alone for now, since they're usually
2269 // optimized. FIXME: revisit this when we can custom lower all setcc
2271 if (C->isAllOnesValue() || C->isNullValue())
2275 // If we have an integer seteq/setne, turn it into a compare against zero
2276 // by xor'ing the rhs with the lhs, which is faster than setting a
2277 // condition register, reading it back out, and masking the correct bit. The
2278 // normal approach here uses sub to do this instead of xor. Using xor exposes
2279 // the result to other bit-twiddling opportunities.
2280 EVT LHSVT = Op.getOperand(0).getValueType();
2281 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2282 EVT VT = Op.getValueType();
2283 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2285 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2290 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2291 const PPCSubtarget &Subtarget) const {
2292 SDNode *Node = Op.getNode();
2293 EVT VT = Node->getValueType(0);
2294 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2295 SDValue InChain = Node->getOperand(0);
2296 SDValue VAListPtr = Node->getOperand(1);
2297 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2300 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2303 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2304 VAListPtr, MachinePointerInfo(SV), MVT::i8,
2305 false, false, false, 0);
2306 InChain = GprIndex.getValue(1);
2308 if (VT == MVT::i64) {
2309 // Check if GprIndex is even
2310 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2311 DAG.getConstant(1, dl, MVT::i32));
2312 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2313 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2314 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2315 DAG.getConstant(1, dl, MVT::i32));
2316 // Align GprIndex to be even if it isn't
2317 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2321 // fpr index is 1 byte after gpr
2322 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2323 DAG.getConstant(1, dl, MVT::i32));
2326 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2327 FprPtr, MachinePointerInfo(SV), MVT::i8,
2328 false, false, false, 0);
2329 InChain = FprIndex.getValue(1);
2331 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2332 DAG.getConstant(8, dl, MVT::i32));
2334 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2335 DAG.getConstant(4, dl, MVT::i32));
2338 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2339 MachinePointerInfo(), false, false,
2341 InChain = OverflowArea.getValue(1);
2343 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2344 MachinePointerInfo(), false, false,
2346 InChain = RegSaveArea.getValue(1);
2348 // select overflow_area if index > 8
2349 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2350 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2352 // adjustment constant gpr_index * 4/8
2353 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2354 VT.isInteger() ? GprIndex : FprIndex,
2355 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2358 // OurReg = RegSaveArea + RegConstant
2359 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2362 // Floating types are 32 bytes into RegSaveArea
2363 if (VT.isFloatingPoint())
2364 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2365 DAG.getConstant(32, dl, MVT::i32));
2367 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2368 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2369 VT.isInteger() ? GprIndex : FprIndex,
2370 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2373 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2374 VT.isInteger() ? VAListPtr : FprPtr,
2375 MachinePointerInfo(SV),
2376 MVT::i8, false, false, 0);
2378 // determine if we should load from reg_save_area or overflow_area
2379 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2381 // increase overflow_area by 4/8 if gpr/fpr > 8
2382 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2383 DAG.getConstant(VT.isInteger() ? 4 : 8,
2386 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2389 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2391 MachinePointerInfo(),
2392 MVT::i32, false, false, 0);
2394 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2395 false, false, false, 0);
2398 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2399 const PPCSubtarget &Subtarget) const {
2400 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2402 // We have to copy the entire va_list struct:
2403 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2404 return DAG.getMemcpy(Op.getOperand(0), Op,
2405 Op.getOperand(1), Op.getOperand(2),
2406 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2407 false, MachinePointerInfo(), MachinePointerInfo());
2410 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2411 SelectionDAG &DAG) const {
2412 return Op.getOperand(0);
2415 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2416 SelectionDAG &DAG) const {
2417 SDValue Chain = Op.getOperand(0);
2418 SDValue Trmp = Op.getOperand(1); // trampoline
2419 SDValue FPtr = Op.getOperand(2); // nested function
2420 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2423 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2424 bool isPPC64 = (PtrVT == MVT::i64);
2425 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2427 TargetLowering::ArgListTy Args;
2428 TargetLowering::ArgListEntry Entry;
2430 Entry.Ty = IntPtrTy;
2431 Entry.Node = Trmp; Args.push_back(Entry);
2433 // TrampSize == (isPPC64 ? 48 : 40);
2434 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2435 isPPC64 ? MVT::i64 : MVT::i32);
2436 Args.push_back(Entry);
2438 Entry.Node = FPtr; Args.push_back(Entry);
2439 Entry.Node = Nest; Args.push_back(Entry);
2441 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2442 TargetLowering::CallLoweringInfo CLI(DAG);
2443 CLI.setDebugLoc(dl).setChain(Chain)
2444 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2445 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2446 std::move(Args), 0);
2448 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2449 return CallResult.second;
2452 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2453 const PPCSubtarget &Subtarget) const {
2454 MachineFunction &MF = DAG.getMachineFunction();
2455 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2459 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2460 // vastart just stores the address of the VarArgsFrameIndex slot into the
2461 // memory location argument.
2462 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2463 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2464 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2465 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2466 MachinePointerInfo(SV),
2470 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2471 // We suppose the given va_list is already allocated.
2474 // char gpr; /* index into the array of 8 GPRs
2475 // * stored in the register save area
2476 // * gpr=0 corresponds to r3,
2477 // * gpr=1 to r4, etc.
2479 // char fpr; /* index into the array of 8 FPRs
2480 // * stored in the register save area
2481 // * fpr=0 corresponds to f1,
2482 // * fpr=1 to f2, etc.
2484 // char *overflow_arg_area;
2485 // /* location on stack that holds
2486 // * the next overflow argument
2488 // char *reg_save_area;
2489 // /* where r3:r10 and f1:f8 (if saved)
2494 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2495 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2497 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2499 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2501 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2504 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2505 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2507 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2508 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2510 uint64_t FPROffset = 1;
2511 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2513 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2515 // Store first byte : number of int regs
2516 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2518 MachinePointerInfo(SV),
2519 MVT::i8, false, false, 0);
2520 uint64_t nextOffset = FPROffset;
2521 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2524 // Store second byte : number of float regs
2525 SDValue secondStore =
2526 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2527 MachinePointerInfo(SV, nextOffset), MVT::i8,
2529 nextOffset += StackOffset;
2530 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2532 // Store second word : arguments given on stack
2533 SDValue thirdStore =
2534 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2535 MachinePointerInfo(SV, nextOffset),
2537 nextOffset += FrameOffset;
2538 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2540 // Store third word : arguments given in registers
2541 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2542 MachinePointerInfo(SV, nextOffset),
2547 #include "PPCGenCallingConv.inc"
2549 // Function whose sole purpose is to kill compiler warnings
2550 // stemming from unused functions included from PPCGenCallingConv.inc.
2551 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2552 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2555 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2556 CCValAssign::LocInfo &LocInfo,
2557 ISD::ArgFlagsTy &ArgFlags,
2562 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2564 CCValAssign::LocInfo &LocInfo,
2565 ISD::ArgFlagsTy &ArgFlags,
2567 static const MCPhysReg ArgRegs[] = {
2568 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2569 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2571 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2573 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2575 // Skip one register if the first unallocated register has an even register
2576 // number and there are still argument registers available which have not been
2577 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2578 // need to skip a register if RegNum is odd.
2579 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2580 State.AllocateReg(ArgRegs[RegNum]);
2583 // Always return false here, as this function only makes sure that the first
2584 // unallocated register has an odd register number and does not actually
2585 // allocate a register for the current argument.
2589 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2591 CCValAssign::LocInfo &LocInfo,
2592 ISD::ArgFlagsTy &ArgFlags,
2594 static const MCPhysReg ArgRegs[] = {
2595 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2599 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2601 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2603 // If there is only one Floating-point register left we need to put both f64
2604 // values of a split ppc_fp128 value on the stack.
2605 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2606 State.AllocateReg(ArgRegs[RegNum]);
2609 // Always return false here, as this function only makes sure that the two f64
2610 // values a ppc_fp128 value is split into are both passed in registers or both
2611 // passed on the stack and does not actually allocate a register for the
2612 // current argument.
2616 /// FPR - The set of FP registers that should be allocated for arguments,
2618 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2619 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2620 PPC::F11, PPC::F12, PPC::F13};
2622 /// QFPR - The set of QPX registers that should be allocated for arguments.
2623 static const MCPhysReg QFPR[] = {
2624 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2625 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2627 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2629 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2630 unsigned PtrByteSize) {
2631 unsigned ArgSize = ArgVT.getStoreSize();
2632 if (Flags.isByVal())
2633 ArgSize = Flags.getByValSize();
2635 // Round up to multiples of the pointer size, except for array members,
2636 // which are always packed.
2637 if (!Flags.isInConsecutiveRegs())
2638 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2643 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2645 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2646 ISD::ArgFlagsTy Flags,
2647 unsigned PtrByteSize) {
2648 unsigned Align = PtrByteSize;
2650 // Altivec parameters are padded to a 16 byte boundary.
2651 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2652 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2653 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2654 ArgVT == MVT::v1i128)
2656 // QPX vector types stored in double-precision are padded to a 32 byte
2658 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2661 // ByVal parameters are aligned as requested.
2662 if (Flags.isByVal()) {
2663 unsigned BVAlign = Flags.getByValAlign();
2664 if (BVAlign > PtrByteSize) {
2665 if (BVAlign % PtrByteSize != 0)
2667 "ByVal alignment is not a multiple of the pointer size");
2673 // Array members are always packed to their original alignment.
2674 if (Flags.isInConsecutiveRegs()) {
2675 // If the array member was split into multiple registers, the first
2676 // needs to be aligned to the size of the full type. (Except for
2677 // ppcf128, which is only aligned as its f64 components.)
2678 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2679 Align = OrigVT.getStoreSize();
2681 Align = ArgVT.getStoreSize();
2687 /// CalculateStackSlotUsed - Return whether this argument will use its
2688 /// stack slot (instead of being passed in registers). ArgOffset,
2689 /// AvailableFPRs, and AvailableVRs must hold the current argument
2690 /// position, and will be updated to account for this argument.
2691 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2692 ISD::ArgFlagsTy Flags,
2693 unsigned PtrByteSize,
2694 unsigned LinkageSize,
2695 unsigned ParamAreaSize,
2696 unsigned &ArgOffset,
2697 unsigned &AvailableFPRs,
2698 unsigned &AvailableVRs, bool HasQPX) {
2699 bool UseMemory = false;
2701 // Respect alignment of argument on the stack.
2703 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2704 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2705 // If there's no space left in the argument save area, we must
2706 // use memory (this check also catches zero-sized arguments).
2707 if (ArgOffset >= LinkageSize + ParamAreaSize)
2710 // Allocate argument on the stack.
2711 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2712 if (Flags.isInConsecutiveRegsLast())
2713 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2714 // If we overran the argument save area, we must use memory
2715 // (this check catches arguments passed partially in memory)
2716 if (ArgOffset > LinkageSize + ParamAreaSize)
2719 // However, if the argument is actually passed in an FPR or a VR,
2720 // we don't use memory after all.
2721 if (!Flags.isByVal()) {
2722 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2723 // QPX registers overlap with the scalar FP registers.
2724 (HasQPX && (ArgVT == MVT::v4f32 ||
2725 ArgVT == MVT::v4f64 ||
2726 ArgVT == MVT::v4i1)))
2727 if (AvailableFPRs > 0) {
2731 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2732 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2733 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2734 ArgVT == MVT::v1i128)
2735 if (AvailableVRs > 0) {
2744 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2745 /// ensure minimum alignment required for target.
2746 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2747 unsigned NumBytes) {
2748 unsigned TargetAlign = Lowering->getStackAlignment();
2749 unsigned AlignMask = TargetAlign - 1;
2750 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2755 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2756 CallingConv::ID CallConv, bool isVarArg,
2757 const SmallVectorImpl<ISD::InputArg>
2759 SDLoc dl, SelectionDAG &DAG,
2760 SmallVectorImpl<SDValue> &InVals)
2762 if (Subtarget.isSVR4ABI()) {
2763 if (Subtarget.isPPC64())
2764 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2767 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2770 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2776 PPCTargetLowering::LowerFormalArguments_32SVR4(
2778 CallingConv::ID CallConv, bool isVarArg,
2779 const SmallVectorImpl<ISD::InputArg>
2781 SDLoc dl, SelectionDAG &DAG,
2782 SmallVectorImpl<SDValue> &InVals) const {
2784 // 32-bit SVR4 ABI Stack Frame Layout:
2785 // +-----------------------------------+
2786 // +--> | Back chain |
2787 // | +-----------------------------------+
2788 // | | Floating-point register save area |
2789 // | +-----------------------------------+
2790 // | | General register save area |
2791 // | +-----------------------------------+
2792 // | | CR save word |
2793 // | +-----------------------------------+
2794 // | | VRSAVE save word |
2795 // | +-----------------------------------+
2796 // | | Alignment padding |
2797 // | +-----------------------------------+
2798 // | | Vector register save area |
2799 // | +-----------------------------------+
2800 // | | Local variable space |
2801 // | +-----------------------------------+
2802 // | | Parameter list area |
2803 // | +-----------------------------------+
2804 // | | LR save word |
2805 // | +-----------------------------------+
2806 // SP--> +--- | Back chain |
2807 // +-----------------------------------+
2810 // System V Application Binary Interface PowerPC Processor Supplement
2811 // AltiVec Technology Programming Interface Manual
2813 MachineFunction &MF = DAG.getMachineFunction();
2814 MachineFrameInfo *MFI = MF.getFrameInfo();
2815 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2817 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2818 // Potential tail calls could cause overwriting of argument stack slots.
2819 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2820 (CallConv == CallingConv::Fast));
2821 unsigned PtrByteSize = 4;
2823 // Assign locations to all of the incoming arguments.
2824 SmallVector<CCValAssign, 16> ArgLocs;
2825 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2828 // Reserve space for the linkage area on the stack.
2829 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2830 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2832 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2834 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2835 CCValAssign &VA = ArgLocs[i];
2837 // Arguments stored in registers.
2838 if (VA.isRegLoc()) {
2839 const TargetRegisterClass *RC;
2840 EVT ValVT = VA.getValVT();
2842 switch (ValVT.getSimpleVT().SimpleTy) {
2844 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2847 RC = &PPC::GPRCRegClass;
2850 if (Subtarget.hasP8Vector())
2851 RC = &PPC::VSSRCRegClass;
2853 RC = &PPC::F4RCRegClass;
2856 if (Subtarget.hasVSX())
2857 RC = &PPC::VSFRCRegClass;
2859 RC = &PPC::F8RCRegClass;
2864 RC = &PPC::VRRCRegClass;
2867 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2871 RC = &PPC::VSHRCRegClass;
2874 RC = &PPC::QFRCRegClass;
2877 RC = &PPC::QBRCRegClass;
2881 // Transform the arguments stored in physical registers into virtual ones.
2882 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2883 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2884 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2886 if (ValVT == MVT::i1)
2887 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2889 InVals.push_back(ArgValue);
2891 // Argument stored in memory.
2892 assert(VA.isMemLoc());
2894 unsigned ArgSize = VA.getLocVT().getStoreSize();
2895 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2898 // Create load nodes to retrieve arguments from the stack.
2899 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2900 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2901 MachinePointerInfo(),
2902 false, false, false, 0));
2906 // Assign locations to all of the incoming aggregate by value arguments.
2907 // Aggregates passed by value are stored in the local variable space of the
2908 // caller's stack frame, right above the parameter list area.
2909 SmallVector<CCValAssign, 16> ByValArgLocs;
2910 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2911 ByValArgLocs, *DAG.getContext());
2913 // Reserve stack space for the allocations in CCInfo.
2914 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2916 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2918 // Area that is at least reserved in the caller of this function.
2919 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2920 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2922 // Set the size that is at least reserved in caller of this function. Tail
2923 // call optimized function's reserved stack space needs to be aligned so that
2924 // taking the difference between two stack areas will result in an aligned
2927 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2928 FuncInfo->setMinReservedArea(MinReservedArea);
2930 SmallVector<SDValue, 8> MemOps;
2932 // If the function takes variable number of arguments, make a frame index for
2933 // the start of the first vararg value... for expansion of llvm.va_start.
2935 static const MCPhysReg GPArgRegs[] = {
2936 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2937 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2939 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2941 static const MCPhysReg FPArgRegs[] = {
2942 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2945 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2946 if (DisablePPCFloatInVariadic)
2949 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2950 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2952 // Make room for NumGPArgRegs and NumFPArgRegs.
2953 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2954 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2956 FuncInfo->setVarArgsStackOffset(
2957 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2958 CCInfo.getNextStackOffset(), true));
2960 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2961 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2963 // The fixed integer arguments of a variadic function are stored to the
2964 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2965 // the result of va_next.
2966 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2967 // Get an existing live-in vreg, or add a new one.
2968 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2970 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2972 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2973 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2974 MachinePointerInfo(), false, false, 0);
2975 MemOps.push_back(Store);
2976 // Increment the address by four for the next argument to store
2977 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2978 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2981 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2983 // The double arguments are stored to the VarArgsFrameIndex
2985 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2986 // Get an existing live-in vreg, or add a new one.
2987 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2989 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2991 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2992 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2993 MachinePointerInfo(), false, false, 0);
2994 MemOps.push_back(Store);
2995 // Increment the address by eight for the next argument to store
2996 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
2998 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3002 if (!MemOps.empty())
3003 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3008 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3009 // value to MVT::i64 and then truncate to the correct register size.
3011 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
3012 SelectionDAG &DAG, SDValue ArgVal,
3015 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3016 DAG.getValueType(ObjectVT));
3017 else if (Flags.isZExt())
3018 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3019 DAG.getValueType(ObjectVT));
3021 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3025 PPCTargetLowering::LowerFormalArguments_64SVR4(
3027 CallingConv::ID CallConv, bool isVarArg,
3028 const SmallVectorImpl<ISD::InputArg>
3030 SDLoc dl, SelectionDAG &DAG,
3031 SmallVectorImpl<SDValue> &InVals) const {
3032 // TODO: add description of PPC stack frame format, or at least some docs.
3034 bool isELFv2ABI = Subtarget.isELFv2ABI();
3035 bool isLittleEndian = Subtarget.isLittleEndian();
3036 MachineFunction &MF = DAG.getMachineFunction();
3037 MachineFrameInfo *MFI = MF.getFrameInfo();
3038 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3040 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3041 "fastcc not supported on varargs functions");
3043 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3044 // Potential tail calls could cause overwriting of argument stack slots.
3045 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3046 (CallConv == CallingConv::Fast));
3047 unsigned PtrByteSize = 8;
3048 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3050 static const MCPhysReg GPR[] = {
3051 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3052 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3054 static const MCPhysReg VR[] = {
3055 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3056 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3058 static const MCPhysReg VSRH[] = {
3059 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3060 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3063 const unsigned Num_GPR_Regs = array_lengthof(GPR);
3064 const unsigned Num_FPR_Regs = 13;
3065 const unsigned Num_VR_Regs = array_lengthof(VR);
3066 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3068 // Do a first pass over the arguments to determine whether the ABI
3069 // guarantees that our caller has allocated the parameter save area
3070 // on its stack frame. In the ELFv1 ABI, this is always the case;
3071 // in the ELFv2 ABI, it is true if this is a vararg function or if
3072 // any parameter is located in a stack slot.
3074 bool HasParameterArea = !isELFv2ABI || isVarArg;
3075 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3076 unsigned NumBytes = LinkageSize;
3077 unsigned AvailableFPRs = Num_FPR_Regs;
3078 unsigned AvailableVRs = Num_VR_Regs;
3079 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3080 if (Ins[i].Flags.isNest())
3083 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3084 PtrByteSize, LinkageSize, ParamAreaSize,
3085 NumBytes, AvailableFPRs, AvailableVRs,
3086 Subtarget.hasQPX()))
3087 HasParameterArea = true;
3090 // Add DAG nodes to load the arguments or copy them out of registers. On
3091 // entry to a function on PPC, the arguments start after the linkage area,
3092 // although the first ones are often in registers.
3094 unsigned ArgOffset = LinkageSize;
3095 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3096 unsigned &QFPR_idx = FPR_idx;
3097 SmallVector<SDValue, 8> MemOps;
3098 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3099 unsigned CurArgIdx = 0;
3100 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3102 bool needsLoad = false;
3103 EVT ObjectVT = Ins[ArgNo].VT;
3104 EVT OrigVT = Ins[ArgNo].ArgVT;
3105 unsigned ObjSize = ObjectVT.getStoreSize();
3106 unsigned ArgSize = ObjSize;
3107 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3108 if (Ins[ArgNo].isOrigArg()) {
3109 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3110 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3112 // We re-align the argument offset for each argument, except when using the
3113 // fast calling convention, when we need to make sure we do that only when
3114 // we'll actually use a stack slot.
3115 unsigned CurArgOffset, Align;
3116 auto ComputeArgOffset = [&]() {
3117 /* Respect alignment of argument on the stack. */
3118 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3119 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3120 CurArgOffset = ArgOffset;
3123 if (CallConv != CallingConv::Fast) {
3126 /* Compute GPR index associated with argument offset. */
3127 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3128 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3131 // FIXME the codegen can be much improved in some cases.
3132 // We do not have to keep everything in memory.
3133 if (Flags.isByVal()) {
3134 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3136 if (CallConv == CallingConv::Fast)
3139 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3140 ObjSize = Flags.getByValSize();
3141 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3142 // Empty aggregate parameters do not take up registers. Examples:
3146 // etc. However, we have to provide a place-holder in InVals, so
3147 // pretend we have an 8-byte item at the current address for that
3150 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3151 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3152 InVals.push_back(FIN);
3156 // Create a stack object covering all stack doublewords occupied
3157 // by the argument. If the argument is (fully or partially) on
3158 // the stack, or if the argument is fully in registers but the
3159 // caller has allocated the parameter save anyway, we can refer
3160 // directly to the caller's stack frame. Otherwise, create a
3161 // local copy in our own frame.
3163 if (HasParameterArea ||
3164 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3165 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3167 FI = MFI->CreateStackObject(ArgSize, Align, false);
3168 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3170 // Handle aggregates smaller than 8 bytes.
3171 if (ObjSize < PtrByteSize) {
3172 // The value of the object is its address, which differs from the
3173 // address of the enclosing doubleword on big-endian systems.
3175 if (!isLittleEndian) {
3176 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3177 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3179 InVals.push_back(Arg);
3181 if (GPR_idx != Num_GPR_Regs) {
3182 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3183 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3186 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3187 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3188 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3189 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3190 MachinePointerInfo(&*FuncArg), ObjType,
3193 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3194 // store the whole register as-is to the parameter save area
3197 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3198 MachinePointerInfo(&*FuncArg), false, false, 0);
3201 MemOps.push_back(Store);
3203 // Whether we copied from a register or not, advance the offset
3204 // into the parameter save area by a full doubleword.
3205 ArgOffset += PtrByteSize;
3209 // The value of the object is its address, which is the address of
3210 // its first stack doubleword.
3211 InVals.push_back(FIN);
3213 // Store whatever pieces of the object are in registers to memory.
3214 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3215 if (GPR_idx == Num_GPR_Regs)
3218 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3219 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3222 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3223 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3226 DAG.getStore(Val.getValue(1), dl, Val, Addr,
3227 MachinePointerInfo(&*FuncArg, j), false, false, 0);
3228 MemOps.push_back(Store);
3231 ArgOffset += ArgSize;
3235 switch (ObjectVT.getSimpleVT().SimpleTy) {
3236 default: llvm_unreachable("Unhandled argument type!");
3240 if (Flags.isNest()) {
3241 // The 'nest' parameter, if any, is passed in R11.
3242 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3243 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3245 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3246 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3251 // These can be scalar arguments or elements of an integer array type
3252 // passed directly. Clang may use those instead of "byval" aggregate
3253 // types to avoid forcing arguments to memory unnecessarily.
3254 if (GPR_idx != Num_GPR_Regs) {
3255 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3256 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3258 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3259 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3260 // value to MVT::i64 and then truncate to the correct register size.
3261 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3263 if (CallConv == CallingConv::Fast)
3267 ArgSize = PtrByteSize;
3269 if (CallConv != CallingConv::Fast || needsLoad)
3275 // These can be scalar arguments or elements of a float array type
3276 // passed directly. The latter are used to implement ELFv2 homogenous
3277 // float aggregates.
3278 if (FPR_idx != Num_FPR_Regs) {
3281 if (ObjectVT == MVT::f32)
3282 VReg = MF.addLiveIn(FPR[FPR_idx],
3283 Subtarget.hasP8Vector()
3284 ? &PPC::VSSRCRegClass
3285 : &PPC::F4RCRegClass);
3287 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3288 ? &PPC::VSFRCRegClass
3289 : &PPC::F8RCRegClass);
3291 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3293 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3294 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3295 // once we support fp <-> gpr moves.
3297 // This can only ever happen in the presence of f32 array types,
3298 // since otherwise we never run out of FPRs before running out
3300 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3301 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3303 if (ObjectVT == MVT::f32) {
3304 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3305 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3306 DAG.getConstant(32, dl, MVT::i32));
3307 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3310 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3312 if (CallConv == CallingConv::Fast)
3318 // When passing an array of floats, the array occupies consecutive
3319 // space in the argument area; only round up to the next doubleword
3320 // at the end of the array. Otherwise, each float takes 8 bytes.
3321 if (CallConv != CallingConv::Fast || needsLoad) {
3322 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3323 ArgOffset += ArgSize;
3324 if (Flags.isInConsecutiveRegsLast())
3325 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3335 if (!Subtarget.hasQPX()) {
3336 // These can be scalar arguments or elements of a vector array type
3337 // passed directly. The latter are used to implement ELFv2 homogenous
3338 // vector aggregates.
3339 if (VR_idx != Num_VR_Regs) {
3340 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3341 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3342 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3343 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3346 if (CallConv == CallingConv::Fast)
3351 if (CallConv != CallingConv::Fast || needsLoad)
3356 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3357 "Invalid QPX parameter type");
3362 // QPX vectors are treated like their scalar floating-point subregisters
3363 // (except that they're larger).
3364 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3365 if (QFPR_idx != Num_QFPR_Regs) {
3366 const TargetRegisterClass *RC;
3367 switch (ObjectVT.getSimpleVT().SimpleTy) {
3368 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3369 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3370 default: RC = &PPC::QBRCRegClass; break;
3373 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3374 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3377 if (CallConv == CallingConv::Fast)
3381 if (CallConv != CallingConv::Fast || needsLoad)
3386 // We need to load the argument to a virtual register if we determined
3387 // above that we ran out of physical registers of the appropriate type.
3389 if (ObjSize < ArgSize && !isLittleEndian)
3390 CurArgOffset += ArgSize - ObjSize;
3391 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3392 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3393 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3394 false, false, false, 0);
3397 InVals.push_back(ArgVal);
3400 // Area that is at least reserved in the caller of this function.
3401 unsigned MinReservedArea;
3402 if (HasParameterArea)
3403 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3405 MinReservedArea = LinkageSize;
3407 // Set the size that is at least reserved in caller of this function. Tail
3408 // call optimized functions' reserved stack space needs to be aligned so that
3409 // taking the difference between two stack areas will result in an aligned
3412 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3413 FuncInfo->setMinReservedArea(MinReservedArea);
3415 // If the function takes variable number of arguments, make a frame index for
3416 // the start of the first vararg value... for expansion of llvm.va_start.
3418 int Depth = ArgOffset;
3420 FuncInfo->setVarArgsFrameIndex(
3421 MFI->CreateFixedObject(PtrByteSize, Depth, true));
3422 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3424 // If this function is vararg, store any remaining integer argument regs
3425 // to their spots on the stack so that they may be loaded by deferencing the
3426 // result of va_next.
3427 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3428 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3429 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3430 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3431 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3432 MachinePointerInfo(), false, false, 0);
3433 MemOps.push_back(Store);
3434 // Increment the address by four for the next argument to store
3435 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3436 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3440 if (!MemOps.empty())
3441 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3447 PPCTargetLowering::LowerFormalArguments_Darwin(
3449 CallingConv::ID CallConv, bool isVarArg,
3450 const SmallVectorImpl<ISD::InputArg>
3452 SDLoc dl, SelectionDAG &DAG,
3453 SmallVectorImpl<SDValue> &InVals) const {
3454 // TODO: add description of PPC stack frame format, or at least some docs.
3456 MachineFunction &MF = DAG.getMachineFunction();
3457 MachineFrameInfo *MFI = MF.getFrameInfo();
3458 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3460 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3461 bool isPPC64 = PtrVT == MVT::i64;
3462 // Potential tail calls could cause overwriting of argument stack slots.
3463 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3464 (CallConv == CallingConv::Fast));
3465 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3466 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3467 unsigned ArgOffset = LinkageSize;
3468 // Area that is at least reserved in caller of this function.
3469 unsigned MinReservedArea = ArgOffset;
3471 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3472 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3473 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3475 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3476 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3477 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3479 static const MCPhysReg VR[] = {
3480 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3481 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3484 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3485 const unsigned Num_FPR_Regs = 13;
3486 const unsigned Num_VR_Regs = array_lengthof( VR);
3488 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3490 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3492 // In 32-bit non-varargs functions, the stack space for vectors is after the
3493 // stack space for non-vectors. We do not use this space unless we have
3494 // too many vectors to fit in registers, something that only occurs in
3495 // constructed examples:), but we have to walk the arglist to figure
3496 // that out...for the pathological case, compute VecArgOffset as the
3497 // start of the vector parameter area. Computing VecArgOffset is the
3498 // entire point of the following loop.
3499 unsigned VecArgOffset = ArgOffset;
3500 if (!isVarArg && !isPPC64) {
3501 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3503 EVT ObjectVT = Ins[ArgNo].VT;
3504 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3506 if (Flags.isByVal()) {
3507 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3508 unsigned ObjSize = Flags.getByValSize();
3510 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3511 VecArgOffset += ArgSize;
3515 switch(ObjectVT.getSimpleVT().SimpleTy) {
3516 default: llvm_unreachable("Unhandled argument type!");
3522 case MVT::i64: // PPC64
3524 // FIXME: We are guaranteed to be !isPPC64 at this point.
3525 // Does MVT::i64 apply?
3532 // Nothing to do, we're only looking at Nonvector args here.
3537 // We've found where the vector parameter area in memory is. Skip the
3538 // first 12 parameters; these don't use that memory.
3539 VecArgOffset = ((VecArgOffset+15)/16)*16;
3540 VecArgOffset += 12*16;
3542 // Add DAG nodes to load the arguments or copy them out of registers. On
3543 // entry to a function on PPC, the arguments start after the linkage area,
3544 // although the first ones are often in registers.
3546 SmallVector<SDValue, 8> MemOps;
3547 unsigned nAltivecParamsAtEnd = 0;
3548 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3549 unsigned CurArgIdx = 0;
3550 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3552 bool needsLoad = false;
3553 EVT ObjectVT = Ins[ArgNo].VT;
3554 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3555 unsigned ArgSize = ObjSize;
3556 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3557 if (Ins[ArgNo].isOrigArg()) {
3558 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3559 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3561 unsigned CurArgOffset = ArgOffset;
3563 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3564 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3565 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3566 if (isVarArg || isPPC64) {
3567 MinReservedArea = ((MinReservedArea+15)/16)*16;
3568 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3571 } else nAltivecParamsAtEnd++;
3573 // Calculate min reserved area.
3574 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3578 // FIXME the codegen can be much improved in some cases.
3579 // We do not have to keep everything in memory.
3580 if (Flags.isByVal()) {
3581 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3583 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3584 ObjSize = Flags.getByValSize();
3585 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3586 // Objects of size 1 and 2 are right justified, everything else is
3587 // left justified. This means the memory address is adjusted forwards.
3588 if (ObjSize==1 || ObjSize==2) {
3589 CurArgOffset = CurArgOffset + (4 - ObjSize);
3591 // The value of the object is its address.
3592 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3593 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3594 InVals.push_back(FIN);
3595 if (ObjSize==1 || ObjSize==2) {
3596 if (GPR_idx != Num_GPR_Regs) {
3599 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3601 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3602 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3603 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3604 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3605 MachinePointerInfo(&*FuncArg),
3606 ObjType, false, false, 0);
3607 MemOps.push_back(Store);
3611 ArgOffset += PtrByteSize;
3615 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3616 // Store whatever pieces of the object are in registers
3617 // to memory. ArgOffset will be the address of the beginning
3619 if (GPR_idx != Num_GPR_Regs) {
3622 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3624 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3625 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3626 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3627 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3629 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3630 MachinePointerInfo(&*FuncArg, j), false, false, 0);
3631 MemOps.push_back(Store);
3633 ArgOffset += PtrByteSize;
3635 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3642 switch (ObjectVT.getSimpleVT().SimpleTy) {
3643 default: llvm_unreachable("Unhandled argument type!");
3647 if (GPR_idx != Num_GPR_Regs) {
3648 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3649 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3651 if (ObjectVT == MVT::i1)
3652 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3657 ArgSize = PtrByteSize;
3659 // All int arguments reserve stack space in the Darwin ABI.
3660 ArgOffset += PtrByteSize;
3664 case MVT::i64: // PPC64
3665 if (GPR_idx != Num_GPR_Regs) {
3666 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3667 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3669 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3670 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3671 // value to MVT::i64 and then truncate to the correct register size.
3672 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3677 ArgSize = PtrByteSize;
3679 // All int arguments reserve stack space in the Darwin ABI.
3685 // Every 4 bytes of argument space consumes one of the GPRs available for
3686 // argument passing.
3687 if (GPR_idx != Num_GPR_Regs) {
3689 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3692 if (FPR_idx != Num_FPR_Regs) {
3695 if (ObjectVT == MVT::f32)
3696 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3698 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3700 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3706 // All FP arguments reserve stack space in the Darwin ABI.
3707 ArgOffset += isPPC64 ? 8 : ObjSize;
3713 // Note that vector arguments in registers don't reserve stack space,
3714 // except in varargs functions.
3715 if (VR_idx != Num_VR_Regs) {
3716 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3717 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3719 while ((ArgOffset % 16) != 0) {
3720 ArgOffset += PtrByteSize;
3721 if (GPR_idx != Num_GPR_Regs)
3725 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3729 if (!isVarArg && !isPPC64) {
3730 // Vectors go after all the nonvectors.
3731 CurArgOffset = VecArgOffset;
3734 // Vectors are aligned.
3735 ArgOffset = ((ArgOffset+15)/16)*16;
3736 CurArgOffset = ArgOffset;
3744 // We need to load the argument to a virtual register if we determined above
3745 // that we ran out of physical registers of the appropriate type.
3747 int FI = MFI->CreateFixedObject(ObjSize,
3748 CurArgOffset + (ArgSize - ObjSize),
3750 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3751 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3752 false, false, false, 0);
3755 InVals.push_back(ArgVal);
3758 // Allow for Altivec parameters at the end, if needed.
3759 if (nAltivecParamsAtEnd) {
3760 MinReservedArea = ((MinReservedArea+15)/16)*16;
3761 MinReservedArea += 16*nAltivecParamsAtEnd;
3764 // Area that is at least reserved in the caller of this function.
3765 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3767 // Set the size that is at least reserved in caller of this function. Tail
3768 // call optimized functions' reserved stack space needs to be aligned so that
3769 // taking the difference between two stack areas will result in an aligned
3772 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3773 FuncInfo->setMinReservedArea(MinReservedArea);
3775 // If the function takes variable number of arguments, make a frame index for
3776 // the start of the first vararg value... for expansion of llvm.va_start.
3778 int Depth = ArgOffset;
3780 FuncInfo->setVarArgsFrameIndex(
3781 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3783 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3785 // If this function is vararg, store any remaining integer argument regs
3786 // to their spots on the stack so that they may be loaded by deferencing the
3787 // result of va_next.
3788 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3792 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3794 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3796 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3797 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3798 MachinePointerInfo(), false, false, 0);
3799 MemOps.push_back(Store);
3800 // Increment the address by four for the next argument to store
3801 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3802 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3806 if (!MemOps.empty())
3807 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3812 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3813 /// adjusted to accommodate the arguments for the tailcall.
3814 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3815 unsigned ParamSize) {
3817 if (!isTailCall) return 0;
3819 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3820 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3821 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3822 // Remember only if the new adjustement is bigger.
3823 if (SPDiff < FI->getTailCallSPDelta())
3824 FI->setTailCallSPDelta(SPDiff);
3829 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3830 /// for tail call optimization. Targets which want to do tail call
3831 /// optimization should implement this function.
3833 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3834 CallingConv::ID CalleeCC,
3836 const SmallVectorImpl<ISD::InputArg> &Ins,
3837 SelectionDAG& DAG) const {
3838 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3841 // Variable argument functions are not supported.
3845 MachineFunction &MF = DAG.getMachineFunction();
3846 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3847 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3848 // Functions containing by val parameters are not supported.
3849 for (unsigned i = 0; i != Ins.size(); i++) {
3850 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3851 if (Flags.isByVal()) return false;
3854 // Non-PIC/GOT tail calls are supported.
3855 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3858 // At the moment we can only do local tail calls (in same module, hidden
3859 // or protected) if we are generating PIC.
3860 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3861 return G->getGlobal()->hasHiddenVisibility()
3862 || G->getGlobal()->hasProtectedVisibility();
3868 /// isCallCompatibleAddress - Return the immediate to use if the specified
3869 /// 32-bit value is representable in the immediate field of a BxA instruction.
3870 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3871 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3872 if (!C) return nullptr;
3874 int Addr = C->getZExtValue();
3875 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3876 SignExtend32<26>(Addr) != Addr)
3877 return nullptr; // Top 6 bits have to be sext of immediate.
3879 return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
3880 DAG.getTargetLoweringInfo().getPointerTy(
3881 DAG.getDataLayout())).getNode();
3886 struct TailCallArgumentInfo {
3891 TailCallArgumentInfo() : FrameIdx(0) {}
3895 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3897 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3899 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3900 SmallVectorImpl<SDValue> &MemOpChains,
3902 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3903 SDValue Arg = TailCallArgs[i].Arg;
3904 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3905 int FI = TailCallArgs[i].FrameIdx;
3906 // Store relative to framepointer.
3907 MemOpChains.push_back(DAG.getStore(
3908 Chain, dl, Arg, FIN,
3909 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
3914 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3915 /// the appropriate stack slot for the tail call optimized function call.
3916 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3917 MachineFunction &MF,
3926 // Calculate the new stack slot for the return address.
3927 int SlotSize = isPPC64 ? 8 : 4;
3928 const PPCFrameLowering *FL =
3929 MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3930 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3931 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3932 NewRetAddrLoc, true);
3933 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3934 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3935 Chain = DAG.getStore(
3936 Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3937 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewRetAddr),
3940 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3941 // slot as the FP is never overwritten.
3943 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3944 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3946 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3947 Chain = DAG.getStore(
3948 Chain, dl, OldFP, NewFramePtrIdx,
3949 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewFPIdx),
3956 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3957 /// the position of the argument.
3959 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3960 SDValue Arg, int SPDiff, unsigned ArgOffset,
3961 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3962 int Offset = ArgOffset + SPDiff;
3963 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3964 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3965 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3966 SDValue FIN = DAG.getFrameIndex(FI, VT);
3967 TailCallArgumentInfo Info;
3969 Info.FrameIdxOp = FIN;
3971 TailCallArguments.push_back(Info);
3974 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3975 /// stack slot. Returns the chain as result and the loaded frame pointers in
3976 /// LROpOut/FPOpout. Used when tail calling.
3977 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3985 // Load the LR and FP stack slot for later adjusting.
3986 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3987 LROpOut = getReturnAddrFrameIndex(DAG);
3988 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3989 false, false, false, 0);
3990 Chain = SDValue(LROpOut.getNode(), 1);
3992 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3993 // slot as the FP is never overwritten.
3995 FPOpOut = getFramePointerFrameIndex(DAG);
3996 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3997 false, false, false, 0);
3998 Chain = SDValue(FPOpOut.getNode(), 1);
4004 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4005 /// by "Src" to address "Dst" of size "Size". Alignment information is
4006 /// specified by the specific parameter attribute. The copy will be passed as
4007 /// a byval function parameter.
4008 /// Sometimes what we are copying is the end of a larger object, the part that
4009 /// does not fit in registers.
4011 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
4012 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
4014 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4015 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4016 false, false, false, MachinePointerInfo(),
4017 MachinePointerInfo());
4020 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4023 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
4024 SDValue Arg, SDValue PtrOff, int SPDiff,
4025 unsigned ArgOffset, bool isPPC64, bool isTailCall,
4026 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4027 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
4029 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4034 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4036 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4037 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4038 DAG.getConstant(ArgOffset, dl, PtrVT));
4040 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4041 MachinePointerInfo(), false, false, 0));
4042 // Calculate and remember argument location.
4043 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4048 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4049 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
4050 SDValue LROp, SDValue FPOp, bool isDarwinABI,
4051 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4052 MachineFunction &MF = DAG.getMachineFunction();
4054 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4055 // might overwrite each other in case of tail call optimization.
4056 SmallVector<SDValue, 8> MemOpChains2;
4057 // Do not flag preceding copytoreg stuff together with the following stuff.
4059 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4061 if (!MemOpChains2.empty())
4062 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4064 // Store the return address to the appropriate stack slot.
4065 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
4066 isPPC64, isDarwinABI, dl);
4068 // Emit callseq_end just before tailcall node.
4069 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4070 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4071 InFlag = Chain.getValue(1);
4074 // Is this global address that of a function that can be called by name? (as
4075 // opposed to something that must hold a descriptor for an indirect call).
4076 static bool isFunctionGlobalAddress(SDValue Callee) {
4077 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4078 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4079 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4082 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
4089 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
4090 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
4091 bool isTailCall, bool IsPatchPoint, bool hasNest,
4092 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
4093 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4094 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4096 bool isPPC64 = Subtarget.isPPC64();
4097 bool isSVR4ABI = Subtarget.isSVR4ABI();
4098 bool isELFv2ABI = Subtarget.isELFv2ABI();
4100 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4101 NodeTys.push_back(MVT::Other); // Returns a chain
4102 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
4104 unsigned CallOpc = PPCISD::CALL;
4106 bool needIndirectCall = true;
4107 if (!isSVR4ABI || !isPPC64)
4108 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4109 // If this is an absolute destination address, use the munged value.
4110 Callee = SDValue(Dest, 0);
4111 needIndirectCall = false;
4114 if (isFunctionGlobalAddress(Callee)) {
4115 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4116 // A call to a TLS address is actually an indirect call to a
4117 // thread-specific pointer.
4118 unsigned OpFlags = 0;
4119 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4120 (Subtarget.getTargetTriple().isMacOSX() &&
4121 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
4122 !G->getGlobal()->isStrongDefinitionForLinker()) ||
4123 (Subtarget.isTargetELF() && !isPPC64 &&
4124 !G->getGlobal()->hasLocalLinkage() &&
4125 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4126 // PC-relative references to external symbols should go through $stub,
4127 // unless we're building with the leopard linker or later, which
4128 // automatically synthesizes these stubs.
4129 OpFlags = PPCII::MO_PLT_OR_STUB;
4132 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4133 // every direct call is) turn it into a TargetGlobalAddress /
4134 // TargetExternalSymbol node so that legalize doesn't hack it.
4135 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4136 Callee.getValueType(), 0, OpFlags);
4137 needIndirectCall = false;
4140 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4141 unsigned char OpFlags = 0;
4143 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4144 (Subtarget.getTargetTriple().isMacOSX() &&
4145 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
4146 (Subtarget.isTargetELF() && !isPPC64 &&
4147 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4148 // PC-relative references to external symbols should go through $stub,
4149 // unless we're building with the leopard linker or later, which
4150 // automatically synthesizes these stubs.
4151 OpFlags = PPCII::MO_PLT_OR_STUB;
4154 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4156 needIndirectCall = false;
4160 // We'll form an invalid direct call when lowering a patchpoint; the full
4161 // sequence for an indirect call is complicated, and many of the
4162 // instructions introduced might have side effects (and, thus, can't be
4163 // removed later). The call itself will be removed as soon as the
4164 // argument/return lowering is complete, so the fact that it has the wrong
4165 // kind of operands should not really matter.
4166 needIndirectCall = false;
4169 if (needIndirectCall) {
4170 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
4171 // to do the call, we can't use PPCISD::CALL.
4172 SDValue MTCTROps[] = {Chain, Callee, InFlag};
4174 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4175 // Function pointers in the 64-bit SVR4 ABI do not point to the function
4176 // entry point, but to the function descriptor (the function entry point
4177 // address is part of the function descriptor though).
4178 // The function descriptor is a three doubleword structure with the
4179 // following fields: function entry point, TOC base address and
4180 // environment pointer.
4181 // Thus for a call through a function pointer, the following actions need
4183 // 1. Save the TOC of the caller in the TOC save area of its stack
4184 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4185 // 2. Load the address of the function entry point from the function
4187 // 3. Load the TOC of the callee from the function descriptor into r2.
4188 // 4. Load the environment pointer from the function descriptor into
4190 // 5. Branch to the function entry point address.
4191 // 6. On return of the callee, the TOC of the caller needs to be
4192 // restored (this is done in FinishCall()).
4194 // The loads are scheduled at the beginning of the call sequence, and the
4195 // register copies are flagged together to ensure that no other
4196 // operations can be scheduled in between. E.g. without flagging the
4197 // copies together, a TOC access in the caller could be scheduled between
4198 // the assignment of the callee TOC and the branch to the callee, which
4199 // results in the TOC access going through the TOC of the callee instead
4200 // of going through the TOC of the caller, which leads to incorrect code.
4202 // Load the address of the function entry point from the function
4204 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4205 if (LDChain.getValueType() == MVT::Glue)
4206 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4208 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4210 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4211 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4212 false, false, LoadsInv, 8);
4214 // Load environment pointer into r11.
4215 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4216 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4217 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4218 MPI.getWithOffset(16), false, false,
4221 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4222 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4223 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4224 MPI.getWithOffset(8), false, false,
4227 setUsesTOCBasePtr(DAG);
4228 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4230 Chain = TOCVal.getValue(0);
4231 InFlag = TOCVal.getValue(1);
4233 // If the function call has an explicit 'nest' parameter, it takes the
4234 // place of the environment pointer.
4236 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4239 Chain = EnvVal.getValue(0);
4240 InFlag = EnvVal.getValue(1);
4243 MTCTROps[0] = Chain;
4244 MTCTROps[1] = LoadFuncPtr;
4245 MTCTROps[2] = InFlag;
4248 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4249 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4250 InFlag = Chain.getValue(1);
4253 NodeTys.push_back(MVT::Other);
4254 NodeTys.push_back(MVT::Glue);
4255 Ops.push_back(Chain);
4256 CallOpc = PPCISD::BCTRL;
4257 Callee.setNode(nullptr);
4258 // Add use of X11 (holding environment pointer)
4259 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4260 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4261 // Add CTR register as callee so a bctr can be emitted later.
4263 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4266 // If this is a direct call, pass the chain and the callee.
4267 if (Callee.getNode()) {
4268 Ops.push_back(Chain);
4269 Ops.push_back(Callee);
4271 // If this is a tail call add stack pointer delta.
4273 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4275 // Add argument registers to the end of the list so that they are known live
4277 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4278 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4279 RegsToPass[i].second.getValueType()));
4281 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4283 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4284 setUsesTOCBasePtr(DAG);
4285 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4292 bool isLocalCall(const SDValue &Callee)
4294 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4295 return G->getGlobal()->isStrongDefinitionForLinker();
4300 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4301 CallingConv::ID CallConv, bool isVarArg,
4302 const SmallVectorImpl<ISD::InputArg> &Ins,
4303 SDLoc dl, SelectionDAG &DAG,
4304 SmallVectorImpl<SDValue> &InVals) const {
4306 SmallVector<CCValAssign, 16> RVLocs;
4307 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4309 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4311 // Copy all of the result registers out of their specified physreg.
4312 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4313 CCValAssign &VA = RVLocs[i];
4314 assert(VA.isRegLoc() && "Can only return in registers!");
4316 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4317 VA.getLocReg(), VA.getLocVT(), InFlag);
4318 Chain = Val.getValue(1);
4319 InFlag = Val.getValue(2);
4321 switch (VA.getLocInfo()) {
4322 default: llvm_unreachable("Unknown loc info!");
4323 case CCValAssign::Full: break;
4324 case CCValAssign::AExt:
4325 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4327 case CCValAssign::ZExt:
4328 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4329 DAG.getValueType(VA.getValVT()));
4330 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4332 case CCValAssign::SExt:
4333 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4334 DAG.getValueType(VA.getValVT()));
4335 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4339 InVals.push_back(Val);
4346 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4347 bool isTailCall, bool isVarArg, bool IsPatchPoint,
4348 bool hasNest, SelectionDAG &DAG,
4349 SmallVector<std::pair<unsigned, SDValue>, 8>
4351 SDValue InFlag, SDValue Chain,
4352 SDValue CallSeqStart, SDValue &Callee,
4353 int SPDiff, unsigned NumBytes,
4354 const SmallVectorImpl<ISD::InputArg> &Ins,
4355 SmallVectorImpl<SDValue> &InVals,
4356 ImmutableCallSite *CS) const {
4358 std::vector<EVT> NodeTys;
4359 SmallVector<SDValue, 8> Ops;
4360 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4361 SPDiff, isTailCall, IsPatchPoint, hasNest,
4362 RegsToPass, Ops, NodeTys, CS, Subtarget);
4364 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4365 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4366 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4368 // When performing tail call optimization the callee pops its arguments off
4369 // the stack. Account for this here so these bytes can be pushed back on in
4370 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4371 int BytesCalleePops =
4372 (CallConv == CallingConv::Fast &&
4373 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4375 // Add a register mask operand representing the call-preserved registers.
4376 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4377 const uint32_t *Mask =
4378 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4379 assert(Mask && "Missing call preserved mask for calling convention");
4380 Ops.push_back(DAG.getRegisterMask(Mask));
4382 if (InFlag.getNode())
4383 Ops.push_back(InFlag);
4387 assert(((Callee.getOpcode() == ISD::Register &&
4388 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4389 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4390 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4391 isa<ConstantSDNode>(Callee)) &&
4392 "Expecting an global address, external symbol, absolute value or register");
4394 DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4395 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4398 // Add a NOP immediately after the branch instruction when using the 64-bit
4399 // SVR4 ABI. At link time, if caller and callee are in a different module and
4400 // thus have a different TOC, the call will be replaced with a call to a stub
4401 // function which saves the current TOC, loads the TOC of the callee and
4402 // branches to the callee. The NOP will be replaced with a load instruction
4403 // which restores the TOC of the caller from the TOC save slot of the current
4404 // stack frame. If caller and callee belong to the same module (and have the
4405 // same TOC), the NOP will remain unchanged.
4407 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4409 if (CallOpc == PPCISD::BCTRL) {
4410 // This is a call through a function pointer.
4411 // Restore the caller TOC from the save area into R2.
4412 // See PrepareCall() for more information about calls through function
4413 // pointers in the 64-bit SVR4 ABI.
4414 // We are using a target-specific load with r2 hard coded, because the
4415 // result of a target-independent load would never go directly into r2,
4416 // since r2 is a reserved register (which prevents the register allocator
4417 // from allocating it), resulting in an additional register being
4418 // allocated and an unnecessary move instruction being generated.
4419 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4421 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4422 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4423 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4424 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4425 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4427 // The address needs to go after the chain input but before the flag (or
4428 // any other variadic arguments).
4429 Ops.insert(std::next(Ops.begin()), AddTOC);
4430 } else if ((CallOpc == PPCISD::CALL) &&
4431 (!isLocalCall(Callee) ||
4432 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4433 // Otherwise insert NOP for non-local calls.
4434 CallOpc = PPCISD::CALL_NOP;
4437 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4438 InFlag = Chain.getValue(1);
4440 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4441 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4444 InFlag = Chain.getValue(1);
4446 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4447 Ins, dl, DAG, InVals);
4451 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4452 SmallVectorImpl<SDValue> &InVals) const {
4453 SelectionDAG &DAG = CLI.DAG;
4455 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4456 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4457 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4458 SDValue Chain = CLI.Chain;
4459 SDValue Callee = CLI.Callee;
4460 bool &isTailCall = CLI.IsTailCall;
4461 CallingConv::ID CallConv = CLI.CallConv;
4462 bool isVarArg = CLI.IsVarArg;
4463 bool IsPatchPoint = CLI.IsPatchPoint;
4464 ImmutableCallSite *CS = CLI.CS;
4467 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4470 if (!isTailCall && CS && CS->isMustTailCall())
4471 report_fatal_error("failed to perform tail call elimination on a call "
4472 "site marked musttail");
4474 if (Subtarget.isSVR4ABI()) {
4475 if (Subtarget.isPPC64())
4476 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4477 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4478 dl, DAG, InVals, CS);
4480 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4481 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4482 dl, DAG, InVals, CS);
4485 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4486 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4487 dl, DAG, InVals, CS);
4491 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4492 CallingConv::ID CallConv, bool isVarArg,
4493 bool isTailCall, bool IsPatchPoint,
4494 const SmallVectorImpl<ISD::OutputArg> &Outs,
4495 const SmallVectorImpl<SDValue> &OutVals,
4496 const SmallVectorImpl<ISD::InputArg> &Ins,
4497 SDLoc dl, SelectionDAG &DAG,
4498 SmallVectorImpl<SDValue> &InVals,
4499 ImmutableCallSite *CS) const {
4500 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4501 // of the 32-bit SVR4 ABI stack frame layout.
4503 assert((CallConv == CallingConv::C ||
4504 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4506 unsigned PtrByteSize = 4;
4508 MachineFunction &MF = DAG.getMachineFunction();
4510 // Mark this function as potentially containing a function that contains a
4511 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4512 // and restoring the callers stack pointer in this functions epilog. This is
4513 // done because by tail calling the called function might overwrite the value
4514 // in this function's (MF) stack pointer stack slot 0(SP).
4515 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4516 CallConv == CallingConv::Fast)
4517 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4519 // Count how many bytes are to be pushed on the stack, including the linkage
4520 // area, parameter list area and the part of the local variable space which
4521 // contains copies of aggregates which are passed by value.
4523 // Assign locations to all of the outgoing arguments.
4524 SmallVector<CCValAssign, 16> ArgLocs;
4525 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4528 // Reserve space for the linkage area on the stack.
4529 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4533 // Handle fixed and variable vector arguments differently.
4534 // Fixed vector arguments go into registers as long as registers are
4535 // available. Variable vector arguments always go into memory.
4536 unsigned NumArgs = Outs.size();
4538 for (unsigned i = 0; i != NumArgs; ++i) {
4539 MVT ArgVT = Outs[i].VT;
4540 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4543 if (Outs[i].IsFixed) {
4544 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4547 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4553 errs() << "Call operand #" << i << " has unhandled type "
4554 << EVT(ArgVT).getEVTString() << "\n";
4556 llvm_unreachable(nullptr);
4560 // All arguments are treated the same.
4561 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4564 // Assign locations to all of the outgoing aggregate by value arguments.
4565 SmallVector<CCValAssign, 16> ByValArgLocs;
4566 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4567 ByValArgLocs, *DAG.getContext());
4569 // Reserve stack space for the allocations in CCInfo.
4570 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4572 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4574 // Size of the linkage area, parameter list area and the part of the local
4575 // space variable where copies of aggregates which are passed by value are
4577 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4579 // Calculate by how many bytes the stack has to be adjusted in case of tail
4580 // call optimization.
4581 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4583 // Adjust the stack pointer for the new arguments...
4584 // These operations are automatically eliminated by the prolog/epilog pass
4585 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4587 SDValue CallSeqStart = Chain;
4589 // Load the return address and frame pointer so it can be moved somewhere else
4592 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4595 // Set up a copy of the stack pointer for use loading and storing any
4596 // arguments that may not fit in the registers available for argument
4598 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4600 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4601 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4602 SmallVector<SDValue, 8> MemOpChains;
4604 bool seenFloatArg = false;
4605 // Walk the register/memloc assignments, inserting copies/loads.
4606 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4609 CCValAssign &VA = ArgLocs[i];
4610 SDValue Arg = OutVals[i];
4611 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4613 if (Flags.isByVal()) {
4614 // Argument is an aggregate which is passed by value, thus we need to
4615 // create a copy of it in the local variable space of the current stack
4616 // frame (which is the stack frame of the caller) and pass the address of
4617 // this copy to the callee.
4618 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4619 CCValAssign &ByValVA = ByValArgLocs[j++];
4620 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4622 // Memory reserved in the local variable space of the callers stack frame.
4623 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4625 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4626 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4629 // Create a copy of the argument in the local area of the current
4631 SDValue MemcpyCall =
4632 CreateCopyOfByValArgument(Arg, PtrOff,
4633 CallSeqStart.getNode()->getOperand(0),
4636 // This must go outside the CALLSEQ_START..END.
4637 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4638 CallSeqStart.getNode()->getOperand(1),
4640 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4641 NewCallSeqStart.getNode());
4642 Chain = CallSeqStart = NewCallSeqStart;
4644 // Pass the address of the aggregate copy on the stack either in a
4645 // physical register or in the parameter list area of the current stack
4646 // frame to the callee.
4650 if (VA.isRegLoc()) {
4651 if (Arg.getValueType() == MVT::i1)
4652 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4654 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4655 // Put argument in a physical register.
4656 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4658 // Put argument in the parameter list area of the current stack frame.
4659 assert(VA.isMemLoc());
4660 unsigned LocMemOffset = VA.getLocMemOffset();
4663 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4664 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4667 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4668 MachinePointerInfo(),
4671 // Calculate and remember argument location.
4672 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4678 if (!MemOpChains.empty())
4679 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4681 // Build a sequence of copy-to-reg nodes chained together with token chain
4682 // and flag operands which copy the outgoing args into the appropriate regs.
4684 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4685 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4686 RegsToPass[i].second, InFlag);
4687 InFlag = Chain.getValue(1);
4690 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4693 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4694 SDValue Ops[] = { Chain, InFlag };
4696 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4697 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4699 InFlag = Chain.getValue(1);
4703 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4704 false, TailCallArguments);
4706 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
4707 /* unused except on PPC64 ELFv1 */ false, DAG,
4708 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4709 NumBytes, Ins, InVals, CS);
4712 // Copy an argument into memory, being careful to do this outside the
4713 // call sequence for the call to which the argument belongs.
4715 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4716 SDValue CallSeqStart,
4717 ISD::ArgFlagsTy Flags,
4720 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4721 CallSeqStart.getNode()->getOperand(0),
4723 // The MEMCPY must go outside the CALLSEQ_START..END.
4724 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4725 CallSeqStart.getNode()->getOperand(1),
4727 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4728 NewCallSeqStart.getNode());
4729 return NewCallSeqStart;
4733 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4734 CallingConv::ID CallConv, bool isVarArg,
4735 bool isTailCall, bool IsPatchPoint,
4736 const SmallVectorImpl<ISD::OutputArg> &Outs,
4737 const SmallVectorImpl<SDValue> &OutVals,
4738 const SmallVectorImpl<ISD::InputArg> &Ins,
4739 SDLoc dl, SelectionDAG &DAG,
4740 SmallVectorImpl<SDValue> &InVals,
4741 ImmutableCallSite *CS) const {
4743 bool isELFv2ABI = Subtarget.isELFv2ABI();
4744 bool isLittleEndian = Subtarget.isLittleEndian();
4745 unsigned NumOps = Outs.size();
4746 bool hasNest = false;
4748 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4749 unsigned PtrByteSize = 8;
4751 MachineFunction &MF = DAG.getMachineFunction();
4753 // Mark this function as potentially containing a function that contains a
4754 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4755 // and restoring the callers stack pointer in this functions epilog. This is
4756 // done because by tail calling the called function might overwrite the value
4757 // in this function's (MF) stack pointer stack slot 0(SP).
4758 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4759 CallConv == CallingConv::Fast)
4760 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4762 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4763 "fastcc not supported on varargs functions");
4765 // Count how many bytes are to be pushed on the stack, including the linkage
4766 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4767 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4768 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4769 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4770 unsigned NumBytes = LinkageSize;
4771 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4772 unsigned &QFPR_idx = FPR_idx;
4774 static const MCPhysReg GPR[] = {
4775 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4776 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4778 static const MCPhysReg VR[] = {
4779 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4780 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4782 static const MCPhysReg VSRH[] = {
4783 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4784 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4787 const unsigned NumGPRs = array_lengthof(GPR);
4788 const unsigned NumFPRs = 13;
4789 const unsigned NumVRs = array_lengthof(VR);
4790 const unsigned NumQFPRs = NumFPRs;
4792 // When using the fast calling convention, we don't provide backing for
4793 // arguments that will be in registers.
4794 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4796 // Add up all the space actually used.
4797 for (unsigned i = 0; i != NumOps; ++i) {
4798 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4799 EVT ArgVT = Outs[i].VT;
4800 EVT OrigVT = Outs[i].ArgVT;
4805 if (CallConv == CallingConv::Fast) {
4806 if (Flags.isByVal())
4807 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4809 switch (ArgVT.getSimpleVT().SimpleTy) {
4810 default: llvm_unreachable("Unexpected ValueType for argument!");
4814 if (++NumGPRsUsed <= NumGPRs)
4823 if (++NumVRsUsed <= NumVRs)
4827 // When using QPX, this is handled like a FP register, otherwise, it
4828 // is an Altivec register.
4829 if (Subtarget.hasQPX()) {
4830 if (++NumFPRsUsed <= NumFPRs)
4833 if (++NumVRsUsed <= NumVRs)
4839 case MVT::v4f64: // QPX
4840 case MVT::v4i1: // QPX
4841 if (++NumFPRsUsed <= NumFPRs)
4847 /* Respect alignment of argument on the stack. */
4849 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4850 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4852 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4853 if (Flags.isInConsecutiveRegsLast())
4854 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4857 unsigned NumBytesActuallyUsed = NumBytes;
4859 // The prolog code of the callee may store up to 8 GPR argument registers to
4860 // the stack, allowing va_start to index over them in memory if its varargs.
4861 // Because we cannot tell if this is needed on the caller side, we have to
4862 // conservatively assume that it is needed. As such, make sure we have at
4863 // least enough stack space for the caller to store the 8 GPRs.
4864 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4865 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4867 // Tail call needs the stack to be aligned.
4868 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4869 CallConv == CallingConv::Fast)
4870 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4872 // Calculate by how many bytes the stack has to be adjusted in case of tail
4873 // call optimization.
4874 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4876 // To protect arguments on the stack from being clobbered in a tail call,
4877 // force all the loads to happen before doing any other lowering.
4879 Chain = DAG.getStackArgumentTokenFactor(Chain);
4881 // Adjust the stack pointer for the new arguments...
4882 // These operations are automatically eliminated by the prolog/epilog pass
4883 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4885 SDValue CallSeqStart = Chain;
4887 // Load the return address and frame pointer so it can be move somewhere else
4890 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4893 // Set up a copy of the stack pointer for use loading and storing any
4894 // arguments that may not fit in the registers available for argument
4896 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4898 // Figure out which arguments are going to go in registers, and which in
4899 // memory. Also, if this is a vararg function, floating point operations
4900 // must be stored to our stack, and loaded into integer regs as well, if
4901 // any integer regs are available for argument passing.
4902 unsigned ArgOffset = LinkageSize;
4904 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4905 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4907 SmallVector<SDValue, 8> MemOpChains;
4908 for (unsigned i = 0; i != NumOps; ++i) {
4909 SDValue Arg = OutVals[i];
4910 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4911 EVT ArgVT = Outs[i].VT;
4912 EVT OrigVT = Outs[i].ArgVT;
4914 // PtrOff will be used to store the current argument to the stack if a
4915 // register cannot be found for it.
4918 // We re-align the argument offset for each argument, except when using the
4919 // fast calling convention, when we need to make sure we do that only when
4920 // we'll actually use a stack slot.
4921 auto ComputePtrOff = [&]() {
4922 /* Respect alignment of argument on the stack. */
4924 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4925 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4927 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
4929 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4932 if (CallConv != CallingConv::Fast) {
4935 /* Compute GPR index associated with argument offset. */
4936 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4937 GPR_idx = std::min(GPR_idx, NumGPRs);
4940 // Promote integers to 64-bit values.
4941 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4942 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4943 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4944 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4947 // FIXME memcpy is used way more than necessary. Correctness first.
4948 // Note: "by value" is code for passing a structure by value, not
4950 if (Flags.isByVal()) {
4951 // Note: Size includes alignment padding, so
4952 // struct x { short a; char b; }
4953 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4954 // These are the proper values we need for right-justifying the
4955 // aggregate in a parameter register.
4956 unsigned Size = Flags.getByValSize();
4958 // An empty aggregate parameter takes up no storage and no
4963 if (CallConv == CallingConv::Fast)
4966 // All aggregates smaller than 8 bytes must be passed right-justified.
4967 if (Size==1 || Size==2 || Size==4) {
4968 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4969 if (GPR_idx != NumGPRs) {
4970 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4971 MachinePointerInfo(), VT,
4972 false, false, false, 0);
4973 MemOpChains.push_back(Load.getValue(1));
4974 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4976 ArgOffset += PtrByteSize;
4981 if (GPR_idx == NumGPRs && Size < 8) {
4982 SDValue AddPtr = PtrOff;
4983 if (!isLittleEndian) {
4984 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
4985 PtrOff.getValueType());
4986 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4988 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4991 ArgOffset += PtrByteSize;
4994 // Copy entire object into memory. There are cases where gcc-generated
4995 // code assumes it is there, even if it could be put entirely into
4996 // registers. (This is not what the doc says.)
4998 // FIXME: The above statement is likely due to a misunderstanding of the
4999 // documents. All arguments must be copied into the parameter area BY
5000 // THE CALLEE in the event that the callee takes the address of any
5001 // formal argument. That has not yet been implemented. However, it is
5002 // reasonable to use the stack area as a staging area for the register
5005 // Skip this for small aggregates, as we will use the same slot for a
5006 // right-justified copy, below.
5008 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5012 // When a register is available, pass a small aggregate right-justified.
5013 if (Size < 8 && GPR_idx != NumGPRs) {
5014 // The easiest way to get this right-justified in a register
5015 // is to copy the structure into the rightmost portion of a
5016 // local variable slot, then load the whole slot into the
5018 // FIXME: The memcpy seems to produce pretty awful code for
5019 // small aggregates, particularly for packed ones.
5020 // FIXME: It would be preferable to use the slot in the
5021 // parameter save area instead of a new local variable.
5022 SDValue AddPtr = PtrOff;
5023 if (!isLittleEndian) {
5024 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5025 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5027 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5031 // Load the slot into the register.
5032 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
5033 MachinePointerInfo(),
5034 false, false, false, 0);
5035 MemOpChains.push_back(Load.getValue(1));
5036 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5038 // Done with this argument.
5039 ArgOffset += PtrByteSize;
5043 // For aggregates larger than PtrByteSize, copy the pieces of the
5044 // object that fit into registers from the parameter save area.
5045 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5046 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5047 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5048 if (GPR_idx != NumGPRs) {
5049 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5050 MachinePointerInfo(),
5051 false, false, false, 0);
5052 MemOpChains.push_back(Load.getValue(1));
5053 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5054 ArgOffset += PtrByteSize;
5056 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5063 switch (Arg.getSimpleValueType().SimpleTy) {
5064 default: llvm_unreachable("Unexpected ValueType for argument!");
5068 if (Flags.isNest()) {
5069 // The 'nest' parameter, if any, is passed in R11.
5070 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5075 // These can be scalar arguments or elements of an integer array type
5076 // passed directly. Clang may use those instead of "byval" aggregate
5077 // types to avoid forcing arguments to memory unnecessarily.
5078 if (GPR_idx != NumGPRs) {
5079 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5081 if (CallConv == CallingConv::Fast)
5084 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5085 true, isTailCall, false, MemOpChains,
5086 TailCallArguments, dl);
5087 if (CallConv == CallingConv::Fast)
5088 ArgOffset += PtrByteSize;
5090 if (CallConv != CallingConv::Fast)
5091 ArgOffset += PtrByteSize;
5095 // These can be scalar arguments or elements of a float array type
5096 // passed directly. The latter are used to implement ELFv2 homogenous
5097 // float aggregates.
5099 // Named arguments go into FPRs first, and once they overflow, the
5100 // remaining arguments go into GPRs and then the parameter save area.
5101 // Unnamed arguments for vararg functions always go to GPRs and
5102 // then the parameter save area. For now, put all arguments to vararg
5103 // routines always in both locations (FPR *and* GPR or stack slot).
5104 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5105 bool NeededLoad = false;
5107 // First load the argument into the next available FPR.
5108 if (FPR_idx != NumFPRs)
5109 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5111 // Next, load the argument into GPR or stack slot if needed.
5112 if (!NeedGPROrStack)
5114 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5115 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5116 // once we support fp <-> gpr moves.
5118 // In the non-vararg case, this can only ever happen in the
5119 // presence of f32 array types, since otherwise we never run
5120 // out of FPRs before running out of GPRs.
5123 // Double values are always passed in a single GPR.
5124 if (Arg.getValueType() != MVT::f32) {
5125 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5127 // Non-array float values are extended and passed in a GPR.
5128 } else if (!Flags.isInConsecutiveRegs()) {
5129 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5130 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5132 // If we have an array of floats, we collect every odd element
5133 // together with its predecessor into one GPR.
5134 } else if (ArgOffset % PtrByteSize != 0) {
5136 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5137 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5138 if (!isLittleEndian)
5140 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5142 // The final element, if even, goes into the first half of a GPR.
5143 } else if (Flags.isInConsecutiveRegsLast()) {
5144 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5145 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5146 if (!isLittleEndian)
5147 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5148 DAG.getConstant(32, dl, MVT::i32));
5150 // Non-final even elements are skipped; they will be handled
5151 // together the with subsequent argument on the next go-around.
5155 if (ArgVal.getNode())
5156 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5158 if (CallConv == CallingConv::Fast)
5161 // Single-precision floating-point values are mapped to the
5162 // second (rightmost) word of the stack doubleword.
5163 if (Arg.getValueType() == MVT::f32 &&
5164 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5165 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5166 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5169 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5170 true, isTailCall, false, MemOpChains,
5171 TailCallArguments, dl);
5175 // When passing an array of floats, the array occupies consecutive
5176 // space in the argument area; only round up to the next doubleword
5177 // at the end of the array. Otherwise, each float takes 8 bytes.
5178 if (CallConv != CallingConv::Fast || NeededLoad) {
5179 ArgOffset += (Arg.getValueType() == MVT::f32 &&
5180 Flags.isInConsecutiveRegs()) ? 4 : 8;
5181 if (Flags.isInConsecutiveRegsLast())
5182 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5193 if (!Subtarget.hasQPX()) {
5194 // These can be scalar arguments or elements of a vector array type
5195 // passed directly. The latter are used to implement ELFv2 homogenous
5196 // vector aggregates.
5198 // For a varargs call, named arguments go into VRs or on the stack as
5199 // usual; unnamed arguments always go to the stack or the corresponding
5200 // GPRs when within range. For now, we always put the value in both
5201 // locations (or even all three).
5203 // We could elide this store in the case where the object fits
5204 // entirely in R registers. Maybe later.
5205 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5206 MachinePointerInfo(), false, false, 0);
5207 MemOpChains.push_back(Store);
5208 if (VR_idx != NumVRs) {
5209 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5210 MachinePointerInfo(),
5211 false, false, false, 0);
5212 MemOpChains.push_back(Load.getValue(1));
5214 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5215 Arg.getSimpleValueType() == MVT::v2i64) ?
5216 VSRH[VR_idx] : VR[VR_idx];
5219 RegsToPass.push_back(std::make_pair(VReg, Load));
5222 for (unsigned i=0; i<16; i+=PtrByteSize) {
5223 if (GPR_idx == NumGPRs)
5225 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5226 DAG.getConstant(i, dl, PtrVT));
5227 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5228 false, false, false, 0);
5229 MemOpChains.push_back(Load.getValue(1));
5230 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5235 // Non-varargs Altivec params go into VRs or on the stack.
5236 if (VR_idx != NumVRs) {
5237 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5238 Arg.getSimpleValueType() == MVT::v2i64) ?
5239 VSRH[VR_idx] : VR[VR_idx];
5242 RegsToPass.push_back(std::make_pair(VReg, Arg));
5244 if (CallConv == CallingConv::Fast)
5247 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5248 true, isTailCall, true, MemOpChains,
5249 TailCallArguments, dl);
5250 if (CallConv == CallingConv::Fast)
5254 if (CallConv != CallingConv::Fast)
5259 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5260 "Invalid QPX parameter type");
5265 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5267 // We could elide this store in the case where the object fits
5268 // entirely in R registers. Maybe later.
5269 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5270 MachinePointerInfo(), false, false, 0);
5271 MemOpChains.push_back(Store);
5272 if (QFPR_idx != NumQFPRs) {
5273 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5274 Store, PtrOff, MachinePointerInfo(),
5275 false, false, false, 0);
5276 MemOpChains.push_back(Load.getValue(1));
5277 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5279 ArgOffset += (IsF32 ? 16 : 32);
5280 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5281 if (GPR_idx == NumGPRs)
5283 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5284 DAG.getConstant(i, dl, PtrVT));
5285 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5286 false, false, false, 0);
5287 MemOpChains.push_back(Load.getValue(1));
5288 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5293 // Non-varargs QPX params go into registers or on the stack.
5294 if (QFPR_idx != NumQFPRs) {
5295 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5297 if (CallConv == CallingConv::Fast)
5300 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5301 true, isTailCall, true, MemOpChains,
5302 TailCallArguments, dl);
5303 if (CallConv == CallingConv::Fast)
5304 ArgOffset += (IsF32 ? 16 : 32);
5307 if (CallConv != CallingConv::Fast)
5308 ArgOffset += (IsF32 ? 16 : 32);
5314 assert(NumBytesActuallyUsed == ArgOffset);
5315 (void)NumBytesActuallyUsed;
5317 if (!MemOpChains.empty())
5318 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5320 // Check if this is an indirect call (MTCTR/BCTRL).
5321 // See PrepareCall() for more information about calls through function
5322 // pointers in the 64-bit SVR4 ABI.
5323 if (!isTailCall && !IsPatchPoint &&
5324 !isFunctionGlobalAddress(Callee) &&
5325 !isa<ExternalSymbolSDNode>(Callee)) {
5326 // Load r2 into a virtual register and store it to the TOC save area.
5327 setUsesTOCBasePtr(DAG);
5328 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5329 // TOC save area offset.
5330 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5331 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5332 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5333 Chain = DAG.getStore(
5334 Val.getValue(1), dl, Val, AddPtr,
5335 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset),
5337 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5338 // This does not mean the MTCTR instruction must use R12; it's easier
5339 // to model this as an extra parameter, so do that.
5340 if (isELFv2ABI && !IsPatchPoint)
5341 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5344 // Build a sequence of copy-to-reg nodes chained together with token chain
5345 // and flag operands which copy the outgoing args into the appropriate regs.
5347 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5348 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5349 RegsToPass[i].second, InFlag);
5350 InFlag = Chain.getValue(1);
5354 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5355 FPOp, true, TailCallArguments);
5357 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, hasNest,
5358 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5359 SPDiff, NumBytes, Ins, InVals, CS);
5363 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5364 CallingConv::ID CallConv, bool isVarArg,
5365 bool isTailCall, bool IsPatchPoint,
5366 const SmallVectorImpl<ISD::OutputArg> &Outs,
5367 const SmallVectorImpl<SDValue> &OutVals,
5368 const SmallVectorImpl<ISD::InputArg> &Ins,
5369 SDLoc dl, SelectionDAG &DAG,
5370 SmallVectorImpl<SDValue> &InVals,
5371 ImmutableCallSite *CS) const {
5373 unsigned NumOps = Outs.size();
5375 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5376 bool isPPC64 = PtrVT == MVT::i64;
5377 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5379 MachineFunction &MF = DAG.getMachineFunction();
5381 // Mark this function as potentially containing a function that contains a
5382 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5383 // and restoring the callers stack pointer in this functions epilog. This is
5384 // done because by tail calling the called function might overwrite the value
5385 // in this function's (MF) stack pointer stack slot 0(SP).
5386 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5387 CallConv == CallingConv::Fast)
5388 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5390 // Count how many bytes are to be pushed on the stack, including the linkage
5391 // area, and parameter passing area. We start with 24/48 bytes, which is
5392 // prereserved space for [SP][CR][LR][3 x unused].
5393 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5394 unsigned NumBytes = LinkageSize;
5396 // Add up all the space actually used.
5397 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5398 // they all go in registers, but we must reserve stack space for them for
5399 // possible use by the caller. In varargs or 64-bit calls, parameters are
5400 // assigned stack space in order, with padding so Altivec parameters are
5402 unsigned nAltivecParamsAtEnd = 0;
5403 for (unsigned i = 0; i != NumOps; ++i) {
5404 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5405 EVT ArgVT = Outs[i].VT;
5406 // Varargs Altivec parameters are padded to a 16 byte boundary.
5407 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5408 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5409 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5410 if (!isVarArg && !isPPC64) {
5411 // Non-varargs Altivec parameters go after all the non-Altivec
5412 // parameters; handle those later so we know how much padding we need.
5413 nAltivecParamsAtEnd++;
5416 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5417 NumBytes = ((NumBytes+15)/16)*16;
5419 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5422 // Allow for Altivec parameters at the end, if needed.
5423 if (nAltivecParamsAtEnd) {
5424 NumBytes = ((NumBytes+15)/16)*16;
5425 NumBytes += 16*nAltivecParamsAtEnd;
5428 // The prolog code of the callee may store up to 8 GPR argument registers to
5429 // the stack, allowing va_start to index over them in memory if its varargs.
5430 // Because we cannot tell if this is needed on the caller side, we have to
5431 // conservatively assume that it is needed. As such, make sure we have at
5432 // least enough stack space for the caller to store the 8 GPRs.
5433 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5435 // Tail call needs the stack to be aligned.
5436 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5437 CallConv == CallingConv::Fast)
5438 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5440 // Calculate by how many bytes the stack has to be adjusted in case of tail
5441 // call optimization.
5442 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5444 // To protect arguments on the stack from being clobbered in a tail call,
5445 // force all the loads to happen before doing any other lowering.
5447 Chain = DAG.getStackArgumentTokenFactor(Chain);
5449 // Adjust the stack pointer for the new arguments...
5450 // These operations are automatically eliminated by the prolog/epilog pass
5451 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5453 SDValue CallSeqStart = Chain;
5455 // Load the return address and frame pointer so it can be move somewhere else
5458 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5461 // Set up a copy of the stack pointer for use loading and storing any
5462 // arguments that may not fit in the registers available for argument
5466 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5468 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5470 // Figure out which arguments are going to go in registers, and which in
5471 // memory. Also, if this is a vararg function, floating point operations
5472 // must be stored to our stack, and loaded into integer regs as well, if
5473 // any integer regs are available for argument passing.
5474 unsigned ArgOffset = LinkageSize;
5475 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5477 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5478 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5479 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5481 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5482 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5483 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5485 static const MCPhysReg VR[] = {
5486 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5487 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5489 const unsigned NumGPRs = array_lengthof(GPR_32);
5490 const unsigned NumFPRs = 13;
5491 const unsigned NumVRs = array_lengthof(VR);
5493 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5495 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5496 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5498 SmallVector<SDValue, 8> MemOpChains;
5499 for (unsigned i = 0; i != NumOps; ++i) {
5500 SDValue Arg = OutVals[i];
5501 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5503 // PtrOff will be used to store the current argument to the stack if a
5504 // register cannot be found for it.
5507 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5509 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5511 // On PPC64, promote integers to 64-bit values.
5512 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5513 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5514 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5515 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5518 // FIXME memcpy is used way more than necessary. Correctness first.
5519 // Note: "by value" is code for passing a structure by value, not
5521 if (Flags.isByVal()) {
5522 unsigned Size = Flags.getByValSize();
5523 // Very small objects are passed right-justified. Everything else is
5524 // passed left-justified.
5525 if (Size==1 || Size==2) {
5526 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5527 if (GPR_idx != NumGPRs) {
5528 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5529 MachinePointerInfo(), VT,
5530 false, false, false, 0);
5531 MemOpChains.push_back(Load.getValue(1));
5532 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5534 ArgOffset += PtrByteSize;
5536 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5537 PtrOff.getValueType());
5538 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5539 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5542 ArgOffset += PtrByteSize;
5546 // Copy entire object into memory. There are cases where gcc-generated
5547 // code assumes it is there, even if it could be put entirely into
5548 // registers. (This is not what the doc says.)
5549 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5553 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5554 // copy the pieces of the object that fit into registers from the
5555 // parameter save area.
5556 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5557 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5558 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5559 if (GPR_idx != NumGPRs) {
5560 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5561 MachinePointerInfo(),
5562 false, false, false, 0);
5563 MemOpChains.push_back(Load.getValue(1));
5564 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5565 ArgOffset += PtrByteSize;
5567 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5574 switch (Arg.getSimpleValueType().SimpleTy) {
5575 default: llvm_unreachable("Unexpected ValueType for argument!");
5579 if (GPR_idx != NumGPRs) {
5580 if (Arg.getValueType() == MVT::i1)
5581 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5583 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5585 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5586 isPPC64, isTailCall, false, MemOpChains,
5587 TailCallArguments, dl);
5589 ArgOffset += PtrByteSize;
5593 if (FPR_idx != NumFPRs) {
5594 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5597 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5598 MachinePointerInfo(), false, false, 0);
5599 MemOpChains.push_back(Store);
5601 // Float varargs are always shadowed in available integer registers
5602 if (GPR_idx != NumGPRs) {
5603 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5604 MachinePointerInfo(), false, false,
5606 MemOpChains.push_back(Load.getValue(1));
5607 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5609 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5610 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5611 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5612 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5613 MachinePointerInfo(),
5614 false, false, false, 0);
5615 MemOpChains.push_back(Load.getValue(1));
5616 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5619 // If we have any FPRs remaining, we may also have GPRs remaining.
5620 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5622 if (GPR_idx != NumGPRs)
5624 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5625 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5629 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5630 isPPC64, isTailCall, false, MemOpChains,
5631 TailCallArguments, dl);
5635 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5642 // These go aligned on the stack, or in the corresponding R registers
5643 // when within range. The Darwin PPC ABI doc claims they also go in
5644 // V registers; in fact gcc does this only for arguments that are
5645 // prototyped, not for those that match the ... We do it for all
5646 // arguments, seems to work.
5647 while (ArgOffset % 16 !=0) {
5648 ArgOffset += PtrByteSize;
5649 if (GPR_idx != NumGPRs)
5652 // We could elide this store in the case where the object fits
5653 // entirely in R registers. Maybe later.
5654 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5655 DAG.getConstant(ArgOffset, dl, PtrVT));
5656 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5657 MachinePointerInfo(), false, false, 0);
5658 MemOpChains.push_back(Store);
5659 if (VR_idx != NumVRs) {
5660 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5661 MachinePointerInfo(),
5662 false, false, false, 0);
5663 MemOpChains.push_back(Load.getValue(1));
5664 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5667 for (unsigned i=0; i<16; i+=PtrByteSize) {
5668 if (GPR_idx == NumGPRs)
5670 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5671 DAG.getConstant(i, dl, PtrVT));
5672 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5673 false, false, false, 0);
5674 MemOpChains.push_back(Load.getValue(1));
5675 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5680 // Non-varargs Altivec params generally go in registers, but have
5681 // stack space allocated at the end.
5682 if (VR_idx != NumVRs) {
5683 // Doesn't have GPR space allocated.
5684 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5685 } else if (nAltivecParamsAtEnd==0) {
5686 // We are emitting Altivec params in order.
5687 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5688 isPPC64, isTailCall, true, MemOpChains,
5689 TailCallArguments, dl);
5695 // If all Altivec parameters fit in registers, as they usually do,
5696 // they get stack space following the non-Altivec parameters. We
5697 // don't track this here because nobody below needs it.
5698 // If there are more Altivec parameters than fit in registers emit
5700 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5702 // Offset is aligned; skip 1st 12 params which go in V registers.
5703 ArgOffset = ((ArgOffset+15)/16)*16;
5705 for (unsigned i = 0; i != NumOps; ++i) {
5706 SDValue Arg = OutVals[i];
5707 EVT ArgType = Outs[i].VT;
5708 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5709 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5712 // We are emitting Altivec params in order.
5713 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5714 isPPC64, isTailCall, true, MemOpChains,
5715 TailCallArguments, dl);
5722 if (!MemOpChains.empty())
5723 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5725 // On Darwin, R12 must contain the address of an indirect callee. This does
5726 // not mean the MTCTR instruction must use R12; it's easier to model this as
5727 // an extra parameter, so do that.
5729 !isFunctionGlobalAddress(Callee) &&
5730 !isa<ExternalSymbolSDNode>(Callee) &&
5731 !isBLACompatibleAddress(Callee, DAG))
5732 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5733 PPC::R12), Callee));
5735 // Build a sequence of copy-to-reg nodes chained together with token chain
5736 // and flag operands which copy the outgoing args into the appropriate regs.
5738 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5739 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5740 RegsToPass[i].second, InFlag);
5741 InFlag = Chain.getValue(1);
5745 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5746 FPOp, true, TailCallArguments);
5748 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
5749 /* unused except on PPC64 ELFv1 */ false, DAG,
5750 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5751 NumBytes, Ins, InVals, CS);
5755 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5756 MachineFunction &MF, bool isVarArg,
5757 const SmallVectorImpl<ISD::OutputArg> &Outs,
5758 LLVMContext &Context) const {
5759 SmallVector<CCValAssign, 16> RVLocs;
5760 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5761 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5765 PPCTargetLowering::LowerReturn(SDValue Chain,
5766 CallingConv::ID CallConv, bool isVarArg,
5767 const SmallVectorImpl<ISD::OutputArg> &Outs,
5768 const SmallVectorImpl<SDValue> &OutVals,
5769 SDLoc dl, SelectionDAG &DAG) const {
5771 SmallVector<CCValAssign, 16> RVLocs;
5772 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5774 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5777 SmallVector<SDValue, 4> RetOps(1, Chain);
5779 // Copy the result values into the output registers.
5780 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5781 CCValAssign &VA = RVLocs[i];
5782 assert(VA.isRegLoc() && "Can only return in registers!");
5784 SDValue Arg = OutVals[i];
5786 switch (VA.getLocInfo()) {
5787 default: llvm_unreachable("Unknown loc info!");
5788 case CCValAssign::Full: break;
5789 case CCValAssign::AExt:
5790 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5792 case CCValAssign::ZExt:
5793 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5795 case CCValAssign::SExt:
5796 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5800 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5801 Flag = Chain.getValue(1);
5802 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5805 RetOps[0] = Chain; // Update chain.
5807 // Add the flag if we have it.
5809 RetOps.push_back(Flag);
5811 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5814 SDValue PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(
5815 SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const {
5818 // Get the corect type for integers.
5819 EVT IntVT = Op.getValueType();
5822 SDValue Chain = Op.getOperand(0);
5823 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5824 // Build a DYNAREAOFFSET node.
5825 SDValue Ops[2] = {Chain, FPSIdx};
5826 SDVTList VTs = DAG.getVTList(IntVT);
5827 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
5830 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5831 const PPCSubtarget &Subtarget) const {
5832 // When we pop the dynamic allocation we need to restore the SP link.
5835 // Get the corect type for pointers.
5836 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5838 // Construct the stack pointer operand.
5839 bool isPPC64 = Subtarget.isPPC64();
5840 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5841 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5843 // Get the operands for the STACKRESTORE.
5844 SDValue Chain = Op.getOperand(0);
5845 SDValue SaveSP = Op.getOperand(1);
5847 // Load the old link SP.
5848 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5849 MachinePointerInfo(),
5850 false, false, false, 0);
5852 // Restore the stack pointer.
5853 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5855 // Store the old link SP.
5856 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5860 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
5861 MachineFunction &MF = DAG.getMachineFunction();
5862 bool isPPC64 = Subtarget.isPPC64();
5863 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
5865 // Get current frame pointer save index. The users of this index will be
5866 // primarily DYNALLOC instructions.
5867 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5868 int RASI = FI->getReturnAddrSaveIndex();
5870 // If the frame pointer save index hasn't been defined yet.
5872 // Find out what the fix offset of the frame pointer save area.
5873 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5874 // Allocate the frame index for frame pointer save area.
5875 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5877 FI->setReturnAddrSaveIndex(RASI);
5879 return DAG.getFrameIndex(RASI, PtrVT);
5883 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5884 MachineFunction &MF = DAG.getMachineFunction();
5885 bool isPPC64 = Subtarget.isPPC64();
5886 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
5888 // Get current frame pointer save index. The users of this index will be
5889 // primarily DYNALLOC instructions.
5890 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5891 int FPSI = FI->getFramePointerSaveIndex();
5893 // If the frame pointer save index hasn't been defined yet.
5895 // Find out what the fix offset of the frame pointer save area.
5896 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5897 // Allocate the frame index for frame pointer save area.
5898 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5900 FI->setFramePointerSaveIndex(FPSI);
5902 return DAG.getFrameIndex(FPSI, PtrVT);
5905 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5907 const PPCSubtarget &Subtarget) const {
5909 SDValue Chain = Op.getOperand(0);
5910 SDValue Size = Op.getOperand(1);
5913 // Get the corect type for pointers.
5914 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5916 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5917 DAG.getConstant(0, dl, PtrVT), Size);
5918 // Construct a node for the frame pointer save index.
5919 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5920 // Build a DYNALLOC node.
5921 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5922 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5923 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5926 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5927 SelectionDAG &DAG) const {
5929 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5930 DAG.getVTList(MVT::i32, MVT::Other),
5931 Op.getOperand(0), Op.getOperand(1));
5934 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5935 SelectionDAG &DAG) const {
5937 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5938 Op.getOperand(0), Op.getOperand(1));
5941 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5942 if (Op.getValueType().isVector())
5943 return LowerVectorLoad(Op, DAG);
5945 assert(Op.getValueType() == MVT::i1 &&
5946 "Custom lowering only for i1 loads");
5948 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5951 LoadSDNode *LD = cast<LoadSDNode>(Op);
5953 SDValue Chain = LD->getChain();
5954 SDValue BasePtr = LD->getBasePtr();
5955 MachineMemOperand *MMO = LD->getMemOperand();
5958 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
5959 BasePtr, MVT::i8, MMO);
5960 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5962 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5963 return DAG.getMergeValues(Ops, dl);
5966 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5967 if (Op.getOperand(1).getValueType().isVector())
5968 return LowerVectorStore(Op, DAG);
5970 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5971 "Custom lowering only for i1 stores");
5973 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5976 StoreSDNode *ST = cast<StoreSDNode>(Op);
5978 SDValue Chain = ST->getChain();
5979 SDValue BasePtr = ST->getBasePtr();
5980 SDValue Value = ST->getValue();
5981 MachineMemOperand *MMO = ST->getMemOperand();
5983 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
5985 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5988 // FIXME: Remove this once the ANDI glue bug is fixed:
5989 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5990 assert(Op.getValueType() == MVT::i1 &&
5991 "Custom lowering only for i1 results");
5994 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5998 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6000 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6001 // Not FP? Not a fsel.
6002 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6003 !Op.getOperand(2).getValueType().isFloatingPoint())
6006 // We might be able to do better than this under some circumstances, but in
6007 // general, fsel-based lowering of select is a finite-math-only optimization.
6008 // For more information, see section F.3 of the 2.06 ISA specification.
6009 if (!DAG.getTarget().Options.NoInfsFPMath ||
6010 !DAG.getTarget().Options.NoNaNsFPMath)
6012 // TODO: Propagate flags from the select rather than global settings.
6014 Flags.setNoInfs(true);
6015 Flags.setNoNaNs(true);
6017 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6019 EVT ResVT = Op.getValueType();
6020 EVT CmpVT = Op.getOperand(0).getValueType();
6021 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6022 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
6025 // If the RHS of the comparison is a 0.0, we don't need to do the
6026 // subtraction at all.
6028 if (isFloatingPointZero(RHS))
6030 default: break; // SETUO etc aren't handled by fsel.
6034 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6035 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6036 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6037 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6038 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6039 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6040 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6043 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6046 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6047 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6048 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6051 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6054 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6055 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6056 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6057 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6062 default: break; // SETUO etc aren't handled by fsel.
6066 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6067 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6068 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6069 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6070 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6071 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6072 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6073 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6076 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6077 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6078 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6079 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6082 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6083 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6084 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6085 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6088 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6089 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6090 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6091 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6094 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6095 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6096 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6097 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6102 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6105 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6106 SDValue Src = Op.getOperand(0);
6107 if (Src.getValueType() == MVT::f32)
6108 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6111 switch (Op.getSimpleValueType().SimpleTy) {
6112 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6115 Op.getOpcode() == ISD::FP_TO_SINT
6117 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6121 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6122 "i64 FP_TO_UINT is supported only with FPCVT");
6123 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6129 // Convert the FP value to an int value through memory.
6130 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6131 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6132 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6133 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6134 MachinePointerInfo MPI =
6135 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6137 // Emit a store to the stack slot.
6140 MachineFunction &MF = DAG.getMachineFunction();
6141 MachineMemOperand *MMO =
6142 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6143 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6144 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6145 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6147 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
6148 MPI, false, false, 0);
6150 // Result is a load from the stack slot. If loading 4 bytes, make sure to
6152 if (Op.getValueType() == MVT::i32 && !i32Stack) {
6153 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6154 DAG.getConstant(4, dl, FIPtr.getValueType()));
6155 MPI = MPI.getWithOffset(4);
6163 /// \brief Custom lowers floating point to integer conversions to use
6164 /// the direct move instructions available in ISA 2.07 to avoid the
6165 /// need for load/store combinations.
6166 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6169 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6170 SDValue Src = Op.getOperand(0);
6172 if (Src.getValueType() == MVT::f32)
6173 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6176 switch (Op.getSimpleValueType().SimpleTy) {
6177 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6180 Op.getOpcode() == ISD::FP_TO_SINT
6182 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6184 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6187 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6188 "i64 FP_TO_UINT is supported only with FPCVT");
6189 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6192 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6198 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6200 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6201 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6204 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6206 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6207 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6211 // We're trying to insert a regular store, S, and then a load, L. If the
6212 // incoming value, O, is a load, we might just be able to have our load use the
6213 // address used by O. However, we don't know if anything else will store to
6214 // that address before we can load from it. To prevent this situation, we need
6215 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6216 // the same chain operand as O, we create a token factor from the chain results
6217 // of O and L, and we replace all uses of O's chain result with that token
6218 // factor (see spliceIntoChain below for this last part).
6219 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6222 ISD::LoadExtType ET) const {
6224 if (ET == ISD::NON_EXTLOAD &&
6225 (Op.getOpcode() == ISD::FP_TO_UINT ||
6226 Op.getOpcode() == ISD::FP_TO_SINT) &&
6227 isOperationLegalOrCustom(Op.getOpcode(),
6228 Op.getOperand(0).getValueType())) {
6230 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6234 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6235 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6236 LD->isNonTemporal())
6238 if (LD->getMemoryVT() != MemVT)
6241 RLI.Ptr = LD->getBasePtr();
6242 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
6243 assert(LD->getAddressingMode() == ISD::PRE_INC &&
6244 "Non-pre-inc AM on PPC?");
6245 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6249 RLI.Chain = LD->getChain();
6250 RLI.MPI = LD->getPointerInfo();
6251 RLI.IsInvariant = LD->isInvariant();
6252 RLI.Alignment = LD->getAlignment();
6253 RLI.AAInfo = LD->getAAInfo();
6254 RLI.Ranges = LD->getRanges();
6256 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6260 // Given the head of the old chain, ResChain, insert a token factor containing
6261 // it and NewResChain, and make users of ResChain now be users of that token
6263 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6264 SDValue NewResChain,
6265 SelectionDAG &DAG) const {
6269 SDLoc dl(NewResChain);
6271 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6272 NewResChain, DAG.getUNDEF(MVT::Other));
6273 assert(TF.getNode() != NewResChain.getNode() &&
6274 "A new TF really is required here");
6276 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6277 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6280 /// \brief Custom lowers integer to floating point conversions to use
6281 /// the direct move instructions available in ISA 2.07 to avoid the
6282 /// need for load/store combinations.
6283 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6286 assert((Op.getValueType() == MVT::f32 ||
6287 Op.getValueType() == MVT::f64) &&
6288 "Invalid floating point type as target of conversion");
6289 assert(Subtarget.hasFPCVT() &&
6290 "Int to FP conversions with direct moves require FPCVT");
6292 SDValue Src = Op.getOperand(0);
6293 bool SinglePrec = Op.getValueType() == MVT::f32;
6294 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6295 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6296 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6297 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6300 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6302 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6305 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6306 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6312 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6313 SelectionDAG &DAG) const {
6316 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6317 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6320 SDValue Value = Op.getOperand(0);
6321 // The values are now known to be -1 (false) or 1 (true). To convert this
6322 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6323 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6324 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6326 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
6327 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, FPHalfs, FPHalfs,
6330 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6332 if (Op.getValueType() != MVT::v4f64)
6333 Value = DAG.getNode(ISD::FP_ROUND, dl,
6334 Op.getValueType(), Value,
6335 DAG.getIntPtrConstant(1, dl));
6339 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6340 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6343 if (Op.getOperand(0).getValueType() == MVT::i1)
6344 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6345 DAG.getConstantFP(1.0, dl, Op.getValueType()),
6346 DAG.getConstantFP(0.0, dl, Op.getValueType()));
6348 // If we have direct moves, we can do all the conversion, skip the store/load
6349 // however, without FPCVT we can't do most conversions.
6350 if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6351 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6353 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6354 "UINT_TO_FP is supported only with FPCVT");
6356 // If we have FCFIDS, then use it when converting to single-precision.
6357 // Otherwise, convert to double-precision and then round.
6358 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6359 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6361 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6363 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6367 if (Op.getOperand(0).getValueType() == MVT::i64) {
6368 SDValue SINT = Op.getOperand(0);
6369 // When converting to single-precision, we actually need to convert
6370 // to double-precision first and then round to single-precision.
6371 // To avoid double-rounding effects during that operation, we have
6372 // to prepare the input operand. Bits that might be truncated when
6373 // converting to double-precision are replaced by a bit that won't
6374 // be lost at this stage, but is below the single-precision rounding
6377 // However, if -enable-unsafe-fp-math is in effect, accept double
6378 // rounding to avoid the extra overhead.
6379 if (Op.getValueType() == MVT::f32 &&
6380 !Subtarget.hasFPCVT() &&
6381 !DAG.getTarget().Options.UnsafeFPMath) {
6383 // Twiddle input to make sure the low 11 bits are zero. (If this
6384 // is the case, we are guaranteed the value will fit into the 53 bit
6385 // mantissa of an IEEE double-precision value without rounding.)
6386 // If any of those low 11 bits were not zero originally, make sure
6387 // bit 12 (value 2048) is set instead, so that the final rounding
6388 // to single-precision gets the correct result.
6389 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6390 SINT, DAG.getConstant(2047, dl, MVT::i64));
6391 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6392 Round, DAG.getConstant(2047, dl, MVT::i64));
6393 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6394 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6395 Round, DAG.getConstant(-2048, dl, MVT::i64));
6397 // However, we cannot use that value unconditionally: if the magnitude
6398 // of the input value is small, the bit-twiddling we did above might
6399 // end up visibly changing the output. Fortunately, in that case, we
6400 // don't need to twiddle bits since the original input will convert
6401 // exactly to double-precision floating-point already. Therefore,
6402 // construct a conditional to use the original value if the top 11
6403 // bits are all sign-bit copies, and use the rounded value computed
6405 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6406 SINT, DAG.getConstant(53, dl, MVT::i32));
6407 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6408 Cond, DAG.getConstant(1, dl, MVT::i64));
6409 Cond = DAG.getSetCC(dl, MVT::i32,
6410 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6412 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6418 MachineFunction &MF = DAG.getMachineFunction();
6419 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6420 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6421 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6423 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6424 } else if (Subtarget.hasLFIWAX() &&
6425 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6426 MachineMemOperand *MMO =
6427 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6428 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6429 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6430 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6431 DAG.getVTList(MVT::f64, MVT::Other),
6432 Ops, MVT::i32, MMO);
6433 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6434 } else if (Subtarget.hasFPCVT() &&
6435 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6436 MachineMemOperand *MMO =
6437 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6438 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6439 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6440 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6441 DAG.getVTList(MVT::f64, MVT::Other),
6442 Ops, MVT::i32, MMO);
6443 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6444 } else if (((Subtarget.hasLFIWAX() &&
6445 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6446 (Subtarget.hasFPCVT() &&
6447 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6448 SINT.getOperand(0).getValueType() == MVT::i32) {
6449 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6450 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6452 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6453 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6455 SDValue Store = DAG.getStore(
6456 DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6457 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6460 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6461 "Expected an i32 store");
6466 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6469 MachineMemOperand *MMO =
6470 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6471 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6472 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6473 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6474 PPCISD::LFIWZX : PPCISD::LFIWAX,
6475 dl, DAG.getVTList(MVT::f64, MVT::Other),
6476 Ops, MVT::i32, MMO);
6478 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6480 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6482 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6483 FP = DAG.getNode(ISD::FP_ROUND, dl,
6484 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6488 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6489 "Unhandled INT_TO_FP type in custom expander!");
6490 // Since we only generate this in 64-bit mode, we can take advantage of
6491 // 64-bit registers. In particular, sign extend the input value into the
6492 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6493 // then lfd it and fcfid it.
6494 MachineFunction &MF = DAG.getMachineFunction();
6495 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6496 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6499 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6502 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6504 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6505 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6507 SDValue Store = DAG.getStore(
6508 DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6509 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6512 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6513 "Expected an i32 store");
6518 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6522 MachineMemOperand *MMO =
6523 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6524 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6525 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6526 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6527 PPCISD::LFIWZX : PPCISD::LFIWAX,
6528 dl, DAG.getVTList(MVT::f64, MVT::Other),
6529 Ops, MVT::i32, MMO);
6531 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6533 assert(Subtarget.isPPC64() &&
6534 "i32->FP without LFIWAX supported only on PPC64");
6536 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6537 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6539 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6542 // STD the extended value into the stack slot.
6543 SDValue Store = DAG.getStore(
6544 DAG.getEntryNode(), dl, Ext64, FIdx,
6545 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6548 // Load the value as a double.
6550 MVT::f64, dl, Store, FIdx,
6551 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6552 false, false, false, 0);
6555 // FCFID it and return it.
6556 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6557 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6558 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6559 DAG.getIntPtrConstant(0, dl));
6563 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6564 SelectionDAG &DAG) const {
6567 The rounding mode is in bits 30:31 of FPSR, and has the following
6574 FLT_ROUNDS, on the other hand, expects the following:
6581 To perform the conversion, we do:
6582 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6585 MachineFunction &MF = DAG.getMachineFunction();
6586 EVT VT = Op.getValueType();
6587 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6589 // Save FP Control Word to register
6591 MVT::f64, // return register
6592 MVT::Glue // unused in this context
6594 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6596 // Save FP register to stack slot
6597 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6598 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6599 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6600 StackSlot, MachinePointerInfo(), false, false,0);
6602 // Load FP Control Word from low 32 bits of stack slot.
6603 SDValue Four = DAG.getConstant(4, dl, PtrVT);
6604 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6605 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6606 false, false, false, 0);
6608 // Transform as necessary
6610 DAG.getNode(ISD::AND, dl, MVT::i32,
6611 CWD, DAG.getConstant(3, dl, MVT::i32));
6613 DAG.getNode(ISD::SRL, dl, MVT::i32,
6614 DAG.getNode(ISD::AND, dl, MVT::i32,
6615 DAG.getNode(ISD::XOR, dl, MVT::i32,
6616 CWD, DAG.getConstant(3, dl, MVT::i32)),
6617 DAG.getConstant(3, dl, MVT::i32)),
6618 DAG.getConstant(1, dl, MVT::i32));
6621 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6623 return DAG.getNode((VT.getSizeInBits() < 16 ?
6624 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6627 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6628 EVT VT = Op.getValueType();
6629 unsigned BitWidth = VT.getSizeInBits();
6631 assert(Op.getNumOperands() == 3 &&
6632 VT == Op.getOperand(1).getValueType() &&
6635 // Expand into a bunch of logical ops. Note that these ops
6636 // depend on the PPC behavior for oversized shift amounts.
6637 SDValue Lo = Op.getOperand(0);
6638 SDValue Hi = Op.getOperand(1);
6639 SDValue Amt = Op.getOperand(2);
6640 EVT AmtVT = Amt.getValueType();
6642 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6643 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6644 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6645 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6646 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6647 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6648 DAG.getConstant(-BitWidth, dl, AmtVT));
6649 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6650 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6651 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6652 SDValue OutOps[] = { OutLo, OutHi };
6653 return DAG.getMergeValues(OutOps, dl);
6656 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6657 EVT VT = Op.getValueType();
6659 unsigned BitWidth = VT.getSizeInBits();
6660 assert(Op.getNumOperands() == 3 &&
6661 VT == Op.getOperand(1).getValueType() &&
6664 // Expand into a bunch of logical ops. Note that these ops
6665 // depend on the PPC behavior for oversized shift amounts.
6666 SDValue Lo = Op.getOperand(0);
6667 SDValue Hi = Op.getOperand(1);
6668 SDValue Amt = Op.getOperand(2);
6669 EVT AmtVT = Amt.getValueType();
6671 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6672 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6673 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6674 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6675 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6676 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6677 DAG.getConstant(-BitWidth, dl, AmtVT));
6678 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6679 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6680 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6681 SDValue OutOps[] = { OutLo, OutHi };
6682 return DAG.getMergeValues(OutOps, dl);
6685 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6687 EVT VT = Op.getValueType();
6688 unsigned BitWidth = VT.getSizeInBits();
6689 assert(Op.getNumOperands() == 3 &&
6690 VT == Op.getOperand(1).getValueType() &&
6693 // Expand into a bunch of logical ops, followed by a select_cc.
6694 SDValue Lo = Op.getOperand(0);
6695 SDValue Hi = Op.getOperand(1);
6696 SDValue Amt = Op.getOperand(2);
6697 EVT AmtVT = Amt.getValueType();
6699 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6700 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6701 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6702 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6703 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6704 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6705 DAG.getConstant(-BitWidth, dl, AmtVT));
6706 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6707 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6708 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6709 Tmp4, Tmp6, ISD::SETLE);
6710 SDValue OutOps[] = { OutLo, OutHi };
6711 return DAG.getMergeValues(OutOps, dl);
6714 //===----------------------------------------------------------------------===//
6715 // Vector related lowering.
6718 /// BuildSplatI - Build a canonical splati of Val with an element size of
6719 /// SplatSize. Cast the result to VT.
6720 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6721 SelectionDAG &DAG, SDLoc dl) {
6722 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6724 static const MVT VTys[] = { // canonical VT to use for each size.
6725 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6728 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6730 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6734 EVT CanonicalVT = VTys[SplatSize-1];
6736 // Build a canonical splat for this value.
6737 SDValue Elt = DAG.getConstant(Val, dl, MVT::i32);
6738 SmallVector<SDValue, 8> Ops;
6739 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6740 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6741 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6744 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6745 /// specified intrinsic ID.
6746 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6747 SelectionDAG &DAG, SDLoc dl,
6748 EVT DestVT = MVT::Other) {
6749 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6750 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6751 DAG.getConstant(IID, dl, MVT::i32), Op);
6754 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6755 /// specified intrinsic ID.
6756 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6757 SelectionDAG &DAG, SDLoc dl,
6758 EVT DestVT = MVT::Other) {
6759 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6760 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6761 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6764 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6765 /// specified intrinsic ID.
6766 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6767 SDValue Op2, SelectionDAG &DAG,
6768 SDLoc dl, EVT DestVT = MVT::Other) {
6769 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6770 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6771 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6774 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6775 /// amount. The result has the specified value type.
6776 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6777 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6778 // Force LHS/RHS to be the right type.
6779 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6780 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6783 for (unsigned i = 0; i != 16; ++i)
6785 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6786 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6789 // If this is a case we can't handle, return null and let the default
6790 // expansion code take care of it. If we CAN select this case, and if it
6791 // selects to a single instruction, return Op. Otherwise, if we can codegen
6792 // this case more efficiently than a constant pool load, lower it to the
6793 // sequence of ops that should be used.
6794 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6795 SelectionDAG &DAG) const {
6797 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6798 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6800 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6801 // We first build an i32 vector, load it into a QPX register,
6802 // then convert it to a floating-point vector and compare it
6803 // to a zero vector to get the boolean result.
6804 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6805 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6806 MachinePointerInfo PtrInfo =
6807 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6808 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6809 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6811 assert(BVN->getNumOperands() == 4 &&
6812 "BUILD_VECTOR for v4i1 does not have 4 operands");
6814 bool IsConst = true;
6815 for (unsigned i = 0; i < 4; ++i) {
6816 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6817 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6825 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6827 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6829 SmallVector<Constant*, 4> CV(4, NegOne);
6830 for (unsigned i = 0; i < 4; ++i) {
6831 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6832 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6833 else if (isNullConstant(BVN->getOperand(i)))
6839 Constant *CP = ConstantVector::get(CV);
6840 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
6841 16 /* alignment */);
6843 SmallVector<SDValue, 2> Ops;
6844 Ops.push_back(DAG.getEntryNode());
6845 Ops.push_back(CPIdx);
6847 SmallVector<EVT, 2> ValueVTs;
6848 ValueVTs.push_back(MVT::v4i1);
6849 ValueVTs.push_back(MVT::Other); // chain
6850 SDVTList VTs = DAG.getVTList(ValueVTs);
6852 return DAG.getMemIntrinsicNode(
6853 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
6854 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
6857 SmallVector<SDValue, 4> Stores;
6858 for (unsigned i = 0; i < 4; ++i) {
6859 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6861 unsigned Offset = 4*i;
6862 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
6863 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6865 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6866 if (StoreSize > 4) {
6867 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6868 BVN->getOperand(i), Idx,
6869 PtrInfo.getWithOffset(Offset),
6870 MVT::i32, false, false, 0));
6872 SDValue StoreValue = BVN->getOperand(i);
6874 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6876 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6878 PtrInfo.getWithOffset(Offset),
6884 if (!Stores.empty())
6885 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6887 StoreChain = DAG.getEntryNode();
6889 // Now load from v4i32 into the QPX register; this will extend it to
6890 // v4i64 but not yet convert it to a floating point. Nevertheless, this
6891 // is typed as v4f64 because the QPX register integer states are not
6892 // explicitly represented.
6894 SmallVector<SDValue, 2> Ops;
6895 Ops.push_back(StoreChain);
6896 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
6897 Ops.push_back(FIdx);
6899 SmallVector<EVT, 2> ValueVTs;
6900 ValueVTs.push_back(MVT::v4f64);
6901 ValueVTs.push_back(MVT::Other); // chain
6902 SDVTList VTs = DAG.getVTList(ValueVTs);
6904 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6905 dl, VTs, Ops, MVT::v4i32, PtrInfo);
6906 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6907 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
6910 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64);
6911 FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6912 FPZeros, FPZeros, FPZeros, FPZeros);
6914 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6917 // All other QPX vectors are handled by generic code.
6918 if (Subtarget.hasQPX())
6921 // Check if this is a splat of a constant value.
6922 APInt APSplatBits, APSplatUndef;
6923 unsigned SplatBitSize;
6925 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6926 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6930 unsigned SplatBits = APSplatBits.getZExtValue();
6931 unsigned SplatUndef = APSplatUndef.getZExtValue();
6932 unsigned SplatSize = SplatBitSize / 8;
6934 // First, handle single instruction cases.
6937 if (SplatBits == 0) {
6938 // Canonicalize all zero vectors to be v4i32.
6939 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6940 SDValue Z = DAG.getConstant(0, dl, MVT::i32);
6941 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6942 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6947 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6948 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6950 if (SextVal >= -16 && SextVal <= 15)
6951 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6953 // Two instruction sequences.
6955 // If this value is in the range [-32,30] and is even, use:
6956 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6957 // If this value is in the range [17,31] and is odd, use:
6958 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6959 // If this value is in the range [-31,-17] and is odd, use:
6960 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6961 // Note the last two are three-instruction sequences.
6962 if (SextVal >= -32 && SextVal <= 31) {
6963 // To avoid having these optimizations undone by constant folding,
6964 // we convert to a pseudo that will be expanded later into one of
6966 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
6967 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6968 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6969 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
6970 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6971 if (VT == Op.getValueType())
6974 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6977 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6978 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6980 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6981 // Make -1 and vspltisw -1:
6982 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6984 // Make the VSLW intrinsic, computing 0x8000_0000.
6985 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6988 // xor by OnesV to invert it.
6989 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6990 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6993 // Check to see if this is a wide variety of vsplti*, binop self cases.
6994 static const signed char SplatCsts[] = {
6995 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6996 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6999 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7000 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7001 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
7002 int i = SplatCsts[idx];
7004 // Figure out what shift amount will be used by altivec if shifted by i in
7006 unsigned TypeShiftAmt = i & (SplatBitSize-1);
7008 // vsplti + shl self.
7009 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7010 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7011 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7012 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7013 Intrinsic::ppc_altivec_vslw
7015 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7016 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7019 // vsplti + srl self.
7020 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7021 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7022 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7023 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7024 Intrinsic::ppc_altivec_vsrw
7026 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7027 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7030 // vsplti + sra self.
7031 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7032 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7033 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7034 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7035 Intrinsic::ppc_altivec_vsraw
7037 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7038 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7041 // vsplti + rol self.
7042 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7043 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7044 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7045 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7046 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7047 Intrinsic::ppc_altivec_vrlw
7049 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7050 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7053 // t = vsplti c, result = vsldoi t, t, 1
7054 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7055 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7056 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7057 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7059 // t = vsplti c, result = vsldoi t, t, 2
7060 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7061 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7062 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7063 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7065 // t = vsplti c, result = vsldoi t, t, 3
7066 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7067 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7068 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7069 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7076 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7077 /// the specified operations to build the shuffle.
7078 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7079 SDValue RHS, SelectionDAG &DAG,
7081 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7082 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7083 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7086 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7098 if (OpNum == OP_COPY) {
7099 if (LHSID == (1*9+2)*9+3) return LHS;
7100 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7104 SDValue OpLHS, OpRHS;
7105 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7106 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7110 default: llvm_unreachable("Unknown i32 permute!");
7112 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
7113 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7114 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
7115 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7118 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7119 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7120 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7121 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7124 for (unsigned i = 0; i != 16; ++i)
7125 ShufIdxs[i] = (i&3)+0;
7128 for (unsigned i = 0; i != 16; ++i)
7129 ShufIdxs[i] = (i&3)+4;
7132 for (unsigned i = 0; i != 16; ++i)
7133 ShufIdxs[i] = (i&3)+8;
7136 for (unsigned i = 0; i != 16; ++i)
7137 ShufIdxs[i] = (i&3)+12;
7140 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7142 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7144 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7146 EVT VT = OpLHS.getValueType();
7147 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7148 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7149 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7150 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7153 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
7154 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
7155 /// return the code it can be lowered into. Worst case, it can always be
7156 /// lowered into a vperm.
7157 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7158 SelectionDAG &DAG) const {
7160 SDValue V1 = Op.getOperand(0);
7161 SDValue V2 = Op.getOperand(1);
7162 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7163 EVT VT = Op.getValueType();
7164 bool isLittleEndian = Subtarget.isLittleEndian();
7166 if (Subtarget.hasQPX()) {
7167 if (VT.getVectorNumElements() != 4)
7170 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7172 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7173 if (AlignIdx != -1) {
7174 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7175 DAG.getConstant(AlignIdx, dl, MVT::i32));
7176 } else if (SVOp->isSplat()) {
7177 int SplatIdx = SVOp->getSplatIndex();
7178 if (SplatIdx >= 4) {
7183 // FIXME: If SplatIdx == 0 and the input came from a load, then there is
7186 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7187 DAG.getConstant(SplatIdx, dl, MVT::i32));
7190 // Lower this into a qvgpci/qvfperm pair.
7192 // Compute the qvgpci literal
7194 for (unsigned i = 0; i < 4; ++i) {
7195 int m = SVOp->getMaskElt(i);
7196 unsigned mm = m >= 0 ? (unsigned) m : i;
7197 idx |= mm << (3-i)*3;
7200 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7201 DAG.getConstant(idx, dl, MVT::i32));
7202 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7205 // Cases that are handled by instructions that take permute immediates
7206 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7207 // selected by the instruction selector.
7208 if (V2.getOpcode() == ISD::UNDEF) {
7209 if (PPC::isSplatShuffleMask(SVOp, 1) ||
7210 PPC::isSplatShuffleMask(SVOp, 2) ||
7211 PPC::isSplatShuffleMask(SVOp, 4) ||
7212 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7213 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7214 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7215 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7216 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7217 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7218 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7219 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7220 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7221 (Subtarget.hasP8Altivec() && (
7222 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7223 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7224 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7229 // Altivec has a variety of "shuffle immediates" that take two vector inputs
7230 // and produce a fixed permutation. If any of these match, do not lower to
7232 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7233 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7234 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7235 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7236 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7237 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7238 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7239 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7240 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7241 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7242 (Subtarget.hasP8Altivec() && (
7243 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7244 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7245 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7248 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
7249 // perfect shuffle table to emit an optimal matching sequence.
7250 ArrayRef<int> PermMask = SVOp->getMask();
7252 unsigned PFIndexes[4];
7253 bool isFourElementShuffle = true;
7254 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7255 unsigned EltNo = 8; // Start out undef.
7256 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
7257 if (PermMask[i*4+j] < 0)
7258 continue; // Undef, ignore it.
7260 unsigned ByteSource = PermMask[i*4+j];
7261 if ((ByteSource & 3) != j) {
7262 isFourElementShuffle = false;
7267 EltNo = ByteSource/4;
7268 } else if (EltNo != ByteSource/4) {
7269 isFourElementShuffle = false;
7273 PFIndexes[i] = EltNo;
7276 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7277 // perfect shuffle vector to determine if it is cost effective to do this as
7278 // discrete instructions, or whether we should use a vperm.
7279 // For now, we skip this for little endian until such time as we have a
7280 // little-endian perfect shuffle table.
7281 if (isFourElementShuffle && !isLittleEndian) {
7282 // Compute the index in the perfect shuffle table.
7283 unsigned PFTableIndex =
7284 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7286 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7287 unsigned Cost = (PFEntry >> 30);
7289 // Determining when to avoid vperm is tricky. Many things affect the cost
7290 // of vperm, particularly how many times the perm mask needs to be computed.
7291 // For example, if the perm mask can be hoisted out of a loop or is already
7292 // used (perhaps because there are multiple permutes with the same shuffle
7293 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
7294 // the loop requires an extra register.
7296 // As a compromise, we only emit discrete instructions if the shuffle can be
7297 // generated in 3 or fewer operations. When we have loop information
7298 // available, if this block is within a loop, we should avoid using vperm
7299 // for 3-operation perms and use a constant pool load instead.
7301 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7304 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7305 // vector that will get spilled to the constant pool.
7306 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7308 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7309 // that it is in input element units, not in bytes. Convert now.
7311 // For little endian, the order of the input vectors is reversed, and
7312 // the permutation mask is complemented with respect to 31. This is
7313 // necessary to produce proper semantics with the big-endian-biased vperm
7315 EVT EltVT = V1.getValueType().getVectorElementType();
7316 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7318 SmallVector<SDValue, 16> ResultMask;
7319 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7320 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7322 for (unsigned j = 0; j != BytesPerElement; ++j)
7324 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7327 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7331 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7334 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7337 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7341 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7342 /// vector comparison. If it is, return true and fill in Opc/isDot with
7343 /// information about the intrinsic.
7344 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7345 bool &isDot, const PPCSubtarget &Subtarget) {
7346 unsigned IntrinsicID =
7347 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7350 switch (IntrinsicID) {
7351 default: return false;
7352 // Comparison predicates.
7353 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
7354 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7355 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
7356 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
7357 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7358 case Intrinsic::ppc_altivec_vcmpequd_p:
7359 if (Subtarget.hasP8Altivec()) {
7366 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7367 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7368 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7369 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7370 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7371 case Intrinsic::ppc_altivec_vcmpgtsd_p:
7372 if (Subtarget.hasP8Altivec()) {
7379 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7380 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7381 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7382 case Intrinsic::ppc_altivec_vcmpgtud_p:
7383 if (Subtarget.hasP8Altivec()) {
7390 // VSX predicate comparisons use the same infrastructure
7391 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7392 case Intrinsic::ppc_vsx_xvcmpgedp_p:
7393 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7394 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7395 case Intrinsic::ppc_vsx_xvcmpgesp_p:
7396 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7397 if (Subtarget.hasVSX()) {
7398 switch (IntrinsicID) {
7399 case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7400 case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7401 case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7402 case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7403 case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7404 case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7413 // Normal Comparisons.
7414 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
7415 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
7416 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
7417 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
7418 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
7419 case Intrinsic::ppc_altivec_vcmpequd:
7420 if (Subtarget.hasP8Altivec()) {
7427 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
7428 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
7429 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
7430 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
7431 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
7432 case Intrinsic::ppc_altivec_vcmpgtsd:
7433 if (Subtarget.hasP8Altivec()) {
7440 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
7441 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
7442 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
7443 case Intrinsic::ppc_altivec_vcmpgtud:
7444 if (Subtarget.hasP8Altivec()) {
7455 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7456 /// lower, do it, otherwise return null.
7457 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7458 SelectionDAG &DAG) const {
7459 // If this is a lowered altivec predicate compare, CompareOpc is set to the
7460 // opcode number of the comparison.
7464 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7465 return SDValue(); // Don't custom lower most intrinsics.
7467 // If this is a non-dot comparison, make the VCMP node and we are done.
7469 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7470 Op.getOperand(1), Op.getOperand(2),
7471 DAG.getConstant(CompareOpc, dl, MVT::i32));
7472 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7475 // Create the PPCISD altivec 'dot' comparison node.
7477 Op.getOperand(2), // LHS
7478 Op.getOperand(3), // RHS
7479 DAG.getConstant(CompareOpc, dl, MVT::i32)
7481 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7482 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7484 // Now that we have the comparison, emit a copy from the CR to a GPR.
7485 // This is flagged to the above dot comparison.
7486 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7487 DAG.getRegister(PPC::CR6, MVT::i32),
7488 CompNode.getValue(1));
7490 // Unpack the result based on how the target uses it.
7491 unsigned BitNo; // Bit # of CR6.
7492 bool InvertBit; // Invert result?
7493 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7494 default: // Can't happen, don't crash on invalid number though.
7495 case 0: // Return the value of the EQ bit of CR6.
7496 BitNo = 0; InvertBit = false;
7498 case 1: // Return the inverted value of the EQ bit of CR6.
7499 BitNo = 0; InvertBit = true;
7501 case 2: // Return the value of the LT bit of CR6.
7502 BitNo = 2; InvertBit = false;
7504 case 3: // Return the inverted value of the LT bit of CR6.
7505 BitNo = 2; InvertBit = true;
7509 // Shift the bit into the low position.
7510 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7511 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7513 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7514 DAG.getConstant(1, dl, MVT::i32));
7516 // If we are supposed to, toggle the bit.
7518 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7519 DAG.getConstant(1, dl, MVT::i32));
7523 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7524 SelectionDAG &DAG) const {
7526 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7527 // instructions), but for smaller types, we need to first extend up to v2i32
7528 // before doing going farther.
7529 if (Op.getValueType() == MVT::v2i64) {
7530 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7531 if (ExtVT != MVT::v2i32) {
7532 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7533 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7534 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7535 ExtVT.getVectorElementType(), 4)));
7536 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7537 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7538 DAG.getValueType(MVT::v2i32));
7547 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7548 SelectionDAG &DAG) const {
7550 // Create a stack slot that is 16-byte aligned.
7551 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7552 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7553 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7554 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7556 // Store the input value into Value#0 of the stack slot.
7557 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7558 Op.getOperand(0), FIdx, MachinePointerInfo(),
7561 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7562 false, false, false, 0);
7565 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7566 SelectionDAG &DAG) const {
7568 SDNode *N = Op.getNode();
7570 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7571 "Unknown extract_vector_elt type");
7573 SDValue Value = N->getOperand(0);
7575 // The first part of this is like the store lowering except that we don't
7576 // need to track the chain.
7578 // The values are now known to be -1 (false) or 1 (true). To convert this
7579 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7580 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7581 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7583 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7584 // understand how to form the extending load.
7585 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7586 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7587 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7589 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7591 // Now convert to an integer and store.
7592 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7593 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7596 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7597 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7598 MachinePointerInfo PtrInfo =
7599 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7600 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7601 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7603 SDValue StoreChain = DAG.getEntryNode();
7604 SmallVector<SDValue, 2> Ops;
7605 Ops.push_back(StoreChain);
7606 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7607 Ops.push_back(Value);
7608 Ops.push_back(FIdx);
7610 SmallVector<EVT, 2> ValueVTs;
7611 ValueVTs.push_back(MVT::Other); // chain
7612 SDVTList VTs = DAG.getVTList(ValueVTs);
7614 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7615 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7617 // Extract the value requested.
7618 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7619 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7620 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7622 SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7623 PtrInfo.getWithOffset(Offset),
7624 false, false, false, 0);
7626 if (!Subtarget.useCRBits())
7629 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7632 /// Lowering for QPX v4i1 loads
7633 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7634 SelectionDAG &DAG) const {
7636 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7637 SDValue LoadChain = LN->getChain();
7638 SDValue BasePtr = LN->getBasePtr();
7640 if (Op.getValueType() == MVT::v4f64 ||
7641 Op.getValueType() == MVT::v4f32) {
7642 EVT MemVT = LN->getMemoryVT();
7643 unsigned Alignment = LN->getAlignment();
7645 // If this load is properly aligned, then it is legal.
7646 if (Alignment >= MemVT.getStoreSize())
7649 EVT ScalarVT = Op.getValueType().getScalarType(),
7650 ScalarMemVT = MemVT.getScalarType();
7651 unsigned Stride = ScalarMemVT.getStoreSize();
7653 SmallVector<SDValue, 8> Vals, LoadChains;
7654 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7656 if (ScalarVT != ScalarMemVT)
7658 DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7660 LN->getPointerInfo().getWithOffset(Idx*Stride),
7661 ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7662 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7666 DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7667 LN->getPointerInfo().getWithOffset(Idx*Stride),
7668 LN->isVolatile(), LN->isNonTemporal(),
7669 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7672 if (Idx == 0 && LN->isIndexed()) {
7673 assert(LN->getAddressingMode() == ISD::PRE_INC &&
7674 "Unknown addressing mode on vector load");
7675 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7676 LN->getAddressingMode());
7679 Vals.push_back(Load);
7680 LoadChains.push_back(Load.getValue(1));
7682 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7683 DAG.getConstant(Stride, dl,
7684 BasePtr.getValueType()));
7687 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7688 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7689 Op.getValueType(), Vals);
7691 if (LN->isIndexed()) {
7692 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7693 return DAG.getMergeValues(RetOps, dl);
7696 SDValue RetOps[] = { Value, TF };
7697 return DAG.getMergeValues(RetOps, dl);
7700 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7701 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7703 // To lower v4i1 from a byte array, we load the byte elements of the
7704 // vector and then reuse the BUILD_VECTOR logic.
7706 SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7707 for (unsigned i = 0; i < 4; ++i) {
7708 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7709 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7711 VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7712 dl, MVT::i32, LoadChain, Idx,
7713 LN->getPointerInfo().getWithOffset(i),
7714 MVT::i8 /* memory type */,
7715 LN->isVolatile(), LN->isNonTemporal(),
7717 1 /* alignment */, LN->getAAInfo()));
7718 VectElmtChains.push_back(VectElmts[i].getValue(1));
7721 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7722 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7724 SDValue RVals[] = { Value, LoadChain };
7725 return DAG.getMergeValues(RVals, dl);
7728 /// Lowering for QPX v4i1 stores
7729 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7730 SelectionDAG &DAG) const {
7732 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7733 SDValue StoreChain = SN->getChain();
7734 SDValue BasePtr = SN->getBasePtr();
7735 SDValue Value = SN->getValue();
7737 if (Value.getValueType() == MVT::v4f64 ||
7738 Value.getValueType() == MVT::v4f32) {
7739 EVT MemVT = SN->getMemoryVT();
7740 unsigned Alignment = SN->getAlignment();
7742 // If this store is properly aligned, then it is legal.
7743 if (Alignment >= MemVT.getStoreSize())
7746 EVT ScalarVT = Value.getValueType().getScalarType(),
7747 ScalarMemVT = MemVT.getScalarType();
7748 unsigned Stride = ScalarMemVT.getStoreSize();
7750 SmallVector<SDValue, 8> Stores;
7751 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7752 SDValue Ex = DAG.getNode(
7753 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7754 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
7756 if (ScalarVT != ScalarMemVT)
7758 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7759 SN->getPointerInfo().getWithOffset(Idx*Stride),
7760 ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7761 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7764 DAG.getStore(StoreChain, dl, Ex, BasePtr,
7765 SN->getPointerInfo().getWithOffset(Idx*Stride),
7766 SN->isVolatile(), SN->isNonTemporal(),
7767 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7769 if (Idx == 0 && SN->isIndexed()) {
7770 assert(SN->getAddressingMode() == ISD::PRE_INC &&
7771 "Unknown addressing mode on vector store");
7772 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7773 SN->getAddressingMode());
7776 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7777 DAG.getConstant(Stride, dl,
7778 BasePtr.getValueType()));
7779 Stores.push_back(Store);
7782 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7784 if (SN->isIndexed()) {
7785 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7786 return DAG.getMergeValues(RetOps, dl);
7792 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7793 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7795 // The values are now known to be -1 (false) or 1 (true). To convert this
7796 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7797 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7798 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7800 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7801 // understand how to form the extending load.
7802 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7803 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7804 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7806 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7808 // Now convert to an integer and store.
7809 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7810 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7813 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7814 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7815 MachinePointerInfo PtrInfo =
7816 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7817 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7818 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7820 SmallVector<SDValue, 2> Ops;
7821 Ops.push_back(StoreChain);
7822 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7823 Ops.push_back(Value);
7824 Ops.push_back(FIdx);
7826 SmallVector<EVT, 2> ValueVTs;
7827 ValueVTs.push_back(MVT::Other); // chain
7828 SDVTList VTs = DAG.getVTList(ValueVTs);
7830 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7831 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7833 // Move data into the byte array.
7834 SmallVector<SDValue, 4> Loads, LoadChains;
7835 for (unsigned i = 0; i < 4; ++i) {
7836 unsigned Offset = 4*i;
7837 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7838 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7840 Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7841 PtrInfo.getWithOffset(Offset),
7842 false, false, false, 0));
7843 LoadChains.push_back(Loads[i].getValue(1));
7846 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7848 SmallVector<SDValue, 4> Stores;
7849 for (unsigned i = 0; i < 4; ++i) {
7850 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7851 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7853 Stores.push_back(DAG.getTruncStore(
7854 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
7855 MVT::i8 /* memory type */, SN->isNonTemporal(), SN->isVolatile(),
7856 1 /* alignment */, SN->getAAInfo()));
7859 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7864 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7866 if (Op.getValueType() == MVT::v4i32) {
7867 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7869 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
7870 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7872 SDValue RHSSwap = // = vrlw RHS, 16
7873 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7875 // Shrinkify inputs to v8i16.
7876 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7877 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7878 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7880 // Low parts multiplied together, generating 32-bit results (we ignore the
7882 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7883 LHS, RHS, DAG, dl, MVT::v4i32);
7885 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7886 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7887 // Shift the high parts up 16 bits.
7888 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7890 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7891 } else if (Op.getValueType() == MVT::v8i16) {
7892 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7894 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7896 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7897 LHS, RHS, Zero, DAG, dl);
7898 } else if (Op.getValueType() == MVT::v16i8) {
7899 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7900 bool isLittleEndian = Subtarget.isLittleEndian();
7902 // Multiply the even 8-bit parts, producing 16-bit sums.
7903 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7904 LHS, RHS, DAG, dl, MVT::v8i16);
7905 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7907 // Multiply the odd 8-bit parts, producing 16-bit sums.
7908 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7909 LHS, RHS, DAG, dl, MVT::v8i16);
7910 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7912 // Merge the results together. Because vmuleub and vmuloub are
7913 // instructions with a big-endian bias, we must reverse the
7914 // element numbering and reverse the meaning of "odd" and "even"
7915 // when generating little endian code.
7917 for (unsigned i = 0; i != 8; ++i) {
7918 if (isLittleEndian) {
7920 Ops[i*2+1] = 2*i+16;
7923 Ops[i*2+1] = 2*i+1+16;
7927 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7929 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7931 llvm_unreachable("Unknown mul to lower!");
7935 /// LowerOperation - Provide custom lowering hooks for some operations.
7937 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7938 switch (Op.getOpcode()) {
7939 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7940 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7941 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7942 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7943 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7944 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7945 case ISD::SETCC: return LowerSETCC(Op, DAG);
7946 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
7947 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
7949 return LowerVASTART(Op, DAG, Subtarget);
7952 return LowerVAARG(Op, DAG, Subtarget);
7955 return LowerVACOPY(Op, DAG, Subtarget);
7957 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
7958 case ISD::DYNAMIC_STACKALLOC:
7959 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7960 case ISD::GET_DYNAMIC_AREA_OFFSET: return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG, Subtarget);
7962 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
7963 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
7965 case ISD::LOAD: return LowerLOAD(Op, DAG);
7966 case ISD::STORE: return LowerSTORE(Op, DAG);
7967 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
7968 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7969 case ISD::FP_TO_UINT:
7970 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
7972 case ISD::UINT_TO_FP:
7973 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7974 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7976 // Lower 64-bit shifts.
7977 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
7978 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
7979 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
7981 // Vector-related lowering.
7982 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7983 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7984 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7985 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7986 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
7987 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7988 case ISD::MUL: return LowerMUL(Op, DAG);
7990 // For counter-based loop handling.
7991 case ISD::INTRINSIC_W_CHAIN: return SDValue();
7993 // Frame & Return address.
7994 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7995 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7999 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8000 SmallVectorImpl<SDValue>&Results,
8001 SelectionDAG &DAG) const {
8003 switch (N->getOpcode()) {
8005 llvm_unreachable("Do not know how to custom type legalize this operation!");
8006 case ISD::READCYCLECOUNTER: {
8007 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8008 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8010 Results.push_back(RTB);
8011 Results.push_back(RTB.getValue(1));
8012 Results.push_back(RTB.getValue(2));
8015 case ISD::INTRINSIC_W_CHAIN: {
8016 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8017 Intrinsic::ppc_is_decremented_ctr_nonzero)
8020 assert(N->getValueType(0) == MVT::i1 &&
8021 "Unexpected result type for CTR decrement intrinsic");
8022 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8023 N->getValueType(0));
8024 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8025 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8028 Results.push_back(NewInt);
8029 Results.push_back(NewInt.getValue(1));
8033 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8036 EVT VT = N->getValueType(0);
8038 if (VT == MVT::i64) {
8039 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
8041 Results.push_back(NewNode);
8042 Results.push_back(NewNode.getValue(1));
8046 case ISD::FP_ROUND_INREG: {
8047 assert(N->getValueType(0) == MVT::ppcf128);
8048 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8049 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8050 MVT::f64, N->getOperand(0),
8051 DAG.getIntPtrConstant(0, dl));
8052 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8053 MVT::f64, N->getOperand(0),
8054 DAG.getIntPtrConstant(1, dl));
8056 // Add the two halves of the long double in round-to-zero mode.
8057 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8059 // We know the low half is about to be thrown away, so just use something
8061 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8065 case ISD::FP_TO_SINT:
8066 case ISD::FP_TO_UINT:
8067 // LowerFP_TO_INT() can only handle f32 and f64.
8068 if (N->getOperand(0).getValueType() == MVT::ppcf128)
8070 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8075 //===----------------------------------------------------------------------===//
8076 // Other Lowering Code
8077 //===----------------------------------------------------------------------===//
8079 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8080 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8081 Function *Func = Intrinsic::getDeclaration(M, Id);
8082 return Builder.CreateCall(Func, {});
8085 // The mappings for emitLeading/TrailingFence is taken from
8086 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8087 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8088 AtomicOrdering Ord, bool IsStore,
8089 bool IsLoad) const {
8090 if (Ord == SequentiallyConsistent)
8091 return callIntrinsic(Builder, Intrinsic::ppc_sync);
8092 if (isAtLeastRelease(Ord))
8093 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8097 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8098 AtomicOrdering Ord, bool IsStore,
8099 bool IsLoad) const {
8100 if (IsLoad && isAtLeastAcquire(Ord))
8101 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8102 // FIXME: this is too conservative, a dependent branch + isync is enough.
8103 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8104 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8105 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8110 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
8111 unsigned AtomicSize,
8112 unsigned BinOpcode) const {
8113 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8114 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8116 auto LoadMnemonic = PPC::LDARX;
8117 auto StoreMnemonic = PPC::STDCX;
8118 switch (AtomicSize) {
8120 llvm_unreachable("Unexpected size of atomic entity");
8122 LoadMnemonic = PPC::LBARX;
8123 StoreMnemonic = PPC::STBCX;
8124 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8127 LoadMnemonic = PPC::LHARX;
8128 StoreMnemonic = PPC::STHCX;
8129 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8132 LoadMnemonic = PPC::LWARX;
8133 StoreMnemonic = PPC::STWCX;
8136 LoadMnemonic = PPC::LDARX;
8137 StoreMnemonic = PPC::STDCX;
8141 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8142 MachineFunction *F = BB->getParent();
8143 MachineFunction::iterator It = ++BB->getIterator();
8145 unsigned dest = MI->getOperand(0).getReg();
8146 unsigned ptrA = MI->getOperand(1).getReg();
8147 unsigned ptrB = MI->getOperand(2).getReg();
8148 unsigned incr = MI->getOperand(3).getReg();
8149 DebugLoc dl = MI->getDebugLoc();
8151 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8152 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8153 F->insert(It, loopMBB);
8154 F->insert(It, exitMBB);
8155 exitMBB->splice(exitMBB->begin(), BB,
8156 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8157 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8159 MachineRegisterInfo &RegInfo = F->getRegInfo();
8160 unsigned TmpReg = (!BinOpcode) ? incr :
8161 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8162 : &PPC::GPRCRegClass);
8166 // fallthrough --> loopMBB
8167 BB->addSuccessor(loopMBB);
8170 // l[wd]arx dest, ptr
8171 // add r0, dest, incr
8172 // st[wd]cx. r0, ptr
8174 // fallthrough --> exitMBB
8176 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8177 .addReg(ptrA).addReg(ptrB);
8179 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8180 BuildMI(BB, dl, TII->get(StoreMnemonic))
8181 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8182 BuildMI(BB, dl, TII->get(PPC::BCC))
8183 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8184 BB->addSuccessor(loopMBB);
8185 BB->addSuccessor(exitMBB);
8194 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
8195 MachineBasicBlock *BB,
8196 bool is8bit, // operation
8197 unsigned BinOpcode) const {
8198 // If we support part-word atomic mnemonics, just use them
8199 if (Subtarget.hasPartwordAtomics())
8200 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8202 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8203 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8204 // In 64 bit mode we have to use 64 bits for addresses, even though the
8205 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
8206 // registers without caring whether they're 32 or 64, but here we're
8207 // doing actual arithmetic on the addresses.
8208 bool is64bit = Subtarget.isPPC64();
8209 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8211 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8212 MachineFunction *F = BB->getParent();
8213 MachineFunction::iterator It = ++BB->getIterator();
8215 unsigned dest = MI->getOperand(0).getReg();
8216 unsigned ptrA = MI->getOperand(1).getReg();
8217 unsigned ptrB = MI->getOperand(2).getReg();
8218 unsigned incr = MI->getOperand(3).getReg();
8219 DebugLoc dl = MI->getDebugLoc();
8221 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8222 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8223 F->insert(It, loopMBB);
8224 F->insert(It, exitMBB);
8225 exitMBB->splice(exitMBB->begin(), BB,
8226 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8227 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8229 MachineRegisterInfo &RegInfo = F->getRegInfo();
8230 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8231 : &PPC::GPRCRegClass;
8232 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8233 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8234 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8235 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8236 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8237 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8238 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8239 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8240 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8241 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8242 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8244 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8248 // fallthrough --> loopMBB
8249 BB->addSuccessor(loopMBB);
8251 // The 4-byte load must be aligned, while a char or short may be
8252 // anywhere in the word. Hence all this nasty bookkeeping code.
8253 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8254 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8255 // xori shift, shift1, 24 [16]
8256 // rlwinm ptr, ptr1, 0, 0, 29
8257 // slw incr2, incr, shift
8258 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8259 // slw mask, mask2, shift
8261 // lwarx tmpDest, ptr
8262 // add tmp, tmpDest, incr2
8263 // andc tmp2, tmpDest, mask
8264 // and tmp3, tmp, mask
8265 // or tmp4, tmp3, tmp2
8268 // fallthrough --> exitMBB
8269 // srw dest, tmpDest, shift
8270 if (ptrA != ZeroReg) {
8271 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8272 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8273 .addReg(ptrA).addReg(ptrB);
8277 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8278 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8279 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8280 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8282 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8283 .addReg(Ptr1Reg).addImm(0).addImm(61);
8285 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8286 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8287 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8288 .addReg(incr).addReg(ShiftReg);
8290 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8292 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8293 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8295 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8296 .addReg(Mask2Reg).addReg(ShiftReg);
8299 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8300 .addReg(ZeroReg).addReg(PtrReg);
8302 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8303 .addReg(Incr2Reg).addReg(TmpDestReg);
8304 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8305 .addReg(TmpDestReg).addReg(MaskReg);
8306 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8307 .addReg(TmpReg).addReg(MaskReg);
8308 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8309 .addReg(Tmp3Reg).addReg(Tmp2Reg);
8310 BuildMI(BB, dl, TII->get(PPC::STWCX))
8311 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8312 BuildMI(BB, dl, TII->get(PPC::BCC))
8313 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8314 BB->addSuccessor(loopMBB);
8315 BB->addSuccessor(exitMBB);
8320 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8325 llvm::MachineBasicBlock*
8326 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8327 MachineBasicBlock *MBB) const {
8328 DebugLoc DL = MI->getDebugLoc();
8329 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8331 MachineFunction *MF = MBB->getParent();
8332 MachineRegisterInfo &MRI = MF->getRegInfo();
8334 const BasicBlock *BB = MBB->getBasicBlock();
8335 MachineFunction::iterator I = ++MBB->getIterator();
8338 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8339 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8341 unsigned DstReg = MI->getOperand(0).getReg();
8342 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8343 assert(RC->hasType(MVT::i32) && "Invalid destination!");
8344 unsigned mainDstReg = MRI.createVirtualRegister(RC);
8345 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8347 MVT PVT = getPointerTy(MF->getDataLayout());
8348 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8349 "Invalid Pointer Size!");
8350 // For v = setjmp(buf), we generate
8353 // SjLjSetup mainMBB
8359 // buf[LabelOffset] = LR
8363 // v = phi(main, restore)
8366 MachineBasicBlock *thisMBB = MBB;
8367 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8368 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8369 MF->insert(I, mainMBB);
8370 MF->insert(I, sinkMBB);
8372 MachineInstrBuilder MIB;
8374 // Transfer the remainder of BB and its successor edges to sinkMBB.
8375 sinkMBB->splice(sinkMBB->begin(), MBB,
8376 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8377 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8379 // Note that the structure of the jmp_buf used here is not compatible
8380 // with that used by libc, and is not designed to be. Specifically, it
8381 // stores only those 'reserved' registers that LLVM does not otherwise
8382 // understand how to spill. Also, by convention, by the time this
8383 // intrinsic is called, Clang has already stored the frame address in the
8384 // first slot of the buffer and stack address in the third. Following the
8385 // X86 target code, we'll store the jump address in the second slot. We also
8386 // need to save the TOC pointer (R2) to handle jumps between shared
8387 // libraries, and that will be stored in the fourth slot. The thread
8388 // identifier (R13) is not affected.
8391 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8392 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8393 const int64_t BPOffset = 4 * PVT.getStoreSize();
8395 // Prepare IP either in reg.
8396 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8397 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8398 unsigned BufReg = MI->getOperand(1).getReg();
8400 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8401 setUsesTOCBasePtr(*MBB->getParent());
8402 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8406 MIB.setMemRefs(MMOBegin, MMOEnd);
8409 // Naked functions never have a base pointer, and so we use r1. For all
8410 // other functions, this decision must be delayed until during PEI.
8412 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8413 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8415 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8417 MIB = BuildMI(*thisMBB, MI, DL,
8418 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8422 MIB.setMemRefs(MMOBegin, MMOEnd);
8425 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8426 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8427 MIB.addRegMask(TRI->getNoPreservedMask());
8429 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8431 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8433 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8435 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8436 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8441 BuildMI(mainMBB, DL,
8442 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8445 if (Subtarget.isPPC64()) {
8446 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8448 .addImm(LabelOffset)
8451 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8453 .addImm(LabelOffset)
8457 MIB.setMemRefs(MMOBegin, MMOEnd);
8459 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8460 mainMBB->addSuccessor(sinkMBB);
8463 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8464 TII->get(PPC::PHI), DstReg)
8465 .addReg(mainDstReg).addMBB(mainMBB)
8466 .addReg(restoreDstReg).addMBB(thisMBB);
8468 MI->eraseFromParent();
8473 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8474 MachineBasicBlock *MBB) const {
8475 DebugLoc DL = MI->getDebugLoc();
8476 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8478 MachineFunction *MF = MBB->getParent();
8479 MachineRegisterInfo &MRI = MF->getRegInfo();
8482 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8483 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8485 MVT PVT = getPointerTy(MF->getDataLayout());
8486 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8487 "Invalid Pointer Size!");
8489 const TargetRegisterClass *RC =
8490 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8491 unsigned Tmp = MRI.createVirtualRegister(RC);
8492 // Since FP is only updated here but NOT referenced, it's treated as GPR.
8493 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8494 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8498 : (Subtarget.isSVR4ABI() &&
8499 MF->getTarget().getRelocationModel() == Reloc::PIC_
8503 MachineInstrBuilder MIB;
8505 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8506 const int64_t SPOffset = 2 * PVT.getStoreSize();
8507 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8508 const int64_t BPOffset = 4 * PVT.getStoreSize();
8510 unsigned BufReg = MI->getOperand(0).getReg();
8512 // Reload FP (the jumped-to function may not have had a
8513 // frame pointer, and if so, then its r31 will be restored
8515 if (PVT == MVT::i64) {
8516 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8520 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8524 MIB.setMemRefs(MMOBegin, MMOEnd);
8527 if (PVT == MVT::i64) {
8528 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8529 .addImm(LabelOffset)
8532 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8533 .addImm(LabelOffset)
8536 MIB.setMemRefs(MMOBegin, MMOEnd);
8539 if (PVT == MVT::i64) {
8540 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8544 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8548 MIB.setMemRefs(MMOBegin, MMOEnd);
8551 if (PVT == MVT::i64) {
8552 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8556 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8560 MIB.setMemRefs(MMOBegin, MMOEnd);
8563 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8564 setUsesTOCBasePtr(*MBB->getParent());
8565 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8569 MIB.setMemRefs(MMOBegin, MMOEnd);
8573 BuildMI(*MBB, MI, DL,
8574 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8575 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8577 MI->eraseFromParent();
8582 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8583 MachineBasicBlock *BB) const {
8584 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8585 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8586 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8587 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8588 // Call lowering should have added an r2 operand to indicate a dependence
8589 // on the TOC base pointer value. It can't however, because there is no
8590 // way to mark the dependence as implicit there, and so the stackmap code
8591 // will confuse it with a regular operand. Instead, add the dependence
8593 setUsesTOCBasePtr(*BB->getParent());
8594 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8597 return emitPatchPoint(MI, BB);
8600 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8601 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8602 return emitEHSjLjSetJmp(MI, BB);
8603 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8604 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8605 return emitEHSjLjLongJmp(MI, BB);
8608 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8610 // To "insert" these instructions we actually have to insert their
8611 // control-flow patterns.
8612 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8613 MachineFunction::iterator It = ++BB->getIterator();
8615 MachineFunction *F = BB->getParent();
8617 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8618 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8619 MI->getOpcode() == PPC::SELECT_I4 ||
8620 MI->getOpcode() == PPC::SELECT_I8)) {
8621 SmallVector<MachineOperand, 2> Cond;
8622 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8623 MI->getOpcode() == PPC::SELECT_CC_I8)
8624 Cond.push_back(MI->getOperand(4));
8626 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8627 Cond.push_back(MI->getOperand(1));
8629 DebugLoc dl = MI->getDebugLoc();
8630 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8631 Cond, MI->getOperand(2).getReg(),
8632 MI->getOperand(3).getReg());
8633 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8634 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8635 MI->getOpcode() == PPC::SELECT_CC_F4 ||
8636 MI->getOpcode() == PPC::SELECT_CC_F8 ||
8637 MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8638 MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8639 MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8640 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8641 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8642 MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8643 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8644 MI->getOpcode() == PPC::SELECT_I4 ||
8645 MI->getOpcode() == PPC::SELECT_I8 ||
8646 MI->getOpcode() == PPC::SELECT_F4 ||
8647 MI->getOpcode() == PPC::SELECT_F8 ||
8648 MI->getOpcode() == PPC::SELECT_QFRC ||
8649 MI->getOpcode() == PPC::SELECT_QSRC ||
8650 MI->getOpcode() == PPC::SELECT_QBRC ||
8651 MI->getOpcode() == PPC::SELECT_VRRC ||
8652 MI->getOpcode() == PPC::SELECT_VSFRC ||
8653 MI->getOpcode() == PPC::SELECT_VSSRC ||
8654 MI->getOpcode() == PPC::SELECT_VSRC) {
8655 // The incoming instruction knows the destination vreg to set, the
8656 // condition code register to branch on, the true/false values to
8657 // select between, and a branch opcode to use.
8662 // cmpTY ccX, r1, r2
8664 // fallthrough --> copy0MBB
8665 MachineBasicBlock *thisMBB = BB;
8666 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8667 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8668 DebugLoc dl = MI->getDebugLoc();
8669 F->insert(It, copy0MBB);
8670 F->insert(It, sinkMBB);
8672 // Transfer the remainder of BB and its successor edges to sinkMBB.
8673 sinkMBB->splice(sinkMBB->begin(), BB,
8674 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8675 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8677 // Next, add the true and fallthrough blocks as its successors.
8678 BB->addSuccessor(copy0MBB);
8679 BB->addSuccessor(sinkMBB);
8681 if (MI->getOpcode() == PPC::SELECT_I4 ||
8682 MI->getOpcode() == PPC::SELECT_I8 ||
8683 MI->getOpcode() == PPC::SELECT_F4 ||
8684 MI->getOpcode() == PPC::SELECT_F8 ||
8685 MI->getOpcode() == PPC::SELECT_QFRC ||
8686 MI->getOpcode() == PPC::SELECT_QSRC ||
8687 MI->getOpcode() == PPC::SELECT_QBRC ||
8688 MI->getOpcode() == PPC::SELECT_VRRC ||
8689 MI->getOpcode() == PPC::SELECT_VSFRC ||
8690 MI->getOpcode() == PPC::SELECT_VSSRC ||
8691 MI->getOpcode() == PPC::SELECT_VSRC) {
8692 BuildMI(BB, dl, TII->get(PPC::BC))
8693 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8695 unsigned SelectPred = MI->getOperand(4).getImm();
8696 BuildMI(BB, dl, TII->get(PPC::BCC))
8697 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8701 // %FalseValue = ...
8702 // # fallthrough to sinkMBB
8705 // Update machine-CFG edges
8706 BB->addSuccessor(sinkMBB);
8709 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8712 BuildMI(*BB, BB->begin(), dl,
8713 TII->get(PPC::PHI), MI->getOperand(0).getReg())
8714 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8715 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8716 } else if (MI->getOpcode() == PPC::ReadTB) {
8717 // To read the 64-bit time-base register on a 32-bit target, we read the
8718 // two halves. Should the counter have wrapped while it was being read, we
8719 // need to try again.
8722 // mfspr Rx,TBU # load from TBU
8723 // mfspr Ry,TB # load from TB
8724 // mfspr Rz,TBU # load from TBU
8725 // cmpw crX,Rx,Rz # check if 'old'='new'
8726 // bne readLoop # branch if they're not equal
8729 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8730 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8731 DebugLoc dl = MI->getDebugLoc();
8732 F->insert(It, readMBB);
8733 F->insert(It, sinkMBB);
8735 // Transfer the remainder of BB and its successor edges to sinkMBB.
8736 sinkMBB->splice(sinkMBB->begin(), BB,
8737 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8738 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8740 BB->addSuccessor(readMBB);
8743 MachineRegisterInfo &RegInfo = F->getRegInfo();
8744 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8745 unsigned LoReg = MI->getOperand(0).getReg();
8746 unsigned HiReg = MI->getOperand(1).getReg();
8748 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8749 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8750 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8752 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8754 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8755 .addReg(HiReg).addReg(ReadAgainReg);
8756 BuildMI(BB, dl, TII->get(PPC::BCC))
8757 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8759 BB->addSuccessor(readMBB);
8760 BB->addSuccessor(sinkMBB);
8762 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8763 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8764 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8765 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8766 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8767 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8768 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8769 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8771 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8772 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8773 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8774 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8775 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8776 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8777 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8778 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8780 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8781 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8782 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8783 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8784 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8785 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8786 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8787 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8789 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8790 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8791 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8792 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8793 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8794 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8795 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8796 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8798 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8799 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8800 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8801 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8802 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8803 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8804 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8805 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8807 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8808 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8809 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8810 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8811 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8812 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8813 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8814 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8816 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8817 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8818 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8819 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8820 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8821 BB = EmitAtomicBinary(MI, BB, 4, 0);
8822 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8823 BB = EmitAtomicBinary(MI, BB, 8, 0);
8825 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8826 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8827 (Subtarget.hasPartwordAtomics() &&
8828 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8829 (Subtarget.hasPartwordAtomics() &&
8830 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8831 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8833 auto LoadMnemonic = PPC::LDARX;
8834 auto StoreMnemonic = PPC::STDCX;
8835 switch(MI->getOpcode()) {
8837 llvm_unreachable("Compare and swap of unknown size");
8838 case PPC::ATOMIC_CMP_SWAP_I8:
8839 LoadMnemonic = PPC::LBARX;
8840 StoreMnemonic = PPC::STBCX;
8841 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8843 case PPC::ATOMIC_CMP_SWAP_I16:
8844 LoadMnemonic = PPC::LHARX;
8845 StoreMnemonic = PPC::STHCX;
8846 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8848 case PPC::ATOMIC_CMP_SWAP_I32:
8849 LoadMnemonic = PPC::LWARX;
8850 StoreMnemonic = PPC::STWCX;
8852 case PPC::ATOMIC_CMP_SWAP_I64:
8853 LoadMnemonic = PPC::LDARX;
8854 StoreMnemonic = PPC::STDCX;
8857 unsigned dest = MI->getOperand(0).getReg();
8858 unsigned ptrA = MI->getOperand(1).getReg();
8859 unsigned ptrB = MI->getOperand(2).getReg();
8860 unsigned oldval = MI->getOperand(3).getReg();
8861 unsigned newval = MI->getOperand(4).getReg();
8862 DebugLoc dl = MI->getDebugLoc();
8864 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8865 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8866 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8867 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8868 F->insert(It, loop1MBB);
8869 F->insert(It, loop2MBB);
8870 F->insert(It, midMBB);
8871 F->insert(It, exitMBB);
8872 exitMBB->splice(exitMBB->begin(), BB,
8873 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8874 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8878 // fallthrough --> loopMBB
8879 BB->addSuccessor(loop1MBB);
8882 // l[bhwd]arx dest, ptr
8883 // cmp[wd] dest, oldval
8886 // st[bhwd]cx. newval, ptr
8890 // st[bhwd]cx. dest, ptr
8893 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8894 .addReg(ptrA).addReg(ptrB);
8895 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8896 .addReg(oldval).addReg(dest);
8897 BuildMI(BB, dl, TII->get(PPC::BCC))
8898 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8899 BB->addSuccessor(loop2MBB);
8900 BB->addSuccessor(midMBB);
8903 BuildMI(BB, dl, TII->get(StoreMnemonic))
8904 .addReg(newval).addReg(ptrA).addReg(ptrB);
8905 BuildMI(BB, dl, TII->get(PPC::BCC))
8906 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8907 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8908 BB->addSuccessor(loop1MBB);
8909 BB->addSuccessor(exitMBB);
8912 BuildMI(BB, dl, TII->get(StoreMnemonic))
8913 .addReg(dest).addReg(ptrA).addReg(ptrB);
8914 BB->addSuccessor(exitMBB);
8919 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8920 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8921 // We must use 64-bit registers for addresses when targeting 64-bit,
8922 // since we're actually doing arithmetic on them. Other registers
8924 bool is64bit = Subtarget.isPPC64();
8925 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8927 unsigned dest = MI->getOperand(0).getReg();
8928 unsigned ptrA = MI->getOperand(1).getReg();
8929 unsigned ptrB = MI->getOperand(2).getReg();
8930 unsigned oldval = MI->getOperand(3).getReg();
8931 unsigned newval = MI->getOperand(4).getReg();
8932 DebugLoc dl = MI->getDebugLoc();
8934 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8935 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8936 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8937 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8938 F->insert(It, loop1MBB);
8939 F->insert(It, loop2MBB);
8940 F->insert(It, midMBB);
8941 F->insert(It, exitMBB);
8942 exitMBB->splice(exitMBB->begin(), BB,
8943 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8944 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8946 MachineRegisterInfo &RegInfo = F->getRegInfo();
8947 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8948 : &PPC::GPRCRegClass;
8949 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8950 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8951 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8952 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8953 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8954 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8955 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8956 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8957 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8958 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8959 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8960 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8961 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8963 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8964 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8967 // fallthrough --> loopMBB
8968 BB->addSuccessor(loop1MBB);
8970 // The 4-byte load must be aligned, while a char or short may be
8971 // anywhere in the word. Hence all this nasty bookkeeping code.
8972 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8973 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8974 // xori shift, shift1, 24 [16]
8975 // rlwinm ptr, ptr1, 0, 0, 29
8976 // slw newval2, newval, shift
8977 // slw oldval2, oldval,shift
8978 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8979 // slw mask, mask2, shift
8980 // and newval3, newval2, mask
8981 // and oldval3, oldval2, mask
8983 // lwarx tmpDest, ptr
8984 // and tmp, tmpDest, mask
8985 // cmpw tmp, oldval3
8988 // andc tmp2, tmpDest, mask
8989 // or tmp4, tmp2, newval3
8994 // stwcx. tmpDest, ptr
8996 // srw dest, tmpDest, shift
8997 if (ptrA != ZeroReg) {
8998 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8999 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9000 .addReg(ptrA).addReg(ptrB);
9004 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9005 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9006 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9007 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9009 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9010 .addReg(Ptr1Reg).addImm(0).addImm(61);
9012 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9013 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9014 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9015 .addReg(newval).addReg(ShiftReg);
9016 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9017 .addReg(oldval).addReg(ShiftReg);
9019 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9021 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9022 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9023 .addReg(Mask3Reg).addImm(65535);
9025 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9026 .addReg(Mask2Reg).addReg(ShiftReg);
9027 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9028 .addReg(NewVal2Reg).addReg(MaskReg);
9029 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9030 .addReg(OldVal2Reg).addReg(MaskReg);
9033 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9034 .addReg(ZeroReg).addReg(PtrReg);
9035 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9036 .addReg(TmpDestReg).addReg(MaskReg);
9037 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9038 .addReg(TmpReg).addReg(OldVal3Reg);
9039 BuildMI(BB, dl, TII->get(PPC::BCC))
9040 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9041 BB->addSuccessor(loop2MBB);
9042 BB->addSuccessor(midMBB);
9045 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9046 .addReg(TmpDestReg).addReg(MaskReg);
9047 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9048 .addReg(Tmp2Reg).addReg(NewVal3Reg);
9049 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9050 .addReg(ZeroReg).addReg(PtrReg);
9051 BuildMI(BB, dl, TII->get(PPC::BCC))
9052 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9053 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9054 BB->addSuccessor(loop1MBB);
9055 BB->addSuccessor(exitMBB);
9058 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9059 .addReg(ZeroReg).addReg(PtrReg);
9060 BB->addSuccessor(exitMBB);
9065 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9067 } else if (MI->getOpcode() == PPC::FADDrtz) {
9068 // This pseudo performs an FADD with rounding mode temporarily forced
9069 // to round-to-zero. We emit this via custom inserter since the FPSCR
9070 // is not modeled at the SelectionDAG level.
9071 unsigned Dest = MI->getOperand(0).getReg();
9072 unsigned Src1 = MI->getOperand(1).getReg();
9073 unsigned Src2 = MI->getOperand(2).getReg();
9074 DebugLoc dl = MI->getDebugLoc();
9076 MachineRegisterInfo &RegInfo = F->getRegInfo();
9077 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9079 // Save FPSCR value.
9080 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9082 // Set rounding mode to round-to-zero.
9083 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9084 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9086 // Perform addition.
9087 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9089 // Restore FPSCR value.
9090 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9091 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9092 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
9093 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9094 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9095 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9096 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
9097 PPC::ANDIo8 : PPC::ANDIo;
9098 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9099 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9101 MachineRegisterInfo &RegInfo = F->getRegInfo();
9102 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9103 &PPC::GPRCRegClass :
9104 &PPC::G8RCRegClass);
9106 DebugLoc dl = MI->getDebugLoc();
9107 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9108 .addReg(MI->getOperand(1).getReg()).addImm(1);
9109 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9110 MI->getOperand(0).getReg())
9111 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9112 } else if (MI->getOpcode() == PPC::TCHECK_RET) {
9113 DebugLoc Dl = MI->getDebugLoc();
9114 MachineRegisterInfo &RegInfo = F->getRegInfo();
9115 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9116 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9119 llvm_unreachable("Unexpected instr type to insert");
9122 MI->eraseFromParent(); // The pseudo instruction is gone now.
9126 //===----------------------------------------------------------------------===//
9127 // Target Optimization Hooks
9128 //===----------------------------------------------------------------------===//
9130 static std::string getRecipOp(const char *Base, EVT VT) {
9131 std::string RecipOp(Base);
9132 if (VT.getScalarType() == MVT::f64)
9138 RecipOp = "vec-" + RecipOp;
9143 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9144 DAGCombinerInfo &DCI,
9145 unsigned &RefinementSteps,
9146 bool &UseOneConstNR) const {
9147 EVT VT = Operand.getValueType();
9148 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9149 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9150 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9151 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9152 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9153 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9154 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9155 std::string RecipOp = getRecipOp("sqrt", VT);
9156 if (!Recips.isEnabled(RecipOp))
9159 RefinementSteps = Recips.getRefinementSteps(RecipOp);
9160 UseOneConstNR = true;
9161 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9166 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9167 DAGCombinerInfo &DCI,
9168 unsigned &RefinementSteps) const {
9169 EVT VT = Operand.getValueType();
9170 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9171 (VT == MVT::f64 && Subtarget.hasFRE()) ||
9172 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9173 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9174 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9175 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9176 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9177 std::string RecipOp = getRecipOp("div", VT);
9178 if (!Recips.isEnabled(RecipOp))
9181 RefinementSteps = Recips.getRefinementSteps(RecipOp);
9182 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9187 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9188 // Note: This functionality is used only when unsafe-fp-math is enabled, and
9189 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9190 // enabled for division), this functionality is redundant with the default
9191 // combiner logic (once the division -> reciprocal/multiply transformation
9192 // has taken place). As a result, this matters more for older cores than for
9195 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9196 // reciprocal if there are two or more FDIVs (for embedded cores with only
9197 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9198 switch (Subtarget.getDarwinDirective()) {
9203 case PPC::DIR_E500mc:
9204 case PPC::DIR_E5500:
9209 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9210 // collapsed, and so we need to look through chains of them.
9211 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9212 int64_t& Offset, SelectionDAG &DAG) {
9213 if (DAG.isBaseWithConstantOffset(Loc)) {
9214 Base = Loc.getOperand(0);
9215 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9217 // The base might itself be a base plus an offset, and if so, accumulate
9219 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9223 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9224 unsigned Bytes, int Dist,
9225 SelectionDAG &DAG) {
9226 if (VT.getSizeInBits() / 8 != Bytes)
9229 SDValue BaseLoc = Base->getBasePtr();
9230 if (Loc.getOpcode() == ISD::FrameIndex) {
9231 if (BaseLoc.getOpcode() != ISD::FrameIndex)
9233 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9234 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
9235 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9236 int FS = MFI->getObjectSize(FI);
9237 int BFS = MFI->getObjectSize(BFI);
9238 if (FS != BFS || FS != (int)Bytes) return false;
9239 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9242 SDValue Base1 = Loc, Base2 = BaseLoc;
9243 int64_t Offset1 = 0, Offset2 = 0;
9244 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9245 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9246 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9249 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9250 const GlobalValue *GV1 = nullptr;
9251 const GlobalValue *GV2 = nullptr;
9254 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9255 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9256 if (isGA1 && isGA2 && GV1 == GV2)
9257 return Offset1 == (Offset2 + Dist*Bytes);
9261 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9262 // not enforce equality of the chain operands.
9263 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9264 unsigned Bytes, int Dist,
9265 SelectionDAG &DAG) {
9266 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9267 EVT VT = LS->getMemoryVT();
9268 SDValue Loc = LS->getBasePtr();
9269 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9272 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9274 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9275 default: return false;
9276 case Intrinsic::ppc_qpx_qvlfd:
9277 case Intrinsic::ppc_qpx_qvlfda:
9280 case Intrinsic::ppc_qpx_qvlfs:
9281 case Intrinsic::ppc_qpx_qvlfsa:
9284 case Intrinsic::ppc_qpx_qvlfcd:
9285 case Intrinsic::ppc_qpx_qvlfcda:
9288 case Intrinsic::ppc_qpx_qvlfcs:
9289 case Intrinsic::ppc_qpx_qvlfcsa:
9292 case Intrinsic::ppc_qpx_qvlfiwa:
9293 case Intrinsic::ppc_qpx_qvlfiwz:
9294 case Intrinsic::ppc_altivec_lvx:
9295 case Intrinsic::ppc_altivec_lvxl:
9296 case Intrinsic::ppc_vsx_lxvw4x:
9299 case Intrinsic::ppc_vsx_lxvd2x:
9302 case Intrinsic::ppc_altivec_lvebx:
9305 case Intrinsic::ppc_altivec_lvehx:
9308 case Intrinsic::ppc_altivec_lvewx:
9313 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9316 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9318 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9319 default: return false;
9320 case Intrinsic::ppc_qpx_qvstfd:
9321 case Intrinsic::ppc_qpx_qvstfda:
9324 case Intrinsic::ppc_qpx_qvstfs:
9325 case Intrinsic::ppc_qpx_qvstfsa:
9328 case Intrinsic::ppc_qpx_qvstfcd:
9329 case Intrinsic::ppc_qpx_qvstfcda:
9332 case Intrinsic::ppc_qpx_qvstfcs:
9333 case Intrinsic::ppc_qpx_qvstfcsa:
9336 case Intrinsic::ppc_qpx_qvstfiw:
9337 case Intrinsic::ppc_qpx_qvstfiwa:
9338 case Intrinsic::ppc_altivec_stvx:
9339 case Intrinsic::ppc_altivec_stvxl:
9340 case Intrinsic::ppc_vsx_stxvw4x:
9343 case Intrinsic::ppc_vsx_stxvd2x:
9346 case Intrinsic::ppc_altivec_stvebx:
9349 case Intrinsic::ppc_altivec_stvehx:
9352 case Intrinsic::ppc_altivec_stvewx:
9357 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9363 // Return true is there is a nearyby consecutive load to the one provided
9364 // (regardless of alignment). We search up and down the chain, looking though
9365 // token factors and other loads (but nothing else). As a result, a true result
9366 // indicates that it is safe to create a new consecutive load adjacent to the
9368 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9369 SDValue Chain = LD->getChain();
9370 EVT VT = LD->getMemoryVT();
9372 SmallSet<SDNode *, 16> LoadRoots;
9373 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9374 SmallSet<SDNode *, 16> Visited;
9376 // First, search up the chain, branching to follow all token-factor operands.
9377 // If we find a consecutive load, then we're done, otherwise, record all
9378 // nodes just above the top-level loads and token factors.
9379 while (!Queue.empty()) {
9380 SDNode *ChainNext = Queue.pop_back_val();
9381 if (!Visited.insert(ChainNext).second)
9384 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9385 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9388 if (!Visited.count(ChainLD->getChain().getNode()))
9389 Queue.push_back(ChainLD->getChain().getNode());
9390 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9391 for (const SDUse &O : ChainNext->ops())
9392 if (!Visited.count(O.getNode()))
9393 Queue.push_back(O.getNode());
9395 LoadRoots.insert(ChainNext);
9398 // Second, search down the chain, starting from the top-level nodes recorded
9399 // in the first phase. These top-level nodes are the nodes just above all
9400 // loads and token factors. Starting with their uses, recursively look though
9401 // all loads (just the chain uses) and token factors to find a consecutive
9406 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9407 IE = LoadRoots.end(); I != IE; ++I) {
9408 Queue.push_back(*I);
9410 while (!Queue.empty()) {
9411 SDNode *LoadRoot = Queue.pop_back_val();
9412 if (!Visited.insert(LoadRoot).second)
9415 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9416 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9419 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9420 UE = LoadRoot->use_end(); UI != UE; ++UI)
9421 if (((isa<MemSDNode>(*UI) &&
9422 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9423 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9424 Queue.push_back(*UI);
9431 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9432 DAGCombinerInfo &DCI) const {
9433 SelectionDAG &DAG = DCI.DAG;
9436 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9437 // If we're tracking CR bits, we need to be careful that we don't have:
9438 // trunc(binary-ops(zext(x), zext(y)))
9440 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9441 // such that we're unnecessarily moving things into GPRs when it would be
9442 // better to keep them in CR bits.
9444 // Note that trunc here can be an actual i1 trunc, or can be the effective
9445 // truncation that comes from a setcc or select_cc.
9446 if (N->getOpcode() == ISD::TRUNCATE &&
9447 N->getValueType(0) != MVT::i1)
9450 if (N->getOperand(0).getValueType() != MVT::i32 &&
9451 N->getOperand(0).getValueType() != MVT::i64)
9454 if (N->getOpcode() == ISD::SETCC ||
9455 N->getOpcode() == ISD::SELECT_CC) {
9456 // If we're looking at a comparison, then we need to make sure that the
9457 // high bits (all except for the first) don't matter the result.
9459 cast<CondCodeSDNode>(N->getOperand(
9460 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9461 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9463 if (ISD::isSignedIntSetCC(CC)) {
9464 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9465 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9467 } else if (ISD::isUnsignedIntSetCC(CC)) {
9468 if (!DAG.MaskedValueIsZero(N->getOperand(0),
9469 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9470 !DAG.MaskedValueIsZero(N->getOperand(1),
9471 APInt::getHighBitsSet(OpBits, OpBits-1)))
9474 // This is neither a signed nor an unsigned comparison, just make sure
9475 // that the high bits are equal.
9476 APInt Op1Zero, Op1One;
9477 APInt Op2Zero, Op2One;
9478 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9479 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9481 // We don't really care about what is known about the first bit (if
9482 // anything), so clear it in all masks prior to comparing them.
9483 Op1Zero.clearBit(0); Op1One.clearBit(0);
9484 Op2Zero.clearBit(0); Op2One.clearBit(0);
9486 if (Op1Zero != Op2Zero || Op1One != Op2One)
9491 // We now know that the higher-order bits are irrelevant, we just need to
9492 // make sure that all of the intermediate operations are bit operations, and
9493 // all inputs are extensions.
9494 if (N->getOperand(0).getOpcode() != ISD::AND &&
9495 N->getOperand(0).getOpcode() != ISD::OR &&
9496 N->getOperand(0).getOpcode() != ISD::XOR &&
9497 N->getOperand(0).getOpcode() != ISD::SELECT &&
9498 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9499 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9500 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9501 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9502 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9505 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9506 N->getOperand(1).getOpcode() != ISD::AND &&
9507 N->getOperand(1).getOpcode() != ISD::OR &&
9508 N->getOperand(1).getOpcode() != ISD::XOR &&
9509 N->getOperand(1).getOpcode() != ISD::SELECT &&
9510 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9511 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9512 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9513 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9514 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9517 SmallVector<SDValue, 4> Inputs;
9518 SmallVector<SDValue, 8> BinOps, PromOps;
9519 SmallPtrSet<SDNode *, 16> Visited;
9521 for (unsigned i = 0; i < 2; ++i) {
9522 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9523 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9524 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9525 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9526 isa<ConstantSDNode>(N->getOperand(i)))
9527 Inputs.push_back(N->getOperand(i));
9529 BinOps.push_back(N->getOperand(i));
9531 if (N->getOpcode() == ISD::TRUNCATE)
9535 // Visit all inputs, collect all binary operations (and, or, xor and
9536 // select) that are all fed by extensions.
9537 while (!BinOps.empty()) {
9538 SDValue BinOp = BinOps.back();
9541 if (!Visited.insert(BinOp.getNode()).second)
9544 PromOps.push_back(BinOp);
9546 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9547 // The condition of the select is not promoted.
9548 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9550 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9553 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9554 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9555 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9556 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9557 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9558 Inputs.push_back(BinOp.getOperand(i));
9559 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9560 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9561 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9562 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9563 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9564 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9565 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9566 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9567 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9568 BinOps.push_back(BinOp.getOperand(i));
9570 // We have an input that is not an extension or another binary
9571 // operation; we'll abort this transformation.
9577 // Make sure that this is a self-contained cluster of operations (which
9578 // is not quite the same thing as saying that everything has only one
9580 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9581 if (isa<ConstantSDNode>(Inputs[i]))
9584 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9585 UE = Inputs[i].getNode()->use_end();
9588 if (User != N && !Visited.count(User))
9591 // Make sure that we're not going to promote the non-output-value
9592 // operand(s) or SELECT or SELECT_CC.
9593 // FIXME: Although we could sometimes handle this, and it does occur in
9594 // practice that one of the condition inputs to the select is also one of
9595 // the outputs, we currently can't deal with this.
9596 if (User->getOpcode() == ISD::SELECT) {
9597 if (User->getOperand(0) == Inputs[i])
9599 } else if (User->getOpcode() == ISD::SELECT_CC) {
9600 if (User->getOperand(0) == Inputs[i] ||
9601 User->getOperand(1) == Inputs[i])
9607 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9608 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9609 UE = PromOps[i].getNode()->use_end();
9612 if (User != N && !Visited.count(User))
9615 // Make sure that we're not going to promote the non-output-value
9616 // operand(s) or SELECT or SELECT_CC.
9617 // FIXME: Although we could sometimes handle this, and it does occur in
9618 // practice that one of the condition inputs to the select is also one of
9619 // the outputs, we currently can't deal with this.
9620 if (User->getOpcode() == ISD::SELECT) {
9621 if (User->getOperand(0) == PromOps[i])
9623 } else if (User->getOpcode() == ISD::SELECT_CC) {
9624 if (User->getOperand(0) == PromOps[i] ||
9625 User->getOperand(1) == PromOps[i])
9631 // Replace all inputs with the extension operand.
9632 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9633 // Constants may have users outside the cluster of to-be-promoted nodes,
9634 // and so we need to replace those as we do the promotions.
9635 if (isa<ConstantSDNode>(Inputs[i]))
9638 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9641 // Replace all operations (these are all the same, but have a different
9642 // (i1) return type). DAG.getNode will validate that the types of
9643 // a binary operator match, so go through the list in reverse so that
9644 // we've likely promoted both operands first. Any intermediate truncations or
9645 // extensions disappear.
9646 while (!PromOps.empty()) {
9647 SDValue PromOp = PromOps.back();
9650 if (PromOp.getOpcode() == ISD::TRUNCATE ||
9651 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9652 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9653 PromOp.getOpcode() == ISD::ANY_EXTEND) {
9654 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9655 PromOp.getOperand(0).getValueType() != MVT::i1) {
9656 // The operand is not yet ready (see comment below).
9657 PromOps.insert(PromOps.begin(), PromOp);
9661 SDValue RepValue = PromOp.getOperand(0);
9662 if (isa<ConstantSDNode>(RepValue))
9663 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9665 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9670 switch (PromOp.getOpcode()) {
9671 default: C = 0; break;
9672 case ISD::SELECT: C = 1; break;
9673 case ISD::SELECT_CC: C = 2; break;
9676 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9677 PromOp.getOperand(C).getValueType() != MVT::i1) ||
9678 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9679 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9680 // The to-be-promoted operands of this node have not yet been
9681 // promoted (this should be rare because we're going through the
9682 // list backward, but if one of the operands has several users in
9683 // this cluster of to-be-promoted nodes, it is possible).
9684 PromOps.insert(PromOps.begin(), PromOp);
9688 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9689 PromOp.getNode()->op_end());
9691 // If there are any constant inputs, make sure they're replaced now.
9692 for (unsigned i = 0; i < 2; ++i)
9693 if (isa<ConstantSDNode>(Ops[C+i]))
9694 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9696 DAG.ReplaceAllUsesOfValueWith(PromOp,
9697 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9700 // Now we're left with the initial truncation itself.
9701 if (N->getOpcode() == ISD::TRUNCATE)
9702 return N->getOperand(0);
9704 // Otherwise, this is a comparison. The operands to be compared have just
9705 // changed type (to i1), but everything else is the same.
9706 return SDValue(N, 0);
9709 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9710 DAGCombinerInfo &DCI) const {
9711 SelectionDAG &DAG = DCI.DAG;
9714 // If we're tracking CR bits, we need to be careful that we don't have:
9715 // zext(binary-ops(trunc(x), trunc(y)))
9717 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9718 // such that we're unnecessarily moving things into CR bits that can more
9719 // efficiently stay in GPRs. Note that if we're not certain that the high
9720 // bits are set as required by the final extension, we still may need to do
9721 // some masking to get the proper behavior.
9723 // This same functionality is important on PPC64 when dealing with
9724 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9725 // the return values of functions. Because it is so similar, it is handled
9728 if (N->getValueType(0) != MVT::i32 &&
9729 N->getValueType(0) != MVT::i64)
9732 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9733 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9736 if (N->getOperand(0).getOpcode() != ISD::AND &&
9737 N->getOperand(0).getOpcode() != ISD::OR &&
9738 N->getOperand(0).getOpcode() != ISD::XOR &&
9739 N->getOperand(0).getOpcode() != ISD::SELECT &&
9740 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9743 SmallVector<SDValue, 4> Inputs;
9744 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9745 SmallPtrSet<SDNode *, 16> Visited;
9747 // Visit all inputs, collect all binary operations (and, or, xor and
9748 // select) that are all fed by truncations.
9749 while (!BinOps.empty()) {
9750 SDValue BinOp = BinOps.back();
9753 if (!Visited.insert(BinOp.getNode()).second)
9756 PromOps.push_back(BinOp);
9758 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9759 // The condition of the select is not promoted.
9760 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9762 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9765 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9766 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9767 Inputs.push_back(BinOp.getOperand(i));
9768 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9769 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9770 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9771 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9772 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9773 BinOps.push_back(BinOp.getOperand(i));
9775 // We have an input that is not a truncation or another binary
9776 // operation; we'll abort this transformation.
9782 // The operands of a select that must be truncated when the select is
9783 // promoted because the operand is actually part of the to-be-promoted set.
9784 DenseMap<SDNode *, EVT> SelectTruncOp[2];
9786 // Make sure that this is a self-contained cluster of operations (which
9787 // is not quite the same thing as saying that everything has only one
9789 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9790 if (isa<ConstantSDNode>(Inputs[i]))
9793 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9794 UE = Inputs[i].getNode()->use_end();
9797 if (User != N && !Visited.count(User))
9800 // If we're going to promote the non-output-value operand(s) or SELECT or
9801 // SELECT_CC, record them for truncation.
9802 if (User->getOpcode() == ISD::SELECT) {
9803 if (User->getOperand(0) == Inputs[i])
9804 SelectTruncOp[0].insert(std::make_pair(User,
9805 User->getOperand(0).getValueType()));
9806 } else if (User->getOpcode() == ISD::SELECT_CC) {
9807 if (User->getOperand(0) == Inputs[i])
9808 SelectTruncOp[0].insert(std::make_pair(User,
9809 User->getOperand(0).getValueType()));
9810 if (User->getOperand(1) == Inputs[i])
9811 SelectTruncOp[1].insert(std::make_pair(User,
9812 User->getOperand(1).getValueType()));
9817 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9818 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9819 UE = PromOps[i].getNode()->use_end();
9822 if (User != N && !Visited.count(User))
9825 // If we're going to promote the non-output-value operand(s) or SELECT or
9826 // SELECT_CC, record them for truncation.
9827 if (User->getOpcode() == ISD::SELECT) {
9828 if (User->getOperand(0) == PromOps[i])
9829 SelectTruncOp[0].insert(std::make_pair(User,
9830 User->getOperand(0).getValueType()));
9831 } else if (User->getOpcode() == ISD::SELECT_CC) {
9832 if (User->getOperand(0) == PromOps[i])
9833 SelectTruncOp[0].insert(std::make_pair(User,
9834 User->getOperand(0).getValueType()));
9835 if (User->getOperand(1) == PromOps[i])
9836 SelectTruncOp[1].insert(std::make_pair(User,
9837 User->getOperand(1).getValueType()));
9842 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9843 bool ReallyNeedsExt = false;
9844 if (N->getOpcode() != ISD::ANY_EXTEND) {
9845 // If all of the inputs are not already sign/zero extended, then
9846 // we'll still need to do that at the end.
9847 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9848 if (isa<ConstantSDNode>(Inputs[i]))
9852 Inputs[i].getOperand(0).getValueSizeInBits();
9853 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9855 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9856 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9857 APInt::getHighBitsSet(OpBits,
9858 OpBits-PromBits))) ||
9859 (N->getOpcode() == ISD::SIGN_EXTEND &&
9860 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9861 (OpBits-(PromBits-1)))) {
9862 ReallyNeedsExt = true;
9868 // Replace all inputs, either with the truncation operand, or a
9869 // truncation or extension to the final output type.
9870 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9871 // Constant inputs need to be replaced with the to-be-promoted nodes that
9872 // use them because they might have users outside of the cluster of
9874 if (isa<ConstantSDNode>(Inputs[i]))
9877 SDValue InSrc = Inputs[i].getOperand(0);
9878 if (Inputs[i].getValueType() == N->getValueType(0))
9879 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9880 else if (N->getOpcode() == ISD::SIGN_EXTEND)
9881 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9882 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9883 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9884 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9885 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9887 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9888 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9891 // Replace all operations (these are all the same, but have a different
9892 // (promoted) return type). DAG.getNode will validate that the types of
9893 // a binary operator match, so go through the list in reverse so that
9894 // we've likely promoted both operands first.
9895 while (!PromOps.empty()) {
9896 SDValue PromOp = PromOps.back();
9900 switch (PromOp.getOpcode()) {
9901 default: C = 0; break;
9902 case ISD::SELECT: C = 1; break;
9903 case ISD::SELECT_CC: C = 2; break;
9906 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9907 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9908 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9909 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9910 // The to-be-promoted operands of this node have not yet been
9911 // promoted (this should be rare because we're going through the
9912 // list backward, but if one of the operands has several users in
9913 // this cluster of to-be-promoted nodes, it is possible).
9914 PromOps.insert(PromOps.begin(), PromOp);
9918 // For SELECT and SELECT_CC nodes, we do a similar check for any
9919 // to-be-promoted comparison inputs.
9920 if (PromOp.getOpcode() == ISD::SELECT ||
9921 PromOp.getOpcode() == ISD::SELECT_CC) {
9922 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9923 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9924 (SelectTruncOp[1].count(PromOp.getNode()) &&
9925 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9926 PromOps.insert(PromOps.begin(), PromOp);
9931 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9932 PromOp.getNode()->op_end());
9934 // If this node has constant inputs, then they'll need to be promoted here.
9935 for (unsigned i = 0; i < 2; ++i) {
9936 if (!isa<ConstantSDNode>(Ops[C+i]))
9938 if (Ops[C+i].getValueType() == N->getValueType(0))
9941 if (N->getOpcode() == ISD::SIGN_EXTEND)
9942 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9943 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9944 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9946 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9949 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9950 // truncate them again to the original value type.
9951 if (PromOp.getOpcode() == ISD::SELECT ||
9952 PromOp.getOpcode() == ISD::SELECT_CC) {
9953 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9954 if (SI0 != SelectTruncOp[0].end())
9955 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9956 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9957 if (SI1 != SelectTruncOp[1].end())
9958 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9961 DAG.ReplaceAllUsesOfValueWith(PromOp,
9962 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9965 // Now we're left with the initial extension itself.
9966 if (!ReallyNeedsExt)
9967 return N->getOperand(0);
9969 // To zero extend, just mask off everything except for the first bit (in the
9971 if (N->getOpcode() == ISD::ZERO_EXTEND)
9972 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9973 DAG.getConstant(APInt::getLowBitsSet(
9974 N->getValueSizeInBits(0), PromBits),
9975 dl, N->getValueType(0)));
9977 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9978 "Invalid extension type");
9979 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
9981 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
9983 ISD::SRA, dl, N->getValueType(0),
9984 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
9988 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9989 DAGCombinerInfo &DCI) const {
9990 assert((N->getOpcode() == ISD::SINT_TO_FP ||
9991 N->getOpcode() == ISD::UINT_TO_FP) &&
9992 "Need an int -> FP conversion node here");
9994 if (!Subtarget.has64BitSupport())
9997 SelectionDAG &DAG = DCI.DAG;
10001 // Don't handle ppc_fp128 here or i1 conversions.
10002 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10004 if (Op.getOperand(0).getValueType() == MVT::i1)
10007 // For i32 intermediate values, unfortunately, the conversion functions
10008 // leave the upper 32 bits of the value are undefined. Within the set of
10009 // scalar instructions, we have no method for zero- or sign-extending the
10010 // value. Thus, we cannot handle i32 intermediate values here.
10011 if (Op.getOperand(0).getValueType() == MVT::i32)
10014 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10015 "UINT_TO_FP is supported only with FPCVT");
10017 // If we have FCFIDS, then use it when converting to single-precision.
10018 // Otherwise, convert to double-precision and then round.
10019 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10020 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10022 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10024 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10028 // If we're converting from a float, to an int, and back to a float again,
10029 // then we don't need the store/load pair at all.
10030 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10031 Subtarget.hasFPCVT()) ||
10032 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10033 SDValue Src = Op.getOperand(0).getOperand(0);
10034 if (Src.getValueType() == MVT::f32) {
10035 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10036 DCI.AddToWorklist(Src.getNode());
10037 } else if (Src.getValueType() != MVT::f64) {
10038 // Make sure that we don't pick up a ppc_fp128 source value.
10043 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10046 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10047 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10049 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10050 FP = DAG.getNode(ISD::FP_ROUND, dl,
10051 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10052 DCI.AddToWorklist(FP.getNode());
10061 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10062 // builtins) into loads with swaps.
10063 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10064 DAGCombinerInfo &DCI) const {
10065 SelectionDAG &DAG = DCI.DAG;
10069 MachineMemOperand *MMO;
10071 switch (N->getOpcode()) {
10073 llvm_unreachable("Unexpected opcode for little endian VSX load");
10075 LoadSDNode *LD = cast<LoadSDNode>(N);
10076 Chain = LD->getChain();
10077 Base = LD->getBasePtr();
10078 MMO = LD->getMemOperand();
10079 // If the MMO suggests this isn't a load of a full vector, leave
10080 // things alone. For a built-in, we have to make the change for
10081 // correctness, so if there is a size problem that will be a bug.
10082 if (MMO->getSize() < 16)
10086 case ISD::INTRINSIC_W_CHAIN: {
10087 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10088 Chain = Intrin->getChain();
10089 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10090 // us what we want. Get operand 2 instead.
10091 Base = Intrin->getOperand(2);
10092 MMO = Intrin->getMemOperand();
10097 MVT VecTy = N->getValueType(0).getSimpleVT();
10098 SDValue LoadOps[] = { Chain, Base };
10099 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10100 DAG.getVTList(VecTy, MVT::Other),
10101 LoadOps, VecTy, MMO);
10102 DCI.AddToWorklist(Load.getNode());
10103 Chain = Load.getValue(1);
10104 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10105 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
10106 DCI.AddToWorklist(Swap.getNode());
10110 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10111 // builtins) into stores with swaps.
10112 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10113 DAGCombinerInfo &DCI) const {
10114 SelectionDAG &DAG = DCI.DAG;
10119 MachineMemOperand *MMO;
10121 switch (N->getOpcode()) {
10123 llvm_unreachable("Unexpected opcode for little endian VSX store");
10125 StoreSDNode *ST = cast<StoreSDNode>(N);
10126 Chain = ST->getChain();
10127 Base = ST->getBasePtr();
10128 MMO = ST->getMemOperand();
10130 // If the MMO suggests this isn't a store of a full vector, leave
10131 // things alone. For a built-in, we have to make the change for
10132 // correctness, so if there is a size problem that will be a bug.
10133 if (MMO->getSize() < 16)
10137 case ISD::INTRINSIC_VOID: {
10138 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10139 Chain = Intrin->getChain();
10140 // Intrin->getBasePtr() oddly does not get what we want.
10141 Base = Intrin->getOperand(3);
10142 MMO = Intrin->getMemOperand();
10148 SDValue Src = N->getOperand(SrcOpnd);
10149 MVT VecTy = Src.getValueType().getSimpleVT();
10150 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10151 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
10152 DCI.AddToWorklist(Swap.getNode());
10153 Chain = Swap.getValue(1);
10154 SDValue StoreOps[] = { Chain, Swap, Base };
10155 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10156 DAG.getVTList(MVT::Other),
10157 StoreOps, VecTy, MMO);
10158 DCI.AddToWorklist(Store.getNode());
10162 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10163 DAGCombinerInfo &DCI) const {
10164 SelectionDAG &DAG = DCI.DAG;
10166 switch (N->getOpcode()) {
10169 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10170 return N->getOperand(0);
10173 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10174 return N->getOperand(0);
10177 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10178 if (C->isNullValue() || // 0 >>s V -> 0.
10179 C->isAllOnesValue()) // -1 >>s V -> -1.
10180 return N->getOperand(0);
10183 case ISD::SIGN_EXTEND:
10184 case ISD::ZERO_EXTEND:
10185 case ISD::ANY_EXTEND:
10186 return DAGCombineExtBoolTrunc(N, DCI);
10187 case ISD::TRUNCATE:
10189 case ISD::SELECT_CC:
10190 return DAGCombineTruncBoolExt(N, DCI);
10191 case ISD::SINT_TO_FP:
10192 case ISD::UINT_TO_FP:
10193 return combineFPToIntToFP(N, DCI);
10195 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10196 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10197 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10198 N->getOperand(1).getValueType() == MVT::i32 &&
10199 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10200 SDValue Val = N->getOperand(1).getOperand(0);
10201 if (Val.getValueType() == MVT::f32) {
10202 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10203 DCI.AddToWorklist(Val.getNode());
10205 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10206 DCI.AddToWorklist(Val.getNode());
10209 N->getOperand(0), Val, N->getOperand(2),
10210 DAG.getValueType(N->getOperand(1).getValueType())
10213 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10214 DAG.getVTList(MVT::Other), Ops,
10215 cast<StoreSDNode>(N)->getMemoryVT(),
10216 cast<StoreSDNode>(N)->getMemOperand());
10217 DCI.AddToWorklist(Val.getNode());
10221 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10222 if (cast<StoreSDNode>(N)->isUnindexed() &&
10223 N->getOperand(1).getOpcode() == ISD::BSWAP &&
10224 N->getOperand(1).getNode()->hasOneUse() &&
10225 (N->getOperand(1).getValueType() == MVT::i32 ||
10226 N->getOperand(1).getValueType() == MVT::i16 ||
10227 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10228 N->getOperand(1).getValueType() == MVT::i64))) {
10229 SDValue BSwapOp = N->getOperand(1).getOperand(0);
10230 // Do an any-extend to 32-bits if this is a half-word input.
10231 if (BSwapOp.getValueType() == MVT::i16)
10232 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10235 N->getOperand(0), BSwapOp, N->getOperand(2),
10236 DAG.getValueType(N->getOperand(1).getValueType())
10239 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10240 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10241 cast<StoreSDNode>(N)->getMemOperand());
10244 // For little endian, VSX stores require generating xxswapd/lxvd2x.
10245 EVT VT = N->getOperand(1).getValueType();
10246 if (VT.isSimple()) {
10247 MVT StoreVT = VT.getSimpleVT();
10248 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10249 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10250 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10251 return expandVSXStoreForLE(N, DCI);
10256 LoadSDNode *LD = cast<LoadSDNode>(N);
10257 EVT VT = LD->getValueType(0);
10259 // For little endian, VSX loads require generating lxvd2x/xxswapd.
10260 if (VT.isSimple()) {
10261 MVT LoadVT = VT.getSimpleVT();
10262 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10263 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10264 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10265 return expandVSXLoadForLE(N, DCI);
10268 EVT MemVT = LD->getMemoryVT();
10269 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10270 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10271 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10272 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10273 if (LD->isUnindexed() && VT.isVector() &&
10274 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10275 // P8 and later hardware should just use LOAD.
10276 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10277 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10278 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10279 LD->getAlignment() >= ScalarABIAlignment)) &&
10280 LD->getAlignment() < ABIAlignment) {
10281 // This is a type-legal unaligned Altivec or QPX load.
10282 SDValue Chain = LD->getChain();
10283 SDValue Ptr = LD->getBasePtr();
10284 bool isLittleEndian = Subtarget.isLittleEndian();
10286 // This implements the loading of unaligned vectors as described in
10287 // the venerable Apple Velocity Engine overview. Specifically:
10288 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10289 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10291 // The general idea is to expand a sequence of one or more unaligned
10292 // loads into an alignment-based permutation-control instruction (lvsl
10293 // or lvsr), a series of regular vector loads (which always truncate
10294 // their input address to an aligned address), and a series of
10295 // permutations. The results of these permutations are the requested
10296 // loaded values. The trick is that the last "extra" load is not taken
10297 // from the address you might suspect (sizeof(vector) bytes after the
10298 // last requested load), but rather sizeof(vector) - 1 bytes after the
10299 // last requested vector. The point of this is to avoid a page fault if
10300 // the base address happened to be aligned. This works because if the
10301 // base address is aligned, then adding less than a full vector length
10302 // will cause the last vector in the sequence to be (re)loaded.
10303 // Otherwise, the next vector will be fetched as you might suspect was
10306 // We might be able to reuse the permutation generation from
10307 // a different base address offset from this one by an aligned amount.
10308 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10309 // optimization later.
10310 Intrinsic::ID Intr, IntrLD, IntrPerm;
10311 MVT PermCntlTy, PermTy, LDTy;
10312 if (Subtarget.hasAltivec()) {
10313 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
10314 Intrinsic::ppc_altivec_lvsl;
10315 IntrLD = Intrinsic::ppc_altivec_lvx;
10316 IntrPerm = Intrinsic::ppc_altivec_vperm;
10317 PermCntlTy = MVT::v16i8;
10318 PermTy = MVT::v4i32;
10321 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10322 Intrinsic::ppc_qpx_qvlpcls;
10323 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10324 Intrinsic::ppc_qpx_qvlfs;
10325 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10326 PermCntlTy = MVT::v4f64;
10327 PermTy = MVT::v4f64;
10328 LDTy = MemVT.getSimpleVT();
10331 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10333 // Create the new MMO for the new base load. It is like the original MMO,
10334 // but represents an area in memory almost twice the vector size centered
10335 // on the original address. If the address is unaligned, we might start
10336 // reading up to (sizeof(vector)-1) bytes below the address of the
10337 // original unaligned load.
10338 MachineFunction &MF = DAG.getMachineFunction();
10339 MachineMemOperand *BaseMMO =
10340 MF.getMachineMemOperand(LD->getMemOperand(),
10341 -(long)MemVT.getStoreSize()+1,
10342 2*MemVT.getStoreSize()-1);
10344 // Create the new base load.
10346 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10347 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10349 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10350 DAG.getVTList(PermTy, MVT::Other),
10351 BaseLoadOps, LDTy, BaseMMO);
10353 // Note that the value of IncOffset (which is provided to the next
10354 // load's pointer info offset value, and thus used to calculate the
10355 // alignment), and the value of IncValue (which is actually used to
10356 // increment the pointer value) are different! This is because we
10357 // require the next load to appear to be aligned, even though it
10358 // is actually offset from the base pointer by a lesser amount.
10359 int IncOffset = VT.getSizeInBits() / 8;
10360 int IncValue = IncOffset;
10362 // Walk (both up and down) the chain looking for another load at the real
10363 // (aligned) offset (the alignment of the other load does not matter in
10364 // this case). If found, then do not use the offset reduction trick, as
10365 // that will prevent the loads from being later combined (as they would
10366 // otherwise be duplicates).
10367 if (!findConsecutiveLoad(LD, DAG))
10370 SDValue Increment =
10371 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10372 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10374 MachineMemOperand *ExtraMMO =
10375 MF.getMachineMemOperand(LD->getMemOperand(),
10376 1, 2*MemVT.getStoreSize()-1);
10377 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10378 SDValue ExtraLoad =
10379 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10380 DAG.getVTList(PermTy, MVT::Other),
10381 ExtraLoadOps, LDTy, ExtraMMO);
10383 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10384 BaseLoad.getValue(1), ExtraLoad.getValue(1));
10386 // Because vperm has a big-endian bias, we must reverse the order
10387 // of the input vectors and complement the permute control vector
10388 // when generating little endian code. We have already handled the
10389 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10390 // and ExtraLoad here.
10392 if (isLittleEndian)
10393 Perm = BuildIntrinsicOp(IntrPerm,
10394 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10396 Perm = BuildIntrinsicOp(IntrPerm,
10397 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10400 Perm = Subtarget.hasAltivec() ?
10401 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10402 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10403 DAG.getTargetConstant(1, dl, MVT::i64));
10404 // second argument is 1 because this rounding
10405 // is always exact.
10407 // The output of the permutation is our loaded result, the TokenFactor is
10409 DCI.CombineTo(N, Perm, TF);
10410 return SDValue(N, 0);
10414 case ISD::INTRINSIC_WO_CHAIN: {
10415 bool isLittleEndian = Subtarget.isLittleEndian();
10416 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10417 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10418 : Intrinsic::ppc_altivec_lvsl);
10419 if ((IID == Intr ||
10420 IID == Intrinsic::ppc_qpx_qvlpcld ||
10421 IID == Intrinsic::ppc_qpx_qvlpcls) &&
10422 N->getOperand(1)->getOpcode() == ISD::ADD) {
10423 SDValue Add = N->getOperand(1);
10425 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10426 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10428 if (DAG.MaskedValueIsZero(
10429 Add->getOperand(1),
10430 APInt::getAllOnesValue(Bits /* alignment */)
10432 Add.getValueType().getScalarType().getSizeInBits()))) {
10433 SDNode *BasePtr = Add->getOperand(0).getNode();
10434 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10435 UE = BasePtr->use_end();
10437 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10438 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10439 // We've found another LVSL/LVSR, and this address is an aligned
10440 // multiple of that one. The results will be the same, so use the
10441 // one we've just found instead.
10443 return SDValue(*UI, 0);
10448 if (isa<ConstantSDNode>(Add->getOperand(1))) {
10449 SDNode *BasePtr = Add->getOperand(0).getNode();
10450 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10451 UE = BasePtr->use_end(); UI != UE; ++UI) {
10452 if (UI->getOpcode() == ISD::ADD &&
10453 isa<ConstantSDNode>(UI->getOperand(1)) &&
10454 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10455 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10456 (1ULL << Bits) == 0) {
10457 SDNode *OtherAdd = *UI;
10458 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10459 VE = OtherAdd->use_end(); VI != VE; ++VI) {
10460 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10461 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10462 return SDValue(*VI, 0);
10472 case ISD::INTRINSIC_W_CHAIN: {
10473 // For little endian, VSX loads require generating lxvd2x/xxswapd.
10474 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10475 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10478 case Intrinsic::ppc_vsx_lxvw4x:
10479 case Intrinsic::ppc_vsx_lxvd2x:
10480 return expandVSXLoadForLE(N, DCI);
10485 case ISD::INTRINSIC_VOID: {
10486 // For little endian, VSX stores require generating xxswapd/stxvd2x.
10487 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10488 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10491 case Intrinsic::ppc_vsx_stxvw4x:
10492 case Intrinsic::ppc_vsx_stxvd2x:
10493 return expandVSXStoreForLE(N, DCI);
10499 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10500 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10501 N->getOperand(0).hasOneUse() &&
10502 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10503 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10504 N->getValueType(0) == MVT::i64))) {
10505 SDValue Load = N->getOperand(0);
10506 LoadSDNode *LD = cast<LoadSDNode>(Load);
10507 // Create the byte-swapping load.
10509 LD->getChain(), // Chain
10510 LD->getBasePtr(), // Ptr
10511 DAG.getValueType(N->getValueType(0)) // VT
10514 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10515 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10516 MVT::i64 : MVT::i32, MVT::Other),
10517 Ops, LD->getMemoryVT(), LD->getMemOperand());
10519 // If this is an i16 load, insert the truncate.
10520 SDValue ResVal = BSLoad;
10521 if (N->getValueType(0) == MVT::i16)
10522 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10524 // First, combine the bswap away. This makes the value produced by the
10526 DCI.CombineTo(N, ResVal);
10528 // Next, combine the load away, we give it a bogus result value but a real
10529 // chain result. The result value is dead because the bswap is dead.
10530 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10532 // Return N so it doesn't get rechecked!
10533 return SDValue(N, 0);
10537 case PPCISD::VCMP: {
10538 // If a VCMPo node already exists with exactly the same operands as this
10539 // node, use its result instead of this node (VCMPo computes both a CR6 and
10540 // a normal output).
10542 if (!N->getOperand(0).hasOneUse() &&
10543 !N->getOperand(1).hasOneUse() &&
10544 !N->getOperand(2).hasOneUse()) {
10546 // Scan all of the users of the LHS, looking for VCMPo's that match.
10547 SDNode *VCMPoNode = nullptr;
10549 SDNode *LHSN = N->getOperand(0).getNode();
10550 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10552 if (UI->getOpcode() == PPCISD::VCMPo &&
10553 UI->getOperand(1) == N->getOperand(1) &&
10554 UI->getOperand(2) == N->getOperand(2) &&
10555 UI->getOperand(0) == N->getOperand(0)) {
10560 // If there is no VCMPo node, or if the flag value has a single use, don't
10562 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10565 // Look at the (necessarily single) use of the flag value. If it has a
10566 // chain, this transformation is more complex. Note that multiple things
10567 // could use the value result, which we should ignore.
10568 SDNode *FlagUser = nullptr;
10569 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10570 FlagUser == nullptr; ++UI) {
10571 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10572 SDNode *User = *UI;
10573 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10574 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10581 // If the user is a MFOCRF instruction, we know this is safe.
10582 // Otherwise we give up for right now.
10583 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10584 return SDValue(VCMPoNode, 0);
10588 case ISD::BRCOND: {
10589 SDValue Cond = N->getOperand(1);
10590 SDValue Target = N->getOperand(2);
10592 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10593 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10594 Intrinsic::ppc_is_decremented_ctr_nonzero) {
10596 // We now need to make the intrinsic dead (it cannot be instruction
10598 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10599 assert(Cond.getNode()->hasOneUse() &&
10600 "Counter decrement has more than one use");
10602 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10603 N->getOperand(0), Target);
10608 // If this is a branch on an altivec predicate comparison, lower this so
10609 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
10610 // lowering is done pre-legalize, because the legalizer lowers the predicate
10611 // compare down to code that is difficult to reassemble.
10612 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10613 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10615 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10616 // value. If so, pass-through the AND to get to the intrinsic.
10617 if (LHS.getOpcode() == ISD::AND &&
10618 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10619 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10620 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10621 isa<ConstantSDNode>(LHS.getOperand(1)) &&
10622 !isNullConstant(LHS.getOperand(1)))
10623 LHS = LHS.getOperand(0);
10625 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10626 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10627 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10628 isa<ConstantSDNode>(RHS)) {
10629 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10630 "Counter decrement comparison is not EQ or NE");
10632 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10633 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10634 (CC == ISD::SETNE && !Val);
10636 // We now need to make the intrinsic dead (it cannot be instruction
10638 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10639 assert(LHS.getNode()->hasOneUse() &&
10640 "Counter decrement has more than one use");
10642 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10643 N->getOperand(0), N->getOperand(4));
10649 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10650 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10651 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10652 assert(isDot && "Can't compare against a vector result!");
10654 // If this is a comparison against something other than 0/1, then we know
10655 // that the condition is never/always true.
10656 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10657 if (Val != 0 && Val != 1) {
10658 if (CC == ISD::SETEQ) // Cond never true, remove branch.
10659 return N->getOperand(0);
10660 // Always !=, turn it into an unconditional branch.
10661 return DAG.getNode(ISD::BR, dl, MVT::Other,
10662 N->getOperand(0), N->getOperand(4));
10665 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10667 // Create the PPCISD altivec 'dot' comparison node.
10669 LHS.getOperand(2), // LHS of compare
10670 LHS.getOperand(3), // RHS of compare
10671 DAG.getConstant(CompareOpc, dl, MVT::i32)
10673 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10674 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10676 // Unpack the result based on how the target uses it.
10677 PPC::Predicate CompOpc;
10678 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10679 default: // Can't happen, don't crash on invalid number though.
10680 case 0: // Branch on the value of the EQ bit of CR6.
10681 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10683 case 1: // Branch on the inverted value of the EQ bit of CR6.
10684 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10686 case 2: // Branch on the value of the LT bit of CR6.
10687 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10689 case 3: // Branch on the inverted value of the LT bit of CR6.
10690 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10694 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10695 DAG.getConstant(CompOpc, dl, MVT::i32),
10696 DAG.getRegister(PPC::CR6, MVT::i32),
10697 N->getOperand(4), CompNode.getValue(1));
10707 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10709 std::vector<SDNode *> *Created) const {
10710 // fold (sdiv X, pow2)
10711 EVT VT = N->getValueType(0);
10712 if (VT == MVT::i64 && !Subtarget.isPPC64())
10714 if ((VT != MVT::i32 && VT != MVT::i64) ||
10715 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10719 SDValue N0 = N->getOperand(0);
10721 bool IsNegPow2 = (-Divisor).isPowerOf2();
10722 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10723 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
10725 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10727 Created->push_back(Op.getNode());
10730 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10732 Created->push_back(Op.getNode());
10738 //===----------------------------------------------------------------------===//
10739 // Inline Assembly Support
10740 //===----------------------------------------------------------------------===//
10742 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10745 const SelectionDAG &DAG,
10746 unsigned Depth) const {
10747 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10748 switch (Op.getOpcode()) {
10750 case PPCISD::LBRX: {
10751 // lhbrx is known to have the top bits cleared out.
10752 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10753 KnownZero = 0xFFFF0000;
10756 case ISD::INTRINSIC_WO_CHAIN: {
10757 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10759 case Intrinsic::ppc_altivec_vcmpbfp_p:
10760 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10761 case Intrinsic::ppc_altivec_vcmpequb_p:
10762 case Intrinsic::ppc_altivec_vcmpequh_p:
10763 case Intrinsic::ppc_altivec_vcmpequw_p:
10764 case Intrinsic::ppc_altivec_vcmpequd_p:
10765 case Intrinsic::ppc_altivec_vcmpgefp_p:
10766 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10767 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10768 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10769 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10770 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10771 case Intrinsic::ppc_altivec_vcmpgtub_p:
10772 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10773 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10774 case Intrinsic::ppc_altivec_vcmpgtud_p:
10775 KnownZero = ~1U; // All bits but the low one are known to be zero.
10782 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10783 switch (Subtarget.getDarwinDirective()) {
10786 case PPC::DIR_PWR4:
10787 case PPC::DIR_PWR5:
10788 case PPC::DIR_PWR5X:
10789 case PPC::DIR_PWR6:
10790 case PPC::DIR_PWR6X:
10791 case PPC::DIR_PWR7:
10792 case PPC::DIR_PWR8: {
10796 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10798 // For small loops (between 5 and 8 instructions), align to a 32-byte
10799 // boundary so that the entire loop fits in one instruction-cache line.
10800 uint64_t LoopSize = 0;
10801 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10802 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10803 LoopSize += TII->GetInstSizeInBytes(J);
10805 if (LoopSize > 16 && LoopSize <= 32)
10812 return TargetLowering::getPrefLoopAlignment(ML);
10815 /// getConstraintType - Given a constraint, return the type of
10816 /// constraint it is for this target.
10817 PPCTargetLowering::ConstraintType
10818 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
10819 if (Constraint.size() == 1) {
10820 switch (Constraint[0]) {
10827 return C_RegisterClass;
10829 // FIXME: While Z does indicate a memory constraint, it specifically
10830 // indicates an r+r address (used in conjunction with the 'y' modifier
10831 // in the replacement string). Currently, we're forcing the base
10832 // register to be r0 in the asm printer (which is interpreted as zero)
10833 // and forming the complete address in the second register. This is
10837 } else if (Constraint == "wc") { // individual CR bits.
10838 return C_RegisterClass;
10839 } else if (Constraint == "wa" || Constraint == "wd" ||
10840 Constraint == "wf" || Constraint == "ws") {
10841 return C_RegisterClass; // VSX registers.
10843 return TargetLowering::getConstraintType(Constraint);
10846 /// Examine constraint type and operand type and determine a weight value.
10847 /// This object must already have been set up with the operand type
10848 /// and the current alternative constraint selected.
10849 TargetLowering::ConstraintWeight
10850 PPCTargetLowering::getSingleConstraintMatchWeight(
10851 AsmOperandInfo &info, const char *constraint) const {
10852 ConstraintWeight weight = CW_Invalid;
10853 Value *CallOperandVal = info.CallOperandVal;
10854 // If we don't have a value, we can't do a match,
10855 // but allow it at the lowest weight.
10856 if (!CallOperandVal)
10858 Type *type = CallOperandVal->getType();
10860 // Look at the constraint type.
10861 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10862 return CW_Register; // an individual CR bit.
10863 else if ((StringRef(constraint) == "wa" ||
10864 StringRef(constraint) == "wd" ||
10865 StringRef(constraint) == "wf") &&
10866 type->isVectorTy())
10867 return CW_Register;
10868 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10869 return CW_Register;
10871 switch (*constraint) {
10873 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10876 if (type->isIntegerTy())
10877 weight = CW_Register;
10880 if (type->isFloatTy())
10881 weight = CW_Register;
10884 if (type->isDoubleTy())
10885 weight = CW_Register;
10888 if (type->isVectorTy())
10889 weight = CW_Register;
10892 weight = CW_Register;
10895 weight = CW_Memory;
10901 std::pair<unsigned, const TargetRegisterClass *>
10902 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10903 StringRef Constraint,
10905 if (Constraint.size() == 1) {
10906 // GCC RS6000 Constraint Letters
10907 switch (Constraint[0]) {
10908 case 'b': // R1-R31
10909 if (VT == MVT::i64 && Subtarget.isPPC64())
10910 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10911 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10912 case 'r': // R0-R31
10913 if (VT == MVT::i64 && Subtarget.isPPC64())
10914 return std::make_pair(0U, &PPC::G8RCRegClass);
10915 return std::make_pair(0U, &PPC::GPRCRegClass);
10917 if (VT == MVT::f32 || VT == MVT::i32)
10918 return std::make_pair(0U, &PPC::F4RCRegClass);
10919 if (VT == MVT::f64 || VT == MVT::i64)
10920 return std::make_pair(0U, &PPC::F8RCRegClass);
10921 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10922 return std::make_pair(0U, &PPC::QFRCRegClass);
10923 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10924 return std::make_pair(0U, &PPC::QSRCRegClass);
10927 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10928 return std::make_pair(0U, &PPC::QFRCRegClass);
10929 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10930 return std::make_pair(0U, &PPC::QSRCRegClass);
10931 if (Subtarget.hasAltivec())
10932 return std::make_pair(0U, &PPC::VRRCRegClass);
10934 return std::make_pair(0U, &PPC::CRRCRegClass);
10936 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
10937 // An individual CR bit.
10938 return std::make_pair(0U, &PPC::CRBITRCRegClass);
10939 } else if ((Constraint == "wa" || Constraint == "wd" ||
10940 Constraint == "wf") && Subtarget.hasVSX()) {
10941 return std::make_pair(0U, &PPC::VSRCRegClass);
10942 } else if (Constraint == "ws" && Subtarget.hasVSX()) {
10943 if (VT == MVT::f32 && Subtarget.hasP8Vector())
10944 return std::make_pair(0U, &PPC::VSSRCRegClass);
10946 return std::make_pair(0U, &PPC::VSFRCRegClass);
10949 std::pair<unsigned, const TargetRegisterClass *> R =
10950 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10952 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10953 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10954 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10956 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10957 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10958 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10959 PPC::GPRCRegClass.contains(R.first))
10960 return std::make_pair(TRI->getMatchingSuperReg(R.first,
10961 PPC::sub_32, &PPC::G8RCRegClass),
10962 &PPC::G8RCRegClass);
10964 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10965 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10966 R.first = PPC::CR0;
10967 R.second = &PPC::CRRCRegClass;
10973 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10974 /// vector. If it is invalid, don't add anything to Ops.
10975 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10976 std::string &Constraint,
10977 std::vector<SDValue>&Ops,
10978 SelectionDAG &DAG) const {
10981 // Only support length 1 constraints.
10982 if (Constraint.length() > 1) return;
10984 char Letter = Constraint[0];
10995 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10996 if (!CST) return; // Must be an immediate to match.
10998 int64_t Value = CST->getSExtValue();
10999 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11000 // numbers are printed as such.
11002 default: llvm_unreachable("Unknown constraint letter!");
11003 case 'I': // "I" is a signed 16-bit constant.
11004 if (isInt<16>(Value))
11005 Result = DAG.getTargetConstant(Value, dl, TCVT);
11007 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
11008 if (isShiftedUInt<16, 16>(Value))
11009 Result = DAG.getTargetConstant(Value, dl, TCVT);
11011 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
11012 if (isShiftedInt<16, 16>(Value))
11013 Result = DAG.getTargetConstant(Value, dl, TCVT);
11015 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
11016 if (isUInt<16>(Value))
11017 Result = DAG.getTargetConstant(Value, dl, TCVT);
11019 case 'M': // "M" is a constant that is greater than 31.
11021 Result = DAG.getTargetConstant(Value, dl, TCVT);
11023 case 'N': // "N" is a positive constant that is an exact power of two.
11024 if (Value > 0 && isPowerOf2_64(Value))
11025 Result = DAG.getTargetConstant(Value, dl, TCVT);
11027 case 'O': // "O" is the constant zero.
11029 Result = DAG.getTargetConstant(Value, dl, TCVT);
11031 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
11032 if (isInt<16>(-Value))
11033 Result = DAG.getTargetConstant(Value, dl, TCVT);
11040 if (Result.getNode()) {
11041 Ops.push_back(Result);
11045 // Handle standard constraint letters.
11046 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11049 // isLegalAddressingMode - Return true if the addressing mode represented
11050 // by AM is legal for this target, for a load/store of the specified type.
11051 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11052 const AddrMode &AM, Type *Ty,
11053 unsigned AS) const {
11054 // PPC does not allow r+i addressing modes for vectors!
11055 if (Ty->isVectorTy() && AM.BaseOffs != 0)
11058 // PPC allows a sign-extended 16-bit immediate field.
11059 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11062 // No global is ever allowed as a base.
11066 // PPC only support r+r,
11067 switch (AM.Scale) {
11068 case 0: // "r+i" or just "i", depending on HasBaseReg.
11071 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
11073 // Otherwise we have r+r or r+i.
11076 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
11078 // Allow 2*r as r+r.
11081 // No other scales are supported.
11088 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11089 SelectionDAG &DAG) const {
11090 MachineFunction &MF = DAG.getMachineFunction();
11091 MachineFrameInfo *MFI = MF.getFrameInfo();
11092 MFI->setReturnAddressIsTaken(true);
11094 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11098 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11100 // Make sure the function does not optimize away the store of the RA to
11102 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11103 FuncInfo->setLRStoreRequired();
11104 bool isPPC64 = Subtarget.isPPC64();
11105 auto PtrVT = getPointerTy(MF.getDataLayout());
11108 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11110 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11111 isPPC64 ? MVT::i64 : MVT::i32);
11112 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11113 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11114 MachinePointerInfo(), false, false, false, 0);
11117 // Just load the return address off the stack.
11118 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11119 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11120 MachinePointerInfo(), false, false, false, 0);
11123 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11124 SelectionDAG &DAG) const {
11126 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11128 MachineFunction &MF = DAG.getMachineFunction();
11129 MachineFrameInfo *MFI = MF.getFrameInfo();
11130 MFI->setFrameAddressIsTaken(true);
11132 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
11133 bool isPPC64 = PtrVT == MVT::i64;
11135 // Naked functions never have a frame pointer, and so we use r1. For all
11136 // other functions, this decision must be delayed until during PEI.
11138 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11139 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11141 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11143 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11146 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11147 FrameAddr, MachinePointerInfo(), false, false,
11152 // FIXME? Maybe this could be a TableGen attribute on some registers and
11153 // this table could be generated automatically from RegInfo.
11154 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11155 SelectionDAG &DAG) const {
11156 bool isPPC64 = Subtarget.isPPC64();
11157 bool isDarwinABI = Subtarget.isDarwinABI();
11159 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11160 (!isPPC64 && VT != MVT::i32))
11161 report_fatal_error("Invalid register global variable type");
11163 bool is64Bit = isPPC64 && VT == MVT::i64;
11164 unsigned Reg = StringSwitch<unsigned>(RegName)
11165 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11166 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11167 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11168 (is64Bit ? PPC::X13 : PPC::R13))
11173 report_fatal_error("Invalid register name global variable");
11177 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11178 // The PowerPC target isn't yet aware of offsets.
11182 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11184 unsigned Intrinsic) const {
11186 switch (Intrinsic) {
11187 case Intrinsic::ppc_qpx_qvlfd:
11188 case Intrinsic::ppc_qpx_qvlfs:
11189 case Intrinsic::ppc_qpx_qvlfcd:
11190 case Intrinsic::ppc_qpx_qvlfcs:
11191 case Intrinsic::ppc_qpx_qvlfiwa:
11192 case Intrinsic::ppc_qpx_qvlfiwz:
11193 case Intrinsic::ppc_altivec_lvx:
11194 case Intrinsic::ppc_altivec_lvxl:
11195 case Intrinsic::ppc_altivec_lvebx:
11196 case Intrinsic::ppc_altivec_lvehx:
11197 case Intrinsic::ppc_altivec_lvewx:
11198 case Intrinsic::ppc_vsx_lxvd2x:
11199 case Intrinsic::ppc_vsx_lxvw4x: {
11201 switch (Intrinsic) {
11202 case Intrinsic::ppc_altivec_lvebx:
11205 case Intrinsic::ppc_altivec_lvehx:
11208 case Intrinsic::ppc_altivec_lvewx:
11211 case Intrinsic::ppc_vsx_lxvd2x:
11214 case Intrinsic::ppc_qpx_qvlfd:
11217 case Intrinsic::ppc_qpx_qvlfs:
11220 case Intrinsic::ppc_qpx_qvlfcd:
11223 case Intrinsic::ppc_qpx_qvlfcs:
11231 Info.opc = ISD::INTRINSIC_W_CHAIN;
11233 Info.ptrVal = I.getArgOperand(0);
11234 Info.offset = -VT.getStoreSize()+1;
11235 Info.size = 2*VT.getStoreSize()-1;
11238 Info.readMem = true;
11239 Info.writeMem = false;
11242 case Intrinsic::ppc_qpx_qvlfda:
11243 case Intrinsic::ppc_qpx_qvlfsa:
11244 case Intrinsic::ppc_qpx_qvlfcda:
11245 case Intrinsic::ppc_qpx_qvlfcsa:
11246 case Intrinsic::ppc_qpx_qvlfiwaa:
11247 case Intrinsic::ppc_qpx_qvlfiwza: {
11249 switch (Intrinsic) {
11250 case Intrinsic::ppc_qpx_qvlfda:
11253 case Intrinsic::ppc_qpx_qvlfsa:
11256 case Intrinsic::ppc_qpx_qvlfcda:
11259 case Intrinsic::ppc_qpx_qvlfcsa:
11267 Info.opc = ISD::INTRINSIC_W_CHAIN;
11269 Info.ptrVal = I.getArgOperand(0);
11271 Info.size = VT.getStoreSize();
11274 Info.readMem = true;
11275 Info.writeMem = false;
11278 case Intrinsic::ppc_qpx_qvstfd:
11279 case Intrinsic::ppc_qpx_qvstfs:
11280 case Intrinsic::ppc_qpx_qvstfcd:
11281 case Intrinsic::ppc_qpx_qvstfcs:
11282 case Intrinsic::ppc_qpx_qvstfiw:
11283 case Intrinsic::ppc_altivec_stvx:
11284 case Intrinsic::ppc_altivec_stvxl:
11285 case Intrinsic::ppc_altivec_stvebx:
11286 case Intrinsic::ppc_altivec_stvehx:
11287 case Intrinsic::ppc_altivec_stvewx:
11288 case Intrinsic::ppc_vsx_stxvd2x:
11289 case Intrinsic::ppc_vsx_stxvw4x: {
11291 switch (Intrinsic) {
11292 case Intrinsic::ppc_altivec_stvebx:
11295 case Intrinsic::ppc_altivec_stvehx:
11298 case Intrinsic::ppc_altivec_stvewx:
11301 case Intrinsic::ppc_vsx_stxvd2x:
11304 case Intrinsic::ppc_qpx_qvstfd:
11307 case Intrinsic::ppc_qpx_qvstfs:
11310 case Intrinsic::ppc_qpx_qvstfcd:
11313 case Intrinsic::ppc_qpx_qvstfcs:
11321 Info.opc = ISD::INTRINSIC_VOID;
11323 Info.ptrVal = I.getArgOperand(1);
11324 Info.offset = -VT.getStoreSize()+1;
11325 Info.size = 2*VT.getStoreSize()-1;
11328 Info.readMem = false;
11329 Info.writeMem = true;
11332 case Intrinsic::ppc_qpx_qvstfda:
11333 case Intrinsic::ppc_qpx_qvstfsa:
11334 case Intrinsic::ppc_qpx_qvstfcda:
11335 case Intrinsic::ppc_qpx_qvstfcsa:
11336 case Intrinsic::ppc_qpx_qvstfiwa: {
11338 switch (Intrinsic) {
11339 case Intrinsic::ppc_qpx_qvstfda:
11342 case Intrinsic::ppc_qpx_qvstfsa:
11345 case Intrinsic::ppc_qpx_qvstfcda:
11348 case Intrinsic::ppc_qpx_qvstfcsa:
11356 Info.opc = ISD::INTRINSIC_VOID;
11358 Info.ptrVal = I.getArgOperand(1);
11360 Info.size = VT.getStoreSize();
11363 Info.readMem = false;
11364 Info.writeMem = true;
11374 /// getOptimalMemOpType - Returns the target specific optimal type for load
11375 /// and store operations as a result of memset, memcpy, and memmove
11376 /// lowering. If DstAlign is zero that means it's safe to destination
11377 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11378 /// means there isn't a need to check it against alignment requirement,
11379 /// probably because the source does not need to be loaded. If 'IsMemset' is
11380 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11381 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11382 /// source is constant so it does not need to be loaded.
11383 /// It returns EVT::Other if the type should be determined using generic
11384 /// target-independent logic.
11385 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11386 unsigned DstAlign, unsigned SrcAlign,
11387 bool IsMemset, bool ZeroMemset,
11389 MachineFunction &MF) const {
11390 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11391 const Function *F = MF.getFunction();
11392 // When expanding a memset, require at least two QPX instructions to cover
11393 // the cost of loading the value to be stored from the constant pool.
11394 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11395 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11396 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11400 // We should use Altivec/VSX loads and stores when available. For unaligned
11401 // addresses, unaligned VSX loads are only fast starting with the P8.
11402 if (Subtarget.hasAltivec() && Size >= 16 &&
11403 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11404 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11408 if (Subtarget.isPPC64()) {
11415 /// \brief Returns true if it is beneficial to convert a load of a constant
11416 /// to just the constant itself.
11417 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11419 assert(Ty->isIntegerTy());
11421 unsigned BitSize = Ty->getPrimitiveSizeInBits();
11422 if (BitSize == 0 || BitSize > 64)
11427 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11428 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11430 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11431 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11432 return NumBits1 == 64 && NumBits2 == 32;
11435 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11436 if (!VT1.isInteger() || !VT2.isInteger())
11438 unsigned NumBits1 = VT1.getSizeInBits();
11439 unsigned NumBits2 = VT2.getSizeInBits();
11440 return NumBits1 == 64 && NumBits2 == 32;
11443 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11444 // Generally speaking, zexts are not free, but they are free when they can be
11445 // folded with other operations.
11446 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11447 EVT MemVT = LD->getMemoryVT();
11448 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11449 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11450 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11451 LD->getExtensionType() == ISD::ZEXTLOAD))
11455 // FIXME: Add other cases...
11456 // - 32-bit shifts with a zext to i64
11457 // - zext after ctlz, bswap, etc.
11458 // - zext after and by a constant mask
11460 return TargetLowering::isZExtFree(Val, VT2);
11463 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11464 assert(VT.isFloatingPoint());
11468 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11469 return isInt<16>(Imm) || isUInt<16>(Imm);
11472 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11473 return isInt<16>(Imm) || isUInt<16>(Imm);
11476 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11479 bool *Fast) const {
11480 if (DisablePPCUnaligned)
11483 // PowerPC supports unaligned memory access for simple non-vector types.
11484 // Although accessing unaligned addresses is not as efficient as accessing
11485 // aligned addresses, it is generally more efficient than manual expansion,
11486 // and generally only traps for software emulation when crossing page
11489 if (!VT.isSimple())
11492 if (VT.getSimpleVT().isVector()) {
11493 if (Subtarget.hasVSX()) {
11494 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11495 VT != MVT::v4f32 && VT != MVT::v4i32)
11502 if (VT == MVT::ppcf128)
11511 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11512 VT = VT.getScalarType();
11514 if (!VT.isSimple())
11517 switch (VT.getSimpleVT().SimpleTy) {
11529 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11530 // LR is a callee-save register, but we must treat it as clobbered by any call
11531 // site. Hence we include LR in the scratch registers, which are in turn added
11532 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11533 // to CTR, which is used by any indirect call.
11534 static const MCPhysReg ScratchRegs[] = {
11535 PPC::X12, PPC::LR8, PPC::CTR8, 0
11538 return ScratchRegs;
11541 unsigned PPCTargetLowering::getExceptionPointerRegister(
11542 const Constant *PersonalityFn) const {
11543 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
11546 unsigned PPCTargetLowering::getExceptionSelectorRegister(
11547 const Constant *PersonalityFn) const {
11548 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
11552 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11553 EVT VT , unsigned DefinedValues) const {
11554 if (VT == MVT::v2i64)
11555 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
11557 if (Subtarget.hasQPX()) {
11558 if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11562 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11565 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11566 if (DisableILPPref || Subtarget.enableMachineScheduler())
11567 return TargetLowering::getSchedulingPreference(N);
11572 // Create a fast isel object.
11574 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11575 const TargetLibraryInfo *LibInfo) const {
11576 return PPC::createFastISel(FuncInfo, LibInfo);