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);
333 // We want to custom lower some of our intrinsics.
334 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
336 // To handle counter-based loop conditions.
337 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
339 // Comparisons that require checking two conditions.
340 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
341 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
343 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
345 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
347 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
349 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
351 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
353 if (Subtarget.has64BitSupport()) {
354 // They also have instructions for converting between i64 and fp.
355 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
356 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
357 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
358 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
359 // This is just the low 32 bits of a (signed) fp->i64 conversion.
360 // We cannot do this with Promote because i64 is not a legal type.
361 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
363 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
364 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
366 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
367 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
370 // With the instructions enabled under FPCVT, we can do everything.
371 if (Subtarget.hasFPCVT()) {
372 if (Subtarget.has64BitSupport()) {
373 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
374 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
375 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
376 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
379 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
380 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
381 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
382 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
385 if (Subtarget.use64BitRegs()) {
386 // 64-bit PowerPC implementations can support i64 types directly
387 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
388 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
389 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
390 // 64-bit PowerPC wants to expand i128 shifts itself.
391 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
393 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
395 // 32-bit PowerPC wants to expand i64 shifts itself.
396 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
398 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
401 if (Subtarget.hasAltivec()) {
402 // First set operation action for all vector types to expand. Then we
403 // will selectively turn on ones that can be effectively codegen'd.
404 for (MVT VT : MVT::vector_valuetypes()) {
405 // add/sub are legal for all supported vector VT's.
406 // This check is temporary until support for quadword add/sub is added
407 if (VT.SimpleTy != MVT::v1i128) {
408 setOperationAction(ISD::ADD , VT, Legal);
409 setOperationAction(ISD::SUB , VT, Legal);
412 setOperationAction(ISD::ADD , VT, Expand);
413 setOperationAction(ISD::SUB , VT, Expand);
416 // Vector instructions introduced in P8
417 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
418 setOperationAction(ISD::CTPOP, VT, Legal);
419 setOperationAction(ISD::CTLZ, VT, Legal);
422 setOperationAction(ISD::CTPOP, VT, Expand);
423 setOperationAction(ISD::CTLZ, VT, Expand);
426 // We promote all shuffles to v16i8.
427 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
428 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
430 // We promote all non-typed operations to v4i32.
431 setOperationAction(ISD::AND , VT, Promote);
432 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
433 setOperationAction(ISD::OR , VT, Promote);
434 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
435 setOperationAction(ISD::XOR , VT, Promote);
436 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
437 setOperationAction(ISD::LOAD , VT, Promote);
438 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
439 setOperationAction(ISD::SELECT, VT, Promote);
440 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
441 setOperationAction(ISD::STORE, VT, Promote);
442 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
444 // No other operations are legal.
445 setOperationAction(ISD::MUL , VT, Expand);
446 setOperationAction(ISD::SDIV, VT, Expand);
447 setOperationAction(ISD::SREM, VT, Expand);
448 setOperationAction(ISD::UDIV, VT, Expand);
449 setOperationAction(ISD::UREM, VT, Expand);
450 setOperationAction(ISD::FDIV, VT, Expand);
451 setOperationAction(ISD::FREM, VT, Expand);
452 setOperationAction(ISD::FNEG, VT, Expand);
453 setOperationAction(ISD::FSQRT, VT, Expand);
454 setOperationAction(ISD::FLOG, VT, Expand);
455 setOperationAction(ISD::FLOG10, VT, Expand);
456 setOperationAction(ISD::FLOG2, VT, Expand);
457 setOperationAction(ISD::FEXP, VT, Expand);
458 setOperationAction(ISD::FEXP2, VT, Expand);
459 setOperationAction(ISD::FSIN, VT, Expand);
460 setOperationAction(ISD::FCOS, VT, Expand);
461 setOperationAction(ISD::FABS, VT, Expand);
462 setOperationAction(ISD::FPOWI, VT, Expand);
463 setOperationAction(ISD::FFLOOR, VT, Expand);
464 setOperationAction(ISD::FCEIL, VT, Expand);
465 setOperationAction(ISD::FTRUNC, VT, Expand);
466 setOperationAction(ISD::FRINT, VT, Expand);
467 setOperationAction(ISD::FNEARBYINT, VT, Expand);
468 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
469 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
470 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
471 setOperationAction(ISD::MULHU, VT, Expand);
472 setOperationAction(ISD::MULHS, VT, Expand);
473 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
474 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
475 setOperationAction(ISD::UDIVREM, VT, Expand);
476 setOperationAction(ISD::SDIVREM, VT, Expand);
477 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
478 setOperationAction(ISD::FPOW, VT, Expand);
479 setOperationAction(ISD::BSWAP, VT, Expand);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
481 setOperationAction(ISD::CTTZ, VT, Expand);
482 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
483 setOperationAction(ISD::VSELECT, VT, Expand);
484 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
486 for (MVT InnerVT : MVT::vector_valuetypes()) {
487 setTruncStoreAction(VT, InnerVT, Expand);
488 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
489 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
490 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
494 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
495 // with merges, splats, etc.
496 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
498 setOperationAction(ISD::AND , MVT::v4i32, Legal);
499 setOperationAction(ISD::OR , MVT::v4i32, Legal);
500 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
501 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
502 setOperationAction(ISD::SELECT, MVT::v4i32,
503 Subtarget.useCRBits() ? Legal : Expand);
504 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
505 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
506 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
507 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
508 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
509 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
510 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
511 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
512 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
514 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
515 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
516 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
517 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
519 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
520 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
522 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
523 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
524 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
528 if (Subtarget.hasP8Altivec())
529 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
531 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
533 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
534 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
536 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
537 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
539 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
540 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
541 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
542 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
544 // Altivec does not contain unordered floating-point compare instructions
545 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
546 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
547 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
548 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
550 if (Subtarget.hasVSX()) {
551 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
552 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
554 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
555 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
556 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
557 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
558 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
560 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
562 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
563 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
565 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
566 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
568 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
569 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
570 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
571 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
572 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
574 // Share the Altivec comparison restrictions.
575 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
576 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
577 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
578 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
580 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
581 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
583 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
585 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
587 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
588 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
590 if (Subtarget.hasP8Altivec()) {
591 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
592 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
593 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
595 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
598 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
599 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
600 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
602 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
604 // VSX v2i64 only supports non-arithmetic operations.
605 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
606 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
609 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
610 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
611 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
612 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
614 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
616 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
617 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
618 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
619 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
621 // Vector operation legalization checks the result type of
622 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
623 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
624 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
625 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
626 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
628 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
631 if (Subtarget.hasP8Altivec()) {
632 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
633 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
637 if (Subtarget.hasQPX()) {
638 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
639 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
640 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
641 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
643 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
644 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
646 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
647 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
649 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
650 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
652 if (!Subtarget.useCRBits())
653 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
654 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
656 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
657 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
658 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
659 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
660 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
661 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
662 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
664 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
665 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
667 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
668 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
669 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
671 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
672 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
673 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
674 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
675 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
676 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
677 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
678 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
679 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
680 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
681 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
683 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
684 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
686 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
687 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
689 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
691 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
692 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
693 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
694 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
696 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
697 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
699 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
700 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
702 if (!Subtarget.useCRBits())
703 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
704 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
706 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
707 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
708 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
709 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
710 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
711 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
712 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
714 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
715 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
717 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
718 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
719 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
720 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
721 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
722 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
723 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
724 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
725 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
726 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
727 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
729 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
730 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
732 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
733 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
735 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
737 setOperationAction(ISD::AND , MVT::v4i1, Legal);
738 setOperationAction(ISD::OR , MVT::v4i1, Legal);
739 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
741 if (!Subtarget.useCRBits())
742 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
743 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
745 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
746 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
748 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
749 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
750 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
751 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
752 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
753 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
754 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
756 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
757 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
759 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
761 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
762 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
763 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
764 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
766 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
767 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
768 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
769 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
771 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
772 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
774 // These need to set FE_INEXACT, and so cannot be vectorized here.
775 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
776 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
778 if (TM.Options.UnsafeFPMath) {
779 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
780 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
782 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
783 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
785 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
786 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
788 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
789 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
793 if (Subtarget.has64BitSupport())
794 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
796 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
799 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
800 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
803 setBooleanContents(ZeroOrOneBooleanContent);
805 if (Subtarget.hasAltivec()) {
806 // Altivec instructions set fields to all zeros or all ones.
807 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
811 // These libcalls are not available in 32-bit.
812 setLibcallName(RTLIB::SHL_I128, nullptr);
813 setLibcallName(RTLIB::SRL_I128, nullptr);
814 setLibcallName(RTLIB::SRA_I128, nullptr);
818 setStackPointerRegisterToSaveRestore(PPC::X1);
819 setExceptionPointerRegister(PPC::X3);
820 setExceptionSelectorRegister(PPC::X4);
822 setStackPointerRegisterToSaveRestore(PPC::R1);
823 setExceptionPointerRegister(PPC::R3);
824 setExceptionSelectorRegister(PPC::R4);
827 // We have target-specific dag combine patterns for the following nodes:
828 setTargetDAGCombine(ISD::SINT_TO_FP);
829 if (Subtarget.hasFPCVT())
830 setTargetDAGCombine(ISD::UINT_TO_FP);
831 setTargetDAGCombine(ISD::LOAD);
832 setTargetDAGCombine(ISD::STORE);
833 setTargetDAGCombine(ISD::BR_CC);
834 if (Subtarget.useCRBits())
835 setTargetDAGCombine(ISD::BRCOND);
836 setTargetDAGCombine(ISD::BSWAP);
837 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
838 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
839 setTargetDAGCombine(ISD::INTRINSIC_VOID);
841 setTargetDAGCombine(ISD::SIGN_EXTEND);
842 setTargetDAGCombine(ISD::ZERO_EXTEND);
843 setTargetDAGCombine(ISD::ANY_EXTEND);
845 if (Subtarget.useCRBits()) {
846 setTargetDAGCombine(ISD::TRUNCATE);
847 setTargetDAGCombine(ISD::SETCC);
848 setTargetDAGCombine(ISD::SELECT_CC);
851 // Use reciprocal estimates.
852 if (TM.Options.UnsafeFPMath) {
853 setTargetDAGCombine(ISD::FDIV);
854 setTargetDAGCombine(ISD::FSQRT);
857 // Darwin long double math library functions have $LDBL128 appended.
858 if (Subtarget.isDarwin()) {
859 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
860 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
861 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
862 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
863 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
864 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
865 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
866 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
867 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
868 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
871 // With 32 condition bits, we don't need to sink (and duplicate) compares
872 // aggressively in CodeGenPrep.
873 if (Subtarget.useCRBits()) {
874 setHasMultipleConditionRegisters();
875 setJumpIsExpensive();
878 setMinFunctionAlignment(2);
879 if (Subtarget.isDarwin())
880 setPrefFunctionAlignment(4);
882 switch (Subtarget.getDarwinDirective()) {
886 case PPC::DIR_E500mc:
895 setPrefFunctionAlignment(4);
896 setPrefLoopAlignment(4);
900 setInsertFencesForAtomic(true);
902 if (Subtarget.enableMachineScheduler())
903 setSchedulingPreference(Sched::Source);
905 setSchedulingPreference(Sched::Hybrid);
907 computeRegisterProperties(STI.getRegisterInfo());
909 // The Freescale cores do better with aggressive inlining of memcpy and
910 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
911 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
912 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
913 MaxStoresPerMemset = 32;
914 MaxStoresPerMemsetOptSize = 16;
915 MaxStoresPerMemcpy = 32;
916 MaxStoresPerMemcpyOptSize = 8;
917 MaxStoresPerMemmove = 32;
918 MaxStoresPerMemmoveOptSize = 8;
919 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
920 // The A2 also benefits from (very) aggressive inlining of memcpy and
921 // friends. The overhead of a the function call, even when warm, can be
922 // over one hundred cycles.
923 MaxStoresPerMemset = 128;
924 MaxStoresPerMemcpy = 128;
925 MaxStoresPerMemmove = 128;
929 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
930 /// the desired ByVal argument alignment.
931 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
932 unsigned MaxMaxAlign) {
933 if (MaxAlign == MaxMaxAlign)
935 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
936 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
938 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
940 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
941 unsigned EltAlign = 0;
942 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
943 if (EltAlign > MaxAlign)
945 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
946 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
947 unsigned EltAlign = 0;
948 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
949 if (EltAlign > MaxAlign)
951 if (MaxAlign == MaxMaxAlign)
957 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
958 /// function arguments in the caller parameter area.
959 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
960 // Darwin passes everything on 4 byte boundary.
961 if (Subtarget.isDarwin())
964 // 16byte and wider vectors are passed on 16byte boundary.
965 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
966 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
967 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
968 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
972 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
974 default: return nullptr;
975 case PPCISD::FSEL: return "PPCISD::FSEL";
976 case PPCISD::FCFID: return "PPCISD::FCFID";
977 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
978 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
979 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
980 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
981 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
982 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
983 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
984 case PPCISD::FRE: return "PPCISD::FRE";
985 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
986 case PPCISD::STFIWX: return "PPCISD::STFIWX";
987 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
988 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
989 case PPCISD::VPERM: return "PPCISD::VPERM";
990 case PPCISD::CMPB: return "PPCISD::CMPB";
991 case PPCISD::Hi: return "PPCISD::Hi";
992 case PPCISD::Lo: return "PPCISD::Lo";
993 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
994 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
995 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
996 case PPCISD::SRL: return "PPCISD::SRL";
997 case PPCISD::SRA: return "PPCISD::SRA";
998 case PPCISD::SHL: return "PPCISD::SHL";
999 case PPCISD::CALL: return "PPCISD::CALL";
1000 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1001 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1002 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1003 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1004 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1005 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1006 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1007 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1008 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1009 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1010 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1011 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1012 case PPCISD::VCMP: return "PPCISD::VCMP";
1013 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1014 case PPCISD::LBRX: return "PPCISD::LBRX";
1015 case PPCISD::STBRX: return "PPCISD::STBRX";
1016 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1017 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1018 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1019 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1020 case PPCISD::BDZ: return "PPCISD::BDZ";
1021 case PPCISD::MFFS: return "PPCISD::MFFS";
1022 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1023 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1024 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1025 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1026 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1027 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1028 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1029 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1030 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1031 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1032 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1033 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1034 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1035 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1036 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1037 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1038 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1039 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1040 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1041 case PPCISD::SC: return "PPCISD::SC";
1042 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1043 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1044 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1045 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1046 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1047 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1051 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1053 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1055 if (Subtarget.hasQPX())
1056 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1058 return VT.changeVectorElementTypeToInteger();
1061 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1062 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1066 //===----------------------------------------------------------------------===//
1067 // Node matching predicates, for use by the tblgen matching code.
1068 //===----------------------------------------------------------------------===//
1070 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1071 static bool isFloatingPointZero(SDValue Op) {
1072 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1073 return CFP->getValueAPF().isZero();
1074 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1075 // Maybe this has already been legalized into the constant pool?
1076 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1077 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1078 return CFP->getValueAPF().isZero();
1083 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1084 /// true if Op is undef or if it matches the specified value.
1085 static bool isConstantOrUndef(int Op, int Val) {
1086 return Op < 0 || Op == Val;
1089 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1090 /// VPKUHUM instruction.
1091 /// The ShuffleKind distinguishes between big-endian operations with
1092 /// two different inputs (0), either-endian operations with two identical
1093 /// inputs (1), and little-endian operantion with two different inputs (2).
1094 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1095 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1096 SelectionDAG &DAG) {
1097 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1098 if (ShuffleKind == 0) {
1101 for (unsigned i = 0; i != 16; ++i)
1102 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1104 } else if (ShuffleKind == 2) {
1107 for (unsigned i = 0; i != 16; ++i)
1108 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1110 } else if (ShuffleKind == 1) {
1111 unsigned j = IsLE ? 0 : 1;
1112 for (unsigned i = 0; i != 8; ++i)
1113 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1114 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1120 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1121 /// VPKUWUM instruction.
1122 /// The ShuffleKind distinguishes between big-endian operations with
1123 /// two different inputs (0), either-endian operations with two identical
1124 /// inputs (1), and little-endian operantion with two different inputs (2).
1125 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1126 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1127 SelectionDAG &DAG) {
1128 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1129 if (ShuffleKind == 0) {
1132 for (unsigned i = 0; i != 16; i += 2)
1133 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1134 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1136 } else if (ShuffleKind == 2) {
1139 for (unsigned i = 0; i != 16; i += 2)
1140 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1141 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1143 } else if (ShuffleKind == 1) {
1144 unsigned j = IsLE ? 0 : 2;
1145 for (unsigned i = 0; i != 8; i += 2)
1146 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1147 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1148 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1149 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1155 /// isVMerge - Common function, used to match vmrg* shuffles.
1157 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1158 unsigned LHSStart, unsigned RHSStart) {
1159 if (N->getValueType(0) != MVT::v16i8)
1161 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1162 "Unsupported merge size!");
1164 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1165 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1166 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1167 LHSStart+j+i*UnitSize) ||
1168 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1169 RHSStart+j+i*UnitSize))
1175 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1176 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1177 /// The ShuffleKind distinguishes between big-endian merges with two
1178 /// different inputs (0), either-endian merges with two identical inputs (1),
1179 /// and little-endian merges with two different inputs (2). For the latter,
1180 /// the input operands are swapped (see PPCInstrAltivec.td).
1181 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1182 unsigned ShuffleKind, SelectionDAG &DAG) {
1183 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1184 if (ShuffleKind == 1) // unary
1185 return isVMerge(N, UnitSize, 0, 0);
1186 else if (ShuffleKind == 2) // swapped
1187 return isVMerge(N, UnitSize, 0, 16);
1191 if (ShuffleKind == 1) // unary
1192 return isVMerge(N, UnitSize, 8, 8);
1193 else if (ShuffleKind == 0) // normal
1194 return isVMerge(N, UnitSize, 8, 24);
1200 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1201 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1202 /// The ShuffleKind distinguishes between big-endian merges with two
1203 /// different inputs (0), either-endian merges with two identical inputs (1),
1204 /// and little-endian merges with two different inputs (2). For the latter,
1205 /// the input operands are swapped (see PPCInstrAltivec.td).
1206 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1207 unsigned ShuffleKind, SelectionDAG &DAG) {
1208 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1209 if (ShuffleKind == 1) // unary
1210 return isVMerge(N, UnitSize, 8, 8);
1211 else if (ShuffleKind == 2) // swapped
1212 return isVMerge(N, UnitSize, 8, 24);
1216 if (ShuffleKind == 1) // unary
1217 return isVMerge(N, UnitSize, 0, 0);
1218 else if (ShuffleKind == 0) // normal
1219 return isVMerge(N, UnitSize, 0, 16);
1226 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1227 /// amount, otherwise return -1.
1228 /// The ShuffleKind distinguishes between big-endian operations with two
1229 /// different inputs (0), either-endian operations with two identical inputs
1230 /// (1), and little-endian operations with two different inputs (2). For the
1231 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1232 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1233 SelectionDAG &DAG) {
1234 if (N->getValueType(0) != MVT::v16i8)
1237 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1239 // Find the first non-undef value in the shuffle mask.
1241 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1244 if (i == 16) return -1; // all undef.
1246 // Otherwise, check to see if the rest of the elements are consecutively
1247 // numbered from this value.
1248 unsigned ShiftAmt = SVOp->getMaskElt(i);
1249 if (ShiftAmt < i) return -1;
1252 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1254 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1255 // Check the rest of the elements to see if they are consecutive.
1256 for (++i; i != 16; ++i)
1257 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1259 } else if (ShuffleKind == 1) {
1260 // Check the rest of the elements to see if they are consecutive.
1261 for (++i; i != 16; ++i)
1262 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1267 if (ShuffleKind == 2 && isLE)
1268 ShiftAmt = 16 - ShiftAmt;
1273 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1274 /// specifies a splat of a single element that is suitable for input to
1275 /// VSPLTB/VSPLTH/VSPLTW.
1276 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1277 assert(N->getValueType(0) == MVT::v16i8 &&
1278 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1280 // This is a splat operation if each element of the permute is the same, and
1281 // if the value doesn't reference the second vector.
1282 unsigned ElementBase = N->getMaskElt(0);
1284 // FIXME: Handle UNDEF elements too!
1285 if (ElementBase >= 16)
1288 // Check that the indices are consecutive, in the case of a multi-byte element
1289 // splatted with a v16i8 mask.
1290 for (unsigned i = 1; i != EltSize; ++i)
1291 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1294 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1295 if (N->getMaskElt(i) < 0) continue;
1296 for (unsigned j = 0; j != EltSize; ++j)
1297 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1303 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1304 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1305 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1306 SelectionDAG &DAG) {
1307 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1308 assert(isSplatShuffleMask(SVOp, EltSize));
1309 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1310 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1312 return SVOp->getMaskElt(0) / EltSize;
1315 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1316 /// by using a vspltis[bhw] instruction of the specified element size, return
1317 /// the constant being splatted. The ByteSize field indicates the number of
1318 /// bytes of each element [124] -> [bhw].
1319 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1320 SDValue OpVal(nullptr, 0);
1322 // If ByteSize of the splat is bigger than the element size of the
1323 // build_vector, then we have a case where we are checking for a splat where
1324 // multiple elements of the buildvector are folded together into a single
1325 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1326 unsigned EltSize = 16/N->getNumOperands();
1327 if (EltSize < ByteSize) {
1328 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1329 SDValue UniquedVals[4];
1330 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1332 // See if all of the elements in the buildvector agree across.
1333 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1334 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1335 // If the element isn't a constant, bail fully out.
1336 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1339 if (!UniquedVals[i&(Multiple-1)].getNode())
1340 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1341 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1342 return SDValue(); // no match.
1345 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1346 // either constant or undef values that are identical for each chunk. See
1347 // if these chunks can form into a larger vspltis*.
1349 // Check to see if all of the leading entries are either 0 or -1. If
1350 // neither, then this won't fit into the immediate field.
1351 bool LeadingZero = true;
1352 bool LeadingOnes = true;
1353 for (unsigned i = 0; i != Multiple-1; ++i) {
1354 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1356 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1357 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1359 // Finally, check the least significant entry.
1361 if (!UniquedVals[Multiple-1].getNode())
1362 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
1363 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1364 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
1365 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1368 if (!UniquedVals[Multiple-1].getNode())
1369 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1370 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1371 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1372 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1378 // Check to see if this buildvec has a single non-undef value in its elements.
1379 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1380 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1381 if (!OpVal.getNode())
1382 OpVal = N->getOperand(i);
1383 else if (OpVal != N->getOperand(i))
1387 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1389 unsigned ValSizeInBytes = EltSize;
1391 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1392 Value = CN->getZExtValue();
1393 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1394 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1395 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1398 // If the splat value is larger than the element value, then we can never do
1399 // this splat. The only case that we could fit the replicated bits into our
1400 // immediate field for would be zero, and we prefer to use vxor for it.
1401 if (ValSizeInBytes < ByteSize) return SDValue();
1403 // If the element value is larger than the splat value, check if it consists
1404 // of a repeated bit pattern of size ByteSize.
1405 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1408 // Properly sign extend the value.
1409 int MaskVal = SignExtend32(Value, ByteSize * 8);
1411 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1412 if (MaskVal == 0) return SDValue();
1414 // Finally, if this value fits in a 5 bit sext field, return it
1415 if (SignExtend32<5>(MaskVal) == MaskVal)
1416 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1420 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1421 /// amount, otherwise return -1.
1422 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1423 EVT VT = N->getValueType(0);
1424 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1427 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1429 // Find the first non-undef value in the shuffle mask.
1431 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1434 if (i == 4) return -1; // all undef.
1436 // Otherwise, check to see if the rest of the elements are consecutively
1437 // numbered from this value.
1438 unsigned ShiftAmt = SVOp->getMaskElt(i);
1439 if (ShiftAmt < i) return -1;
1442 // Check the rest of the elements to see if they are consecutive.
1443 for (++i; i != 4; ++i)
1444 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1450 //===----------------------------------------------------------------------===//
1451 // Addressing Mode Selection
1452 //===----------------------------------------------------------------------===//
1454 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1455 /// or 64-bit immediate, and if the value can be accurately represented as a
1456 /// sign extension from a 16-bit value. If so, this returns true and the
1458 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1459 if (!isa<ConstantSDNode>(N))
1462 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1463 if (N->getValueType(0) == MVT::i32)
1464 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1466 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1468 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1469 return isIntS16Immediate(Op.getNode(), Imm);
1473 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1474 /// can be represented as an indexed [r+r] operation. Returns false if it
1475 /// can be more efficiently represented with [r+imm].
1476 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1478 SelectionDAG &DAG) const {
1480 if (N.getOpcode() == ISD::ADD) {
1481 if (isIntS16Immediate(N.getOperand(1), imm))
1482 return false; // r+i
1483 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1484 return false; // r+i
1486 Base = N.getOperand(0);
1487 Index = N.getOperand(1);
1489 } else if (N.getOpcode() == ISD::OR) {
1490 if (isIntS16Immediate(N.getOperand(1), imm))
1491 return false; // r+i can fold it if we can.
1493 // If this is an or of disjoint bitfields, we can codegen this as an add
1494 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1496 APInt LHSKnownZero, LHSKnownOne;
1497 APInt RHSKnownZero, RHSKnownOne;
1498 DAG.computeKnownBits(N.getOperand(0),
1499 LHSKnownZero, LHSKnownOne);
1501 if (LHSKnownZero.getBoolValue()) {
1502 DAG.computeKnownBits(N.getOperand(1),
1503 RHSKnownZero, RHSKnownOne);
1504 // If all of the bits are known zero on the LHS or RHS, the add won't
1506 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1507 Base = N.getOperand(0);
1508 Index = N.getOperand(1);
1517 // If we happen to be doing an i64 load or store into a stack slot that has
1518 // less than a 4-byte alignment, then the frame-index elimination may need to
1519 // use an indexed load or store instruction (because the offset may not be a
1520 // multiple of 4). The extra register needed to hold the offset comes from the
1521 // register scavenger, and it is possible that the scavenger will need to use
1522 // an emergency spill slot. As a result, we need to make sure that a spill slot
1523 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1525 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1526 // FIXME: This does not handle the LWA case.
1530 // NOTE: We'll exclude negative FIs here, which come from argument
1531 // lowering, because there are no known test cases triggering this problem
1532 // using packed structures (or similar). We can remove this exclusion if
1533 // we find such a test case. The reason why this is so test-case driven is
1534 // because this entire 'fixup' is only to prevent crashes (from the
1535 // register scavenger) on not-really-valid inputs. For example, if we have:
1537 // %b = bitcast i1* %a to i64*
1538 // store i64* a, i64 b
1539 // then the store should really be marked as 'align 1', but is not. If it
1540 // were marked as 'align 1' then the indexed form would have been
1541 // instruction-selected initially, and the problem this 'fixup' is preventing
1542 // won't happen regardless.
1546 MachineFunction &MF = DAG.getMachineFunction();
1547 MachineFrameInfo *MFI = MF.getFrameInfo();
1549 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1553 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1554 FuncInfo->setHasNonRISpills();
1557 /// Returns true if the address N can be represented by a base register plus
1558 /// a signed 16-bit displacement [r+imm], and if it is not better
1559 /// represented as reg+reg. If Aligned is true, only accept displacements
1560 /// suitable for STD and friends, i.e. multiples of 4.
1561 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1564 bool Aligned) const {
1565 // FIXME dl should come from parent load or store, not from address
1567 // If this can be more profitably realized as r+r, fail.
1568 if (SelectAddressRegReg(N, Disp, Base, DAG))
1571 if (N.getOpcode() == ISD::ADD) {
1573 if (isIntS16Immediate(N.getOperand(1), imm) &&
1574 (!Aligned || (imm & 3) == 0)) {
1575 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1576 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1577 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1578 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1580 Base = N.getOperand(0);
1582 return true; // [r+i]
1583 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1584 // Match LOAD (ADD (X, Lo(G))).
1585 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1586 && "Cannot handle constant offsets yet!");
1587 Disp = N.getOperand(1).getOperand(0); // The global address.
1588 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1589 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1590 Disp.getOpcode() == ISD::TargetConstantPool ||
1591 Disp.getOpcode() == ISD::TargetJumpTable);
1592 Base = N.getOperand(0);
1593 return true; // [&g+r]
1595 } else if (N.getOpcode() == ISD::OR) {
1597 if (isIntS16Immediate(N.getOperand(1), imm) &&
1598 (!Aligned || (imm & 3) == 0)) {
1599 // If this is an or of disjoint bitfields, we can codegen this as an add
1600 // (for better address arithmetic) if the LHS and RHS of the OR are
1601 // provably disjoint.
1602 APInt LHSKnownZero, LHSKnownOne;
1603 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1605 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1606 // If all of the bits are known zero on the LHS or RHS, the add won't
1608 if (FrameIndexSDNode *FI =
1609 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1610 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1611 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1613 Base = N.getOperand(0);
1615 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1619 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1620 // Loading from a constant address.
1622 // If this address fits entirely in a 16-bit sext immediate field, codegen
1625 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1626 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1627 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1628 CN->getValueType(0));
1632 // Handle 32-bit sext immediates with LIS + addr mode.
1633 if ((CN->getValueType(0) == MVT::i32 ||
1634 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1635 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1636 int Addr = (int)CN->getZExtValue();
1638 // Otherwise, break this down into an LIS + disp.
1639 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1641 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1643 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1644 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1649 Disp = DAG.getTargetConstant(0, dl, getPointerTy());
1650 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1651 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1652 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1655 return true; // [r+0]
1658 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1659 /// represented as an indexed [r+r] operation.
1660 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1662 SelectionDAG &DAG) const {
1663 // Check to see if we can easily represent this as an [r+r] address. This
1664 // will fail if it thinks that the address is more profitably represented as
1665 // reg+imm, e.g. where imm = 0.
1666 if (SelectAddressRegReg(N, Base, Index, DAG))
1669 // If the operand is an addition, always emit this as [r+r], since this is
1670 // better (for code size, and execution, as the memop does the add for free)
1671 // than emitting an explicit add.
1672 if (N.getOpcode() == ISD::ADD) {
1673 Base = N.getOperand(0);
1674 Index = N.getOperand(1);
1678 // Otherwise, do it the hard way, using R0 as the base register.
1679 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1685 /// getPreIndexedAddressParts - returns true by value, base pointer and
1686 /// offset pointer and addressing mode by reference if the node's address
1687 /// can be legally represented as pre-indexed load / store address.
1688 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1690 ISD::MemIndexedMode &AM,
1691 SelectionDAG &DAG) const {
1692 if (DisablePPCPreinc) return false;
1698 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1699 Ptr = LD->getBasePtr();
1700 VT = LD->getMemoryVT();
1701 Alignment = LD->getAlignment();
1702 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1703 Ptr = ST->getBasePtr();
1704 VT = ST->getMemoryVT();
1705 Alignment = ST->getAlignment();
1710 // PowerPC doesn't have preinc load/store instructions for vectors (except
1711 // for QPX, which does have preinc r+r forms).
1712 if (VT.isVector()) {
1713 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1715 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1721 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1723 // Common code will reject creating a pre-inc form if the base pointer
1724 // is a frame index, or if N is a store and the base pointer is either
1725 // the same as or a predecessor of the value being stored. Check for
1726 // those situations here, and try with swapped Base/Offset instead.
1729 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1732 SDValue Val = cast<StoreSDNode>(N)->getValue();
1733 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1738 std::swap(Base, Offset);
1744 // LDU/STU can only handle immediates that are a multiple of 4.
1745 if (VT != MVT::i64) {
1746 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1749 // LDU/STU need an address with at least 4-byte alignment.
1753 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1757 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1758 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1759 // sext i32 to i64 when addr mode is r+i.
1760 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1761 LD->getExtensionType() == ISD::SEXTLOAD &&
1762 isa<ConstantSDNode>(Offset))
1770 //===----------------------------------------------------------------------===//
1771 // LowerOperation implementation
1772 //===----------------------------------------------------------------------===//
1774 /// GetLabelAccessInfo - Return true if we should reference labels using a
1775 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1776 static bool GetLabelAccessInfo(const TargetMachine &TM,
1777 const PPCSubtarget &Subtarget,
1778 unsigned &HiOpFlags, unsigned &LoOpFlags,
1779 const GlobalValue *GV = nullptr) {
1780 HiOpFlags = PPCII::MO_HA;
1781 LoOpFlags = PPCII::MO_LO;
1783 // Don't use the pic base if not in PIC relocation model.
1784 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1787 HiOpFlags |= PPCII::MO_PIC_FLAG;
1788 LoOpFlags |= PPCII::MO_PIC_FLAG;
1791 // If this is a reference to a global value that requires a non-lazy-ptr, make
1792 // sure that instruction lowering adds it.
1793 if (GV && Subtarget.hasLazyResolverStub(GV)) {
1794 HiOpFlags |= PPCII::MO_NLP_FLAG;
1795 LoOpFlags |= PPCII::MO_NLP_FLAG;
1797 if (GV->hasHiddenVisibility()) {
1798 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1799 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1806 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1807 SelectionDAG &DAG) {
1809 EVT PtrVT = HiPart.getValueType();
1810 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1812 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1813 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1815 // With PIC, the first instruction is actually "GR+hi(&G)".
1817 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1818 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1820 // Generate non-pic code that has direct accesses to the constant pool.
1821 // The address of the global is just (hi(&g)+lo(&g)).
1822 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1825 static void setUsesTOCBasePtr(MachineFunction &MF) {
1826 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1827 FuncInfo->setUsesTOCBasePtr();
1830 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1831 setUsesTOCBasePtr(DAG.getMachineFunction());
1834 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1836 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1837 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1838 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1840 SDValue Ops[] = { GA, Reg };
1841 return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1842 DAG.getVTList(VT, MVT::Other), Ops, VT,
1843 MachinePointerInfo::getGOT(), 0, false, true,
1847 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1848 SelectionDAG &DAG) const {
1849 EVT PtrVT = Op.getValueType();
1850 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1851 const Constant *C = CP->getConstVal();
1853 // 64-bit SVR4 ABI code is always position-independent.
1854 // The actual address of the GlobalValue is stored in the TOC.
1855 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1856 setUsesTOCBasePtr(DAG);
1857 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1858 return getTOCEntry(DAG, SDLoc(CP), true, GA);
1861 unsigned MOHiFlag, MOLoFlag;
1863 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1865 if (isPIC && Subtarget.isSVR4ABI()) {
1866 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1867 PPCII::MO_PIC_FLAG);
1868 return getTOCEntry(DAG, SDLoc(CP), false, GA);
1872 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1874 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1875 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1878 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1879 EVT PtrVT = Op.getValueType();
1880 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1882 // 64-bit SVR4 ABI code is always position-independent.
1883 // The actual address of the GlobalValue is stored in the TOC.
1884 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1885 setUsesTOCBasePtr(DAG);
1886 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1887 return getTOCEntry(DAG, SDLoc(JT), true, GA);
1890 unsigned MOHiFlag, MOLoFlag;
1892 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1894 if (isPIC && Subtarget.isSVR4ABI()) {
1895 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1896 PPCII::MO_PIC_FLAG);
1897 return getTOCEntry(DAG, SDLoc(GA), false, GA);
1900 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1901 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1902 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1905 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1906 SelectionDAG &DAG) const {
1907 EVT PtrVT = Op.getValueType();
1908 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1909 const BlockAddress *BA = BASDN->getBlockAddress();
1911 // 64-bit SVR4 ABI code is always position-independent.
1912 // The actual BlockAddress is stored in the TOC.
1913 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1914 setUsesTOCBasePtr(DAG);
1915 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1916 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1919 unsigned MOHiFlag, MOLoFlag;
1921 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1922 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1923 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1924 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1927 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1928 SelectionDAG &DAG) const {
1930 // FIXME: TLS addresses currently use medium model code sequences,
1931 // which is the most useful form. Eventually support for small and
1932 // large models could be added if users need it, at the cost of
1933 // additional complexity.
1934 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1936 const GlobalValue *GV = GA->getGlobal();
1937 EVT PtrVT = getPointerTy();
1938 bool is64bit = Subtarget.isPPC64();
1939 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1940 PICLevel::Level picLevel = M->getPICLevel();
1942 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1944 if (Model == TLSModel::LocalExec) {
1945 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1946 PPCII::MO_TPREL_HA);
1947 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1948 PPCII::MO_TPREL_LO);
1949 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1950 is64bit ? MVT::i64 : MVT::i32);
1951 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1952 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1955 if (Model == TLSModel::InitialExec) {
1956 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1957 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1961 setUsesTOCBasePtr(DAG);
1962 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1963 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1964 PtrVT, GOTReg, TGA);
1966 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1967 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1968 PtrVT, TGA, GOTPtr);
1969 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1972 if (Model == TLSModel::GeneralDynamic) {
1973 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1976 setUsesTOCBasePtr(DAG);
1977 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1978 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1981 if (picLevel == PICLevel::Small)
1982 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1984 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1986 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1990 if (Model == TLSModel::LocalDynamic) {
1991 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1994 setUsesTOCBasePtr(DAG);
1995 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1996 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1999 if (picLevel == PICLevel::Small)
2000 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2002 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2004 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2005 PtrVT, GOTPtr, TGA, TGA);
2006 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2007 PtrVT, TLSAddr, TGA);
2008 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2011 llvm_unreachable("Unknown TLS model!");
2014 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2015 SelectionDAG &DAG) const {
2016 EVT PtrVT = Op.getValueType();
2017 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2019 const GlobalValue *GV = GSDN->getGlobal();
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.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2026 return getTOCEntry(DAG, DL, true, GA);
2029 unsigned MOHiFlag, MOLoFlag;
2031 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2033 if (isPIC && Subtarget.isSVR4ABI()) {
2034 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2036 PPCII::MO_PIC_FLAG);
2037 return getTOCEntry(DAG, DL, false, GA);
2041 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2043 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2045 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2047 // If the global reference is actually to a non-lazy-pointer, we have to do an
2048 // extra load to get the address of the global.
2049 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2050 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2051 false, false, false, 0);
2055 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2056 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2059 if (Op.getValueType() == MVT::v2i64) {
2060 // When the operands themselves are v2i64 values, we need to do something
2061 // special because VSX has no underlying comparison operations for these.
2062 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2063 // Equality can be handled by casting to the legal type for Altivec
2064 // comparisons, everything else needs to be expanded.
2065 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2066 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2067 DAG.getSetCC(dl, MVT::v4i32,
2068 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2069 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2076 // We handle most of these in the usual way.
2080 // If we're comparing for equality to zero, expose the fact that this is
2081 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2082 // fold the new nodes.
2083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2084 if (C->isNullValue() && CC == ISD::SETEQ) {
2085 EVT VT = Op.getOperand(0).getValueType();
2086 SDValue Zext = Op.getOperand(0);
2087 if (VT.bitsLT(MVT::i32)) {
2089 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2091 unsigned Log2b = Log2_32(VT.getSizeInBits());
2092 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2093 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2094 DAG.getConstant(Log2b, dl, MVT::i32));
2095 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2097 // Leave comparisons against 0 and -1 alone for now, since they're usually
2098 // optimized. FIXME: revisit this when we can custom lower all setcc
2100 if (C->isAllOnesValue() || C->isNullValue())
2104 // If we have an integer seteq/setne, turn it into a compare against zero
2105 // by xor'ing the rhs with the lhs, which is faster than setting a
2106 // condition register, reading it back out, and masking the correct bit. The
2107 // normal approach here uses sub to do this instead of xor. Using xor exposes
2108 // the result to other bit-twiddling opportunities.
2109 EVT LHSVT = Op.getOperand(0).getValueType();
2110 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2111 EVT VT = Op.getValueType();
2112 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2114 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2119 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2120 const PPCSubtarget &Subtarget) const {
2121 SDNode *Node = Op.getNode();
2122 EVT VT = Node->getValueType(0);
2123 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2124 SDValue InChain = Node->getOperand(0);
2125 SDValue VAListPtr = Node->getOperand(1);
2126 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2129 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2132 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2133 VAListPtr, MachinePointerInfo(SV), MVT::i8,
2134 false, false, false, 0);
2135 InChain = GprIndex.getValue(1);
2137 if (VT == MVT::i64) {
2138 // Check if GprIndex is even
2139 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2140 DAG.getConstant(1, dl, MVT::i32));
2141 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2142 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2143 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2144 DAG.getConstant(1, dl, MVT::i32));
2145 // Align GprIndex to be even if it isn't
2146 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2150 // fpr index is 1 byte after gpr
2151 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2152 DAG.getConstant(1, dl, MVT::i32));
2155 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2156 FprPtr, MachinePointerInfo(SV), MVT::i8,
2157 false, false, false, 0);
2158 InChain = FprIndex.getValue(1);
2160 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2161 DAG.getConstant(8, dl, MVT::i32));
2163 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2164 DAG.getConstant(4, dl, MVT::i32));
2167 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2168 MachinePointerInfo(), false, false,
2170 InChain = OverflowArea.getValue(1);
2172 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2173 MachinePointerInfo(), false, false,
2175 InChain = RegSaveArea.getValue(1);
2177 // select overflow_area if index > 8
2178 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2179 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2181 // adjustment constant gpr_index * 4/8
2182 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2183 VT.isInteger() ? GprIndex : FprIndex,
2184 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2187 // OurReg = RegSaveArea + RegConstant
2188 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2191 // Floating types are 32 bytes into RegSaveArea
2192 if (VT.isFloatingPoint())
2193 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2194 DAG.getConstant(32, dl, MVT::i32));
2196 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2197 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2198 VT.isInteger() ? GprIndex : FprIndex,
2199 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2202 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2203 VT.isInteger() ? VAListPtr : FprPtr,
2204 MachinePointerInfo(SV),
2205 MVT::i8, false, false, 0);
2207 // determine if we should load from reg_save_area or overflow_area
2208 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2210 // increase overflow_area by 4/8 if gpr/fpr > 8
2211 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2212 DAG.getConstant(VT.isInteger() ? 4 : 8,
2215 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2218 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2220 MachinePointerInfo(),
2221 MVT::i32, false, false, 0);
2223 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2224 false, false, false, 0);
2227 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2228 const PPCSubtarget &Subtarget) const {
2229 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2231 // We have to copy the entire va_list struct:
2232 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2233 return DAG.getMemcpy(Op.getOperand(0), Op,
2234 Op.getOperand(1), Op.getOperand(2),
2235 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2236 false, MachinePointerInfo(), MachinePointerInfo());
2239 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2240 SelectionDAG &DAG) const {
2241 return Op.getOperand(0);
2244 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2245 SelectionDAG &DAG) const {
2246 SDValue Chain = Op.getOperand(0);
2247 SDValue Trmp = Op.getOperand(1); // trampoline
2248 SDValue FPtr = Op.getOperand(2); // nested function
2249 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2252 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2253 bool isPPC64 = (PtrVT == MVT::i64);
2255 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2258 TargetLowering::ArgListTy Args;
2259 TargetLowering::ArgListEntry Entry;
2261 Entry.Ty = IntPtrTy;
2262 Entry.Node = Trmp; Args.push_back(Entry);
2264 // TrampSize == (isPPC64 ? 48 : 40);
2265 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2266 isPPC64 ? MVT::i64 : MVT::i32);
2267 Args.push_back(Entry);
2269 Entry.Node = FPtr; Args.push_back(Entry);
2270 Entry.Node = Nest; Args.push_back(Entry);
2272 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2273 TargetLowering::CallLoweringInfo CLI(DAG);
2274 CLI.setDebugLoc(dl).setChain(Chain)
2275 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2276 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2277 std::move(Args), 0);
2279 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2280 return CallResult.second;
2283 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2284 const PPCSubtarget &Subtarget) const {
2285 MachineFunction &MF = DAG.getMachineFunction();
2286 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2290 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2291 // vastart just stores the address of the VarArgsFrameIndex slot into the
2292 // memory location argument.
2293 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2294 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2295 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2296 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2297 MachinePointerInfo(SV),
2301 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2302 // We suppose the given va_list is already allocated.
2305 // char gpr; /* index into the array of 8 GPRs
2306 // * stored in the register save area
2307 // * gpr=0 corresponds to r3,
2308 // * gpr=1 to r4, etc.
2310 // char fpr; /* index into the array of 8 FPRs
2311 // * stored in the register save area
2312 // * fpr=0 corresponds to f1,
2313 // * fpr=1 to f2, etc.
2315 // char *overflow_arg_area;
2316 // /* location on stack that holds
2317 // * the next overflow argument
2319 // char *reg_save_area;
2320 // /* where r3:r10 and f1:f8 (if saved)
2326 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2327 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2330 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2332 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2334 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2337 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2338 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2340 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2341 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2343 uint64_t FPROffset = 1;
2344 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2346 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2348 // Store first byte : number of int regs
2349 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2351 MachinePointerInfo(SV),
2352 MVT::i8, false, false, 0);
2353 uint64_t nextOffset = FPROffset;
2354 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2357 // Store second byte : number of float regs
2358 SDValue secondStore =
2359 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2360 MachinePointerInfo(SV, nextOffset), MVT::i8,
2362 nextOffset += StackOffset;
2363 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2365 // Store second word : arguments given on stack
2366 SDValue thirdStore =
2367 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2368 MachinePointerInfo(SV, nextOffset),
2370 nextOffset += FrameOffset;
2371 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2373 // Store third word : arguments given in registers
2374 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2375 MachinePointerInfo(SV, nextOffset),
2380 #include "PPCGenCallingConv.inc"
2382 // Function whose sole purpose is to kill compiler warnings
2383 // stemming from unused functions included from PPCGenCallingConv.inc.
2384 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2385 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2388 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2389 CCValAssign::LocInfo &LocInfo,
2390 ISD::ArgFlagsTy &ArgFlags,
2395 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2397 CCValAssign::LocInfo &LocInfo,
2398 ISD::ArgFlagsTy &ArgFlags,
2400 static const MCPhysReg ArgRegs[] = {
2401 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2402 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2404 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2406 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2408 // Skip one register if the first unallocated register has an even register
2409 // number and there are still argument registers available which have not been
2410 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2411 // need to skip a register if RegNum is odd.
2412 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2413 State.AllocateReg(ArgRegs[RegNum]);
2416 // Always return false here, as this function only makes sure that the first
2417 // unallocated register has an odd register number and does not actually
2418 // allocate a register for the current argument.
2422 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2424 CCValAssign::LocInfo &LocInfo,
2425 ISD::ArgFlagsTy &ArgFlags,
2427 static const MCPhysReg ArgRegs[] = {
2428 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2432 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2434 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2436 // If there is only one Floating-point register left we need to put both f64
2437 // values of a split ppc_fp128 value on the stack.
2438 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2439 State.AllocateReg(ArgRegs[RegNum]);
2442 // Always return false here, as this function only makes sure that the two f64
2443 // values a ppc_fp128 value is split into are both passed in registers or both
2444 // passed on the stack and does not actually allocate a register for the
2445 // current argument.
2449 /// FPR - The set of FP registers that should be allocated for arguments,
2451 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2452 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2453 PPC::F11, PPC::F12, PPC::F13};
2455 /// QFPR - The set of QPX registers that should be allocated for arguments.
2456 static const MCPhysReg QFPR[] = {
2457 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2458 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2460 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2462 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2463 unsigned PtrByteSize) {
2464 unsigned ArgSize = ArgVT.getStoreSize();
2465 if (Flags.isByVal())
2466 ArgSize = Flags.getByValSize();
2468 // Round up to multiples of the pointer size, except for array members,
2469 // which are always packed.
2470 if (!Flags.isInConsecutiveRegs())
2471 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2476 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2478 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2479 ISD::ArgFlagsTy Flags,
2480 unsigned PtrByteSize) {
2481 unsigned Align = PtrByteSize;
2483 // Altivec parameters are padded to a 16 byte boundary.
2484 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2485 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2486 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2487 ArgVT == MVT::v1i128)
2489 // QPX vector types stored in double-precision are padded to a 32 byte
2491 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2494 // ByVal parameters are aligned as requested.
2495 if (Flags.isByVal()) {
2496 unsigned BVAlign = Flags.getByValAlign();
2497 if (BVAlign > PtrByteSize) {
2498 if (BVAlign % PtrByteSize != 0)
2500 "ByVal alignment is not a multiple of the pointer size");
2506 // Array members are always packed to their original alignment.
2507 if (Flags.isInConsecutiveRegs()) {
2508 // If the array member was split into multiple registers, the first
2509 // needs to be aligned to the size of the full type. (Except for
2510 // ppcf128, which is only aligned as its f64 components.)
2511 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2512 Align = OrigVT.getStoreSize();
2514 Align = ArgVT.getStoreSize();
2520 /// CalculateStackSlotUsed - Return whether this argument will use its
2521 /// stack slot (instead of being passed in registers). ArgOffset,
2522 /// AvailableFPRs, and AvailableVRs must hold the current argument
2523 /// position, and will be updated to account for this argument.
2524 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2525 ISD::ArgFlagsTy Flags,
2526 unsigned PtrByteSize,
2527 unsigned LinkageSize,
2528 unsigned ParamAreaSize,
2529 unsigned &ArgOffset,
2530 unsigned &AvailableFPRs,
2531 unsigned &AvailableVRs, bool HasQPX) {
2532 bool UseMemory = false;
2534 // Respect alignment of argument on the stack.
2536 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2537 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2538 // If there's no space left in the argument save area, we must
2539 // use memory (this check also catches zero-sized arguments).
2540 if (ArgOffset >= LinkageSize + ParamAreaSize)
2543 // Allocate argument on the stack.
2544 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2545 if (Flags.isInConsecutiveRegsLast())
2546 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2547 // If we overran the argument save area, we must use memory
2548 // (this check catches arguments passed partially in memory)
2549 if (ArgOffset > LinkageSize + ParamAreaSize)
2552 // However, if the argument is actually passed in an FPR or a VR,
2553 // we don't use memory after all.
2554 if (!Flags.isByVal()) {
2555 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2556 // QPX registers overlap with the scalar FP registers.
2557 (HasQPX && (ArgVT == MVT::v4f32 ||
2558 ArgVT == MVT::v4f64 ||
2559 ArgVT == MVT::v4i1)))
2560 if (AvailableFPRs > 0) {
2564 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2565 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2566 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2567 ArgVT == MVT::v1i128)
2568 if (AvailableVRs > 0) {
2577 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2578 /// ensure minimum alignment required for target.
2579 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2580 unsigned NumBytes) {
2581 unsigned TargetAlign = Lowering->getStackAlignment();
2582 unsigned AlignMask = TargetAlign - 1;
2583 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2588 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2589 CallingConv::ID CallConv, bool isVarArg,
2590 const SmallVectorImpl<ISD::InputArg>
2592 SDLoc dl, SelectionDAG &DAG,
2593 SmallVectorImpl<SDValue> &InVals)
2595 if (Subtarget.isSVR4ABI()) {
2596 if (Subtarget.isPPC64())
2597 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2600 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2603 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2609 PPCTargetLowering::LowerFormalArguments_32SVR4(
2611 CallingConv::ID CallConv, bool isVarArg,
2612 const SmallVectorImpl<ISD::InputArg>
2614 SDLoc dl, SelectionDAG &DAG,
2615 SmallVectorImpl<SDValue> &InVals) const {
2617 // 32-bit SVR4 ABI Stack Frame Layout:
2618 // +-----------------------------------+
2619 // +--> | Back chain |
2620 // | +-----------------------------------+
2621 // | | Floating-point register save area |
2622 // | +-----------------------------------+
2623 // | | General register save area |
2624 // | +-----------------------------------+
2625 // | | CR save word |
2626 // | +-----------------------------------+
2627 // | | VRSAVE save word |
2628 // | +-----------------------------------+
2629 // | | Alignment padding |
2630 // | +-----------------------------------+
2631 // | | Vector register save area |
2632 // | +-----------------------------------+
2633 // | | Local variable space |
2634 // | +-----------------------------------+
2635 // | | Parameter list area |
2636 // | +-----------------------------------+
2637 // | | LR save word |
2638 // | +-----------------------------------+
2639 // SP--> +--- | Back chain |
2640 // +-----------------------------------+
2643 // System V Application Binary Interface PowerPC Processor Supplement
2644 // AltiVec Technology Programming Interface Manual
2646 MachineFunction &MF = DAG.getMachineFunction();
2647 MachineFrameInfo *MFI = MF.getFrameInfo();
2648 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2650 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2651 // Potential tail calls could cause overwriting of argument stack slots.
2652 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2653 (CallConv == CallingConv::Fast));
2654 unsigned PtrByteSize = 4;
2656 // Assign locations to all of the incoming arguments.
2657 SmallVector<CCValAssign, 16> ArgLocs;
2658 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2661 // Reserve space for the linkage area on the stack.
2662 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2663 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2665 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2667 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2668 CCValAssign &VA = ArgLocs[i];
2670 // Arguments stored in registers.
2671 if (VA.isRegLoc()) {
2672 const TargetRegisterClass *RC;
2673 EVT ValVT = VA.getValVT();
2675 switch (ValVT.getSimpleVT().SimpleTy) {
2677 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2680 RC = &PPC::GPRCRegClass;
2683 RC = &PPC::F4RCRegClass;
2686 if (Subtarget.hasVSX())
2687 RC = &PPC::VSFRCRegClass;
2689 RC = &PPC::F8RCRegClass;
2694 RC = &PPC::VRRCRegClass;
2697 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2701 RC = &PPC::VSHRCRegClass;
2704 RC = &PPC::QFRCRegClass;
2707 RC = &PPC::QBRCRegClass;
2711 // Transform the arguments stored in physical registers into virtual ones.
2712 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2713 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2714 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2716 if (ValVT == MVT::i1)
2717 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2719 InVals.push_back(ArgValue);
2721 // Argument stored in memory.
2722 assert(VA.isMemLoc());
2724 unsigned ArgSize = VA.getLocVT().getStoreSize();
2725 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2728 // Create load nodes to retrieve arguments from the stack.
2729 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2730 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2731 MachinePointerInfo(),
2732 false, false, false, 0));
2736 // Assign locations to all of the incoming aggregate by value arguments.
2737 // Aggregates passed by value are stored in the local variable space of the
2738 // caller's stack frame, right above the parameter list area.
2739 SmallVector<CCValAssign, 16> ByValArgLocs;
2740 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2741 ByValArgLocs, *DAG.getContext());
2743 // Reserve stack space for the allocations in CCInfo.
2744 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2746 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2748 // Area that is at least reserved in the caller of this function.
2749 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2750 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2752 // Set the size that is at least reserved in caller of this function. Tail
2753 // call optimized function's reserved stack space needs to be aligned so that
2754 // taking the difference between two stack areas will result in an aligned
2757 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2758 FuncInfo->setMinReservedArea(MinReservedArea);
2760 SmallVector<SDValue, 8> MemOps;
2762 // If the function takes variable number of arguments, make a frame index for
2763 // the start of the first vararg value... for expansion of llvm.va_start.
2765 static const MCPhysReg GPArgRegs[] = {
2766 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2767 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2769 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2771 static const MCPhysReg FPArgRegs[] = {
2772 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2775 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2776 if (DisablePPCFloatInVariadic)
2779 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2780 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2782 // Make room for NumGPArgRegs and NumFPArgRegs.
2783 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2784 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2786 FuncInfo->setVarArgsStackOffset(
2787 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2788 CCInfo.getNextStackOffset(), true));
2790 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2791 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2793 // The fixed integer arguments of a variadic function are stored to the
2794 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2795 // the result of va_next.
2796 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2797 // Get an existing live-in vreg, or add a new one.
2798 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2800 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2802 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2803 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2804 MachinePointerInfo(), false, false, 0);
2805 MemOps.push_back(Store);
2806 // Increment the address by four for the next argument to store
2807 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2808 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2811 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2813 // The double arguments are stored to the VarArgsFrameIndex
2815 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2816 // Get an existing live-in vreg, or add a new one.
2817 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2819 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2821 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2822 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2823 MachinePointerInfo(), false, false, 0);
2824 MemOps.push_back(Store);
2825 // Increment the address by eight for the next argument to store
2826 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
2828 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2832 if (!MemOps.empty())
2833 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2838 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2839 // value to MVT::i64 and then truncate to the correct register size.
2841 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2842 SelectionDAG &DAG, SDValue ArgVal,
2845 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2846 DAG.getValueType(ObjectVT));
2847 else if (Flags.isZExt())
2848 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2849 DAG.getValueType(ObjectVT));
2851 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2855 PPCTargetLowering::LowerFormalArguments_64SVR4(
2857 CallingConv::ID CallConv, bool isVarArg,
2858 const SmallVectorImpl<ISD::InputArg>
2860 SDLoc dl, SelectionDAG &DAG,
2861 SmallVectorImpl<SDValue> &InVals) const {
2862 // TODO: add description of PPC stack frame format, or at least some docs.
2864 bool isELFv2ABI = Subtarget.isELFv2ABI();
2865 bool isLittleEndian = Subtarget.isLittleEndian();
2866 MachineFunction &MF = DAG.getMachineFunction();
2867 MachineFrameInfo *MFI = MF.getFrameInfo();
2868 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2870 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2871 "fastcc not supported on varargs functions");
2873 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2874 // Potential tail calls could cause overwriting of argument stack slots.
2875 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2876 (CallConv == CallingConv::Fast));
2877 unsigned PtrByteSize = 8;
2878 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2880 static const MCPhysReg GPR[] = {
2881 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2882 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2884 static const MCPhysReg VR[] = {
2885 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2886 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2888 static const MCPhysReg VSRH[] = {
2889 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2890 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2893 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2894 const unsigned Num_FPR_Regs = 13;
2895 const unsigned Num_VR_Regs = array_lengthof(VR);
2896 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2898 // Do a first pass over the arguments to determine whether the ABI
2899 // guarantees that our caller has allocated the parameter save area
2900 // on its stack frame. In the ELFv1 ABI, this is always the case;
2901 // in the ELFv2 ABI, it is true if this is a vararg function or if
2902 // any parameter is located in a stack slot.
2904 bool HasParameterArea = !isELFv2ABI || isVarArg;
2905 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2906 unsigned NumBytes = LinkageSize;
2907 unsigned AvailableFPRs = Num_FPR_Regs;
2908 unsigned AvailableVRs = Num_VR_Regs;
2909 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2910 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2911 PtrByteSize, LinkageSize, ParamAreaSize,
2912 NumBytes, AvailableFPRs, AvailableVRs,
2913 Subtarget.hasQPX()))
2914 HasParameterArea = true;
2916 // Add DAG nodes to load the arguments or copy them out of registers. On
2917 // entry to a function on PPC, the arguments start after the linkage area,
2918 // although the first ones are often in registers.
2920 unsigned ArgOffset = LinkageSize;
2921 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2922 unsigned &QFPR_idx = FPR_idx;
2923 SmallVector<SDValue, 8> MemOps;
2924 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2925 unsigned CurArgIdx = 0;
2926 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2928 bool needsLoad = false;
2929 EVT ObjectVT = Ins[ArgNo].VT;
2930 EVT OrigVT = Ins[ArgNo].ArgVT;
2931 unsigned ObjSize = ObjectVT.getStoreSize();
2932 unsigned ArgSize = ObjSize;
2933 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2934 if (Ins[ArgNo].isOrigArg()) {
2935 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2936 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2938 // We re-align the argument offset for each argument, except when using the
2939 // fast calling convention, when we need to make sure we do that only when
2940 // we'll actually use a stack slot.
2941 unsigned CurArgOffset, Align;
2942 auto ComputeArgOffset = [&]() {
2943 /* Respect alignment of argument on the stack. */
2944 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2945 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2946 CurArgOffset = ArgOffset;
2949 if (CallConv != CallingConv::Fast) {
2952 /* Compute GPR index associated with argument offset. */
2953 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2954 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2957 // FIXME the codegen can be much improved in some cases.
2958 // We do not have to keep everything in memory.
2959 if (Flags.isByVal()) {
2960 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2962 if (CallConv == CallingConv::Fast)
2965 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2966 ObjSize = Flags.getByValSize();
2967 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2968 // Empty aggregate parameters do not take up registers. Examples:
2972 // etc. However, we have to provide a place-holder in InVals, so
2973 // pretend we have an 8-byte item at the current address for that
2976 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2977 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2978 InVals.push_back(FIN);
2982 // Create a stack object covering all stack doublewords occupied
2983 // by the argument. If the argument is (fully or partially) on
2984 // the stack, or if the argument is fully in registers but the
2985 // caller has allocated the parameter save anyway, we can refer
2986 // directly to the caller's stack frame. Otherwise, create a
2987 // local copy in our own frame.
2989 if (HasParameterArea ||
2990 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2991 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2993 FI = MFI->CreateStackObject(ArgSize, Align, false);
2994 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2996 // Handle aggregates smaller than 8 bytes.
2997 if (ObjSize < PtrByteSize) {
2998 // The value of the object is its address, which differs from the
2999 // address of the enclosing doubleword on big-endian systems.
3001 if (!isLittleEndian) {
3002 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3003 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3005 InVals.push_back(Arg);
3007 if (GPR_idx != Num_GPR_Regs) {
3008 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3009 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3012 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3013 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3014 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3015 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3016 MachinePointerInfo(FuncArg),
3017 ObjType, false, false, 0);
3019 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3020 // store the whole register as-is to the parameter save area
3022 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3023 MachinePointerInfo(FuncArg),
3027 MemOps.push_back(Store);
3029 // Whether we copied from a register or not, advance the offset
3030 // into the parameter save area by a full doubleword.
3031 ArgOffset += PtrByteSize;
3035 // The value of the object is its address, which is the address of
3036 // its first stack doubleword.
3037 InVals.push_back(FIN);
3039 // Store whatever pieces of the object are in registers to memory.
3040 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3041 if (GPR_idx == Num_GPR_Regs)
3044 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3045 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3048 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3049 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3051 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3052 MachinePointerInfo(FuncArg, j),
3054 MemOps.push_back(Store);
3057 ArgOffset += ArgSize;
3061 switch (ObjectVT.getSimpleVT().SimpleTy) {
3062 default: llvm_unreachable("Unhandled argument type!");
3066 // These can be scalar arguments or elements of an integer array type
3067 // passed directly. Clang may use those instead of "byval" aggregate
3068 // types to avoid forcing arguments to memory unnecessarily.
3069 if (GPR_idx != Num_GPR_Regs) {
3070 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3071 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3073 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3074 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3075 // value to MVT::i64 and then truncate to the correct register size.
3076 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3078 if (CallConv == CallingConv::Fast)
3082 ArgSize = PtrByteSize;
3084 if (CallConv != CallingConv::Fast || needsLoad)
3090 // These can be scalar arguments or elements of a float array type
3091 // passed directly. The latter are used to implement ELFv2 homogenous
3092 // float aggregates.
3093 if (FPR_idx != Num_FPR_Regs) {
3096 if (ObjectVT == MVT::f32)
3097 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3099 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3100 ? &PPC::VSFRCRegClass
3101 : &PPC::F8RCRegClass);
3103 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3105 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3106 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3107 // once we support fp <-> gpr moves.
3109 // This can only ever happen in the presence of f32 array types,
3110 // since otherwise we never run out of FPRs before running out
3112 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3113 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3115 if (ObjectVT == MVT::f32) {
3116 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3117 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3118 DAG.getConstant(32, dl, MVT::i32));
3119 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3122 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3124 if (CallConv == CallingConv::Fast)
3130 // When passing an array of floats, the array occupies consecutive
3131 // space in the argument area; only round up to the next doubleword
3132 // at the end of the array. Otherwise, each float takes 8 bytes.
3133 if (CallConv != CallingConv::Fast || needsLoad) {
3134 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3135 ArgOffset += ArgSize;
3136 if (Flags.isInConsecutiveRegsLast())
3137 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3147 if (!Subtarget.hasQPX()) {
3148 // These can be scalar arguments or elements of a vector array type
3149 // passed directly. The latter are used to implement ELFv2 homogenous
3150 // vector aggregates.
3151 if (VR_idx != Num_VR_Regs) {
3152 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3153 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3154 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3155 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3158 if (CallConv == CallingConv::Fast)
3163 if (CallConv != CallingConv::Fast || needsLoad)
3168 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3169 "Invalid QPX parameter type");
3174 // QPX vectors are treated like their scalar floating-point subregisters
3175 // (except that they're larger).
3176 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3177 if (QFPR_idx != Num_QFPR_Regs) {
3178 const TargetRegisterClass *RC;
3179 switch (ObjectVT.getSimpleVT().SimpleTy) {
3180 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3181 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3182 default: RC = &PPC::QBRCRegClass; break;
3185 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3186 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3189 if (CallConv == CallingConv::Fast)
3193 if (CallConv != CallingConv::Fast || needsLoad)
3198 // We need to load the argument to a virtual register if we determined
3199 // above that we ran out of physical registers of the appropriate type.
3201 if (ObjSize < ArgSize && !isLittleEndian)
3202 CurArgOffset += ArgSize - ObjSize;
3203 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3204 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3205 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3206 false, false, false, 0);
3209 InVals.push_back(ArgVal);
3212 // Area that is at least reserved in the caller of this function.
3213 unsigned MinReservedArea;
3214 if (HasParameterArea)
3215 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3217 MinReservedArea = LinkageSize;
3219 // Set the size that is at least reserved in caller of this function. Tail
3220 // call optimized functions' reserved stack space needs to be aligned so that
3221 // taking the difference between two stack areas will result in an aligned
3224 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3225 FuncInfo->setMinReservedArea(MinReservedArea);
3227 // If the function takes variable number of arguments, make a frame index for
3228 // the start of the first vararg value... for expansion of llvm.va_start.
3230 int Depth = ArgOffset;
3232 FuncInfo->setVarArgsFrameIndex(
3233 MFI->CreateFixedObject(PtrByteSize, Depth, true));
3234 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3236 // If this function is vararg, store any remaining integer argument regs
3237 // to their spots on the stack so that they may be loaded by deferencing the
3238 // result of va_next.
3239 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3240 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3241 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3242 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3243 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3244 MachinePointerInfo(), false, false, 0);
3245 MemOps.push_back(Store);
3246 // Increment the address by four for the next argument to store
3247 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3248 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3252 if (!MemOps.empty())
3253 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3259 PPCTargetLowering::LowerFormalArguments_Darwin(
3261 CallingConv::ID CallConv, bool isVarArg,
3262 const SmallVectorImpl<ISD::InputArg>
3264 SDLoc dl, SelectionDAG &DAG,
3265 SmallVectorImpl<SDValue> &InVals) const {
3266 // TODO: add description of PPC stack frame format, or at least some docs.
3268 MachineFunction &MF = DAG.getMachineFunction();
3269 MachineFrameInfo *MFI = MF.getFrameInfo();
3270 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3272 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3273 bool isPPC64 = PtrVT == MVT::i64;
3274 // Potential tail calls could cause overwriting of argument stack slots.
3275 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3276 (CallConv == CallingConv::Fast));
3277 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3278 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3279 unsigned ArgOffset = LinkageSize;
3280 // Area that is at least reserved in caller of this function.
3281 unsigned MinReservedArea = ArgOffset;
3283 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3284 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3285 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3287 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3288 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3289 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3291 static const MCPhysReg VR[] = {
3292 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3293 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3296 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3297 const unsigned Num_FPR_Regs = 13;
3298 const unsigned Num_VR_Regs = array_lengthof( VR);
3300 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3302 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3304 // In 32-bit non-varargs functions, the stack space for vectors is after the
3305 // stack space for non-vectors. We do not use this space unless we have
3306 // too many vectors to fit in registers, something that only occurs in
3307 // constructed examples:), but we have to walk the arglist to figure
3308 // that out...for the pathological case, compute VecArgOffset as the
3309 // start of the vector parameter area. Computing VecArgOffset is the
3310 // entire point of the following loop.
3311 unsigned VecArgOffset = ArgOffset;
3312 if (!isVarArg && !isPPC64) {
3313 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3315 EVT ObjectVT = Ins[ArgNo].VT;
3316 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3318 if (Flags.isByVal()) {
3319 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3320 unsigned ObjSize = Flags.getByValSize();
3322 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3323 VecArgOffset += ArgSize;
3327 switch(ObjectVT.getSimpleVT().SimpleTy) {
3328 default: llvm_unreachable("Unhandled argument type!");
3334 case MVT::i64: // PPC64
3336 // FIXME: We are guaranteed to be !isPPC64 at this point.
3337 // Does MVT::i64 apply?
3344 // Nothing to do, we're only looking at Nonvector args here.
3349 // We've found where the vector parameter area in memory is. Skip the
3350 // first 12 parameters; these don't use that memory.
3351 VecArgOffset = ((VecArgOffset+15)/16)*16;
3352 VecArgOffset += 12*16;
3354 // Add DAG nodes to load the arguments or copy them out of registers. On
3355 // entry to a function on PPC, the arguments start after the linkage area,
3356 // although the first ones are often in registers.
3358 SmallVector<SDValue, 8> MemOps;
3359 unsigned nAltivecParamsAtEnd = 0;
3360 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3361 unsigned CurArgIdx = 0;
3362 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3364 bool needsLoad = false;
3365 EVT ObjectVT = Ins[ArgNo].VT;
3366 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3367 unsigned ArgSize = ObjSize;
3368 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3369 if (Ins[ArgNo].isOrigArg()) {
3370 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3371 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3373 unsigned CurArgOffset = ArgOffset;
3375 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3376 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3377 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3378 if (isVarArg || isPPC64) {
3379 MinReservedArea = ((MinReservedArea+15)/16)*16;
3380 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3383 } else nAltivecParamsAtEnd++;
3385 // Calculate min reserved area.
3386 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3390 // FIXME the codegen can be much improved in some cases.
3391 // We do not have to keep everything in memory.
3392 if (Flags.isByVal()) {
3393 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3395 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3396 ObjSize = Flags.getByValSize();
3397 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3398 // Objects of size 1 and 2 are right justified, everything else is
3399 // left justified. This means the memory address is adjusted forwards.
3400 if (ObjSize==1 || ObjSize==2) {
3401 CurArgOffset = CurArgOffset + (4 - ObjSize);
3403 // The value of the object is its address.
3404 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3405 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3406 InVals.push_back(FIN);
3407 if (ObjSize==1 || ObjSize==2) {
3408 if (GPR_idx != Num_GPR_Regs) {
3411 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3413 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3414 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3415 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3416 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3417 MachinePointerInfo(FuncArg),
3418 ObjType, false, false, 0);
3419 MemOps.push_back(Store);
3423 ArgOffset += PtrByteSize;
3427 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3428 // Store whatever pieces of the object are in registers
3429 // to memory. ArgOffset will be the address of the beginning
3431 if (GPR_idx != Num_GPR_Regs) {
3434 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3436 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3437 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3438 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3439 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3440 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3441 MachinePointerInfo(FuncArg, j),
3443 MemOps.push_back(Store);
3445 ArgOffset += PtrByteSize;
3447 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3454 switch (ObjectVT.getSimpleVT().SimpleTy) {
3455 default: llvm_unreachable("Unhandled argument type!");
3459 if (GPR_idx != Num_GPR_Regs) {
3460 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3461 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3463 if (ObjectVT == MVT::i1)
3464 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3469 ArgSize = PtrByteSize;
3471 // All int arguments reserve stack space in the Darwin ABI.
3472 ArgOffset += PtrByteSize;
3476 case MVT::i64: // PPC64
3477 if (GPR_idx != Num_GPR_Regs) {
3478 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3479 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3481 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3482 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3483 // value to MVT::i64 and then truncate to the correct register size.
3484 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3489 ArgSize = PtrByteSize;
3491 // All int arguments reserve stack space in the Darwin ABI.
3497 // Every 4 bytes of argument space consumes one of the GPRs available for
3498 // argument passing.
3499 if (GPR_idx != Num_GPR_Regs) {
3501 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3504 if (FPR_idx != Num_FPR_Regs) {
3507 if (ObjectVT == MVT::f32)
3508 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3510 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3512 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3518 // All FP arguments reserve stack space in the Darwin ABI.
3519 ArgOffset += isPPC64 ? 8 : ObjSize;
3525 // Note that vector arguments in registers don't reserve stack space,
3526 // except in varargs functions.
3527 if (VR_idx != Num_VR_Regs) {
3528 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3529 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3531 while ((ArgOffset % 16) != 0) {
3532 ArgOffset += PtrByteSize;
3533 if (GPR_idx != Num_GPR_Regs)
3537 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3541 if (!isVarArg && !isPPC64) {
3542 // Vectors go after all the nonvectors.
3543 CurArgOffset = VecArgOffset;
3546 // Vectors are aligned.
3547 ArgOffset = ((ArgOffset+15)/16)*16;
3548 CurArgOffset = ArgOffset;
3556 // We need to load the argument to a virtual register if we determined above
3557 // that we ran out of physical registers of the appropriate type.
3559 int FI = MFI->CreateFixedObject(ObjSize,
3560 CurArgOffset + (ArgSize - ObjSize),
3562 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3563 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3564 false, false, false, 0);
3567 InVals.push_back(ArgVal);
3570 // Allow for Altivec parameters at the end, if needed.
3571 if (nAltivecParamsAtEnd) {
3572 MinReservedArea = ((MinReservedArea+15)/16)*16;
3573 MinReservedArea += 16*nAltivecParamsAtEnd;
3576 // Area that is at least reserved in the caller of this function.
3577 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3579 // Set the size that is at least reserved in caller of this function. Tail
3580 // call optimized functions' reserved stack space needs to be aligned so that
3581 // taking the difference between two stack areas will result in an aligned
3584 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3585 FuncInfo->setMinReservedArea(MinReservedArea);
3587 // If the function takes variable number of arguments, make a frame index for
3588 // the start of the first vararg value... for expansion of llvm.va_start.
3590 int Depth = ArgOffset;
3592 FuncInfo->setVarArgsFrameIndex(
3593 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3595 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3597 // If this function is vararg, store any remaining integer argument regs
3598 // to their spots on the stack so that they may be loaded by deferencing the
3599 // result of va_next.
3600 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3604 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3606 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3608 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3609 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3610 MachinePointerInfo(), false, false, 0);
3611 MemOps.push_back(Store);
3612 // Increment the address by four for the next argument to store
3613 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3614 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3618 if (!MemOps.empty())
3619 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3624 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3625 /// adjusted to accommodate the arguments for the tailcall.
3626 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3627 unsigned ParamSize) {
3629 if (!isTailCall) return 0;
3631 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3632 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3633 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3634 // Remember only if the new adjustement is bigger.
3635 if (SPDiff < FI->getTailCallSPDelta())
3636 FI->setTailCallSPDelta(SPDiff);
3641 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3642 /// for tail call optimization. Targets which want to do tail call
3643 /// optimization should implement this function.
3645 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3646 CallingConv::ID CalleeCC,
3648 const SmallVectorImpl<ISD::InputArg> &Ins,
3649 SelectionDAG& DAG) const {
3650 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3653 // Variable argument functions are not supported.
3657 MachineFunction &MF = DAG.getMachineFunction();
3658 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3659 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3660 // Functions containing by val parameters are not supported.
3661 for (unsigned i = 0; i != Ins.size(); i++) {
3662 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3663 if (Flags.isByVal()) return false;
3666 // Non-PIC/GOT tail calls are supported.
3667 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3670 // At the moment we can only do local tail calls (in same module, hidden
3671 // or protected) if we are generating PIC.
3672 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3673 return G->getGlobal()->hasHiddenVisibility()
3674 || G->getGlobal()->hasProtectedVisibility();
3680 /// isCallCompatibleAddress - Return the immediate to use if the specified
3681 /// 32-bit value is representable in the immediate field of a BxA instruction.
3682 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3683 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3684 if (!C) return nullptr;
3686 int Addr = C->getZExtValue();
3687 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3688 SignExtend32<26>(Addr) != Addr)
3689 return nullptr; // Top 6 bits have to be sext of immediate.
3691 return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
3692 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3697 struct TailCallArgumentInfo {
3702 TailCallArgumentInfo() : FrameIdx(0) {}
3707 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3709 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3711 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3712 SmallVectorImpl<SDValue> &MemOpChains,
3714 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3715 SDValue Arg = TailCallArgs[i].Arg;
3716 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3717 int FI = TailCallArgs[i].FrameIdx;
3718 // Store relative to framepointer.
3719 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3720 MachinePointerInfo::getFixedStack(FI),
3725 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3726 /// the appropriate stack slot for the tail call optimized function call.
3727 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3728 MachineFunction &MF,
3737 // Calculate the new stack slot for the return address.
3738 int SlotSize = isPPC64 ? 8 : 4;
3739 const PPCFrameLowering *FL =
3740 MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3741 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3742 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3743 NewRetAddrLoc, true);
3744 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3745 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3746 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3747 MachinePointerInfo::getFixedStack(NewRetAddr),
3750 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3751 // slot as the FP is never overwritten.
3753 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3754 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3756 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3757 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3758 MachinePointerInfo::getFixedStack(NewFPIdx),
3765 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3766 /// the position of the argument.
3768 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3769 SDValue Arg, int SPDiff, unsigned ArgOffset,
3770 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3771 int Offset = ArgOffset + SPDiff;
3772 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3773 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3774 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3775 SDValue FIN = DAG.getFrameIndex(FI, VT);
3776 TailCallArgumentInfo Info;
3778 Info.FrameIdxOp = FIN;
3780 TailCallArguments.push_back(Info);
3783 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3784 /// stack slot. Returns the chain as result and the loaded frame pointers in
3785 /// LROpOut/FPOpout. Used when tail calling.
3786 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3794 // Load the LR and FP stack slot for later adjusting.
3795 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3796 LROpOut = getReturnAddrFrameIndex(DAG);
3797 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3798 false, false, false, 0);
3799 Chain = SDValue(LROpOut.getNode(), 1);
3801 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3802 // slot as the FP is never overwritten.
3804 FPOpOut = getFramePointerFrameIndex(DAG);
3805 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3806 false, false, false, 0);
3807 Chain = SDValue(FPOpOut.getNode(), 1);
3813 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3814 /// by "Src" to address "Dst" of size "Size". Alignment information is
3815 /// specified by the specific parameter attribute. The copy will be passed as
3816 /// a byval function parameter.
3817 /// Sometimes what we are copying is the end of a larger object, the part that
3818 /// does not fit in registers.
3820 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3821 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3823 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
3824 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3825 false, false, false, MachinePointerInfo(),
3826 MachinePointerInfo());
3829 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3832 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3833 SDValue Arg, SDValue PtrOff, int SPDiff,
3834 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3835 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3836 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3838 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3843 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3845 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3846 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3847 DAG.getConstant(ArgOffset, dl, PtrVT));
3849 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3850 MachinePointerInfo(), false, false, 0));
3851 // Calculate and remember argument location.
3852 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3857 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3858 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3859 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3860 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3861 MachineFunction &MF = DAG.getMachineFunction();
3863 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3864 // might overwrite each other in case of tail call optimization.
3865 SmallVector<SDValue, 8> MemOpChains2;
3866 // Do not flag preceding copytoreg stuff together with the following stuff.
3868 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3870 if (!MemOpChains2.empty())
3871 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3873 // Store the return address to the appropriate stack slot.
3874 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3875 isPPC64, isDarwinABI, dl);
3877 // Emit callseq_end just before tailcall node.
3878 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
3879 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3880 InFlag = Chain.getValue(1);
3883 // Is this global address that of a function that can be called by name? (as
3884 // opposed to something that must hold a descriptor for an indirect call).
3885 static bool isFunctionGlobalAddress(SDValue Callee) {
3886 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3887 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3888 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3891 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3898 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3899 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3900 bool isTailCall, bool IsPatchPoint,
3901 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3902 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3903 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3905 bool isPPC64 = Subtarget.isPPC64();
3906 bool isSVR4ABI = Subtarget.isSVR4ABI();
3907 bool isELFv2ABI = Subtarget.isELFv2ABI();
3909 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3910 NodeTys.push_back(MVT::Other); // Returns a chain
3911 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3913 unsigned CallOpc = PPCISD::CALL;
3915 bool needIndirectCall = true;
3916 if (!isSVR4ABI || !isPPC64)
3917 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3918 // If this is an absolute destination address, use the munged value.
3919 Callee = SDValue(Dest, 0);
3920 needIndirectCall = false;
3923 if (isFunctionGlobalAddress(Callee)) {
3924 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3925 // A call to a TLS address is actually an indirect call to a
3926 // thread-specific pointer.
3927 unsigned OpFlags = 0;
3928 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3929 (Subtarget.getTargetTriple().isMacOSX() &&
3930 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3931 (G->getGlobal()->isDeclaration() ||
3932 G->getGlobal()->isWeakForLinker())) ||
3933 (Subtarget.isTargetELF() && !isPPC64 &&
3934 !G->getGlobal()->hasLocalLinkage() &&
3935 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3936 // PC-relative references to external symbols should go through $stub,
3937 // unless we're building with the leopard linker or later, which
3938 // automatically synthesizes these stubs.
3939 OpFlags = PPCII::MO_PLT_OR_STUB;
3942 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3943 // every direct call is) turn it into a TargetGlobalAddress /
3944 // TargetExternalSymbol node so that legalize doesn't hack it.
3945 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3946 Callee.getValueType(), 0, OpFlags);
3947 needIndirectCall = false;
3950 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3951 unsigned char OpFlags = 0;
3953 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3954 (Subtarget.getTargetTriple().isMacOSX() &&
3955 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3956 (Subtarget.isTargetELF() && !isPPC64 &&
3957 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3958 // PC-relative references to external symbols should go through $stub,
3959 // unless we're building with the leopard linker or later, which
3960 // automatically synthesizes these stubs.
3961 OpFlags = PPCII::MO_PLT_OR_STUB;
3964 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3966 needIndirectCall = false;
3970 // We'll form an invalid direct call when lowering a patchpoint; the full
3971 // sequence for an indirect call is complicated, and many of the
3972 // instructions introduced might have side effects (and, thus, can't be
3973 // removed later). The call itself will be removed as soon as the
3974 // argument/return lowering is complete, so the fact that it has the wrong
3975 // kind of operands should not really matter.
3976 needIndirectCall = false;
3979 if (needIndirectCall) {
3980 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3981 // to do the call, we can't use PPCISD::CALL.
3982 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3984 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3985 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3986 // entry point, but to the function descriptor (the function entry point
3987 // address is part of the function descriptor though).
3988 // The function descriptor is a three doubleword structure with the
3989 // following fields: function entry point, TOC base address and
3990 // environment pointer.
3991 // Thus for a call through a function pointer, the following actions need
3993 // 1. Save the TOC of the caller in the TOC save area of its stack
3994 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3995 // 2. Load the address of the function entry point from the function
3997 // 3. Load the TOC of the callee from the function descriptor into r2.
3998 // 4. Load the environment pointer from the function descriptor into
4000 // 5. Branch to the function entry point address.
4001 // 6. On return of the callee, the TOC of the caller needs to be
4002 // restored (this is done in FinishCall()).
4004 // The loads are scheduled at the beginning of the call sequence, and the
4005 // register copies are flagged together to ensure that no other
4006 // operations can be scheduled in between. E.g. without flagging the
4007 // copies together, a TOC access in the caller could be scheduled between
4008 // the assignment of the callee TOC and the branch to the callee, which
4009 // results in the TOC access going through the TOC of the callee instead
4010 // of going through the TOC of the caller, which leads to incorrect code.
4012 // Load the address of the function entry point from the function
4014 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4015 if (LDChain.getValueType() == MVT::Glue)
4016 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4018 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4020 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4021 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4022 false, false, LoadsInv, 8);
4024 // Load environment pointer into r11.
4025 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4026 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4027 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4028 MPI.getWithOffset(16), false, false,
4031 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4032 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4033 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4034 MPI.getWithOffset(8), false, false,
4037 setUsesTOCBasePtr(DAG);
4038 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4040 Chain = TOCVal.getValue(0);
4041 InFlag = TOCVal.getValue(1);
4043 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4046 Chain = EnvVal.getValue(0);
4047 InFlag = EnvVal.getValue(1);
4049 MTCTROps[0] = Chain;
4050 MTCTROps[1] = LoadFuncPtr;
4051 MTCTROps[2] = InFlag;
4054 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4055 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4056 InFlag = Chain.getValue(1);
4059 NodeTys.push_back(MVT::Other);
4060 NodeTys.push_back(MVT::Glue);
4061 Ops.push_back(Chain);
4062 CallOpc = PPCISD::BCTRL;
4063 Callee.setNode(nullptr);
4064 // Add use of X11 (holding environment pointer)
4065 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4066 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4067 // Add CTR register as callee so a bctr can be emitted later.
4069 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4072 // If this is a direct call, pass the chain and the callee.
4073 if (Callee.getNode()) {
4074 Ops.push_back(Chain);
4075 Ops.push_back(Callee);
4077 // If this is a tail call add stack pointer delta.
4079 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4081 // Add argument registers to the end of the list so that they are known live
4083 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4084 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4085 RegsToPass[i].second.getValueType()));
4087 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4089 if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4090 setUsesTOCBasePtr(DAG);
4091 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4098 bool isLocalCall(const SDValue &Callee)
4100 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4101 return !G->getGlobal()->isDeclaration() &&
4102 !G->getGlobal()->isWeakForLinker();
4107 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4108 CallingConv::ID CallConv, bool isVarArg,
4109 const SmallVectorImpl<ISD::InputArg> &Ins,
4110 SDLoc dl, SelectionDAG &DAG,
4111 SmallVectorImpl<SDValue> &InVals) const {
4113 SmallVector<CCValAssign, 16> RVLocs;
4114 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4116 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4118 // Copy all of the result registers out of their specified physreg.
4119 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4120 CCValAssign &VA = RVLocs[i];
4121 assert(VA.isRegLoc() && "Can only return in registers!");
4123 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4124 VA.getLocReg(), VA.getLocVT(), InFlag);
4125 Chain = Val.getValue(1);
4126 InFlag = Val.getValue(2);
4128 switch (VA.getLocInfo()) {
4129 default: llvm_unreachable("Unknown loc info!");
4130 case CCValAssign::Full: break;
4131 case CCValAssign::AExt:
4132 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4134 case CCValAssign::ZExt:
4135 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4136 DAG.getValueType(VA.getValVT()));
4137 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4139 case CCValAssign::SExt:
4140 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4141 DAG.getValueType(VA.getValVT()));
4142 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4146 InVals.push_back(Val);
4153 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4154 bool isTailCall, bool isVarArg, bool IsPatchPoint,
4156 SmallVector<std::pair<unsigned, SDValue>, 8>
4158 SDValue InFlag, SDValue Chain,
4159 SDValue CallSeqStart, SDValue &Callee,
4160 int SPDiff, unsigned NumBytes,
4161 const SmallVectorImpl<ISD::InputArg> &Ins,
4162 SmallVectorImpl<SDValue> &InVals,
4163 ImmutableCallSite *CS) const {
4165 std::vector<EVT> NodeTys;
4166 SmallVector<SDValue, 8> Ops;
4167 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4168 SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4169 Ops, NodeTys, CS, Subtarget);
4171 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4172 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4173 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4175 // When performing tail call optimization the callee pops its arguments off
4176 // the stack. Account for this here so these bytes can be pushed back on in
4177 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4178 int BytesCalleePops =
4179 (CallConv == CallingConv::Fast &&
4180 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4182 // Add a register mask operand representing the call-preserved registers.
4183 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4184 const uint32_t *Mask =
4185 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4186 assert(Mask && "Missing call preserved mask for calling convention");
4187 Ops.push_back(DAG.getRegisterMask(Mask));
4189 if (InFlag.getNode())
4190 Ops.push_back(InFlag);
4194 assert(((Callee.getOpcode() == ISD::Register &&
4195 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4196 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4197 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4198 isa<ConstantSDNode>(Callee)) &&
4199 "Expecting an global address, external symbol, absolute value or register");
4201 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4204 // Add a NOP immediately after the branch instruction when using the 64-bit
4205 // SVR4 ABI. At link time, if caller and callee are in a different module and
4206 // thus have a different TOC, the call will be replaced with a call to a stub
4207 // function which saves the current TOC, loads the TOC of the callee and
4208 // branches to the callee. The NOP will be replaced with a load instruction
4209 // which restores the TOC of the caller from the TOC save slot of the current
4210 // stack frame. If caller and callee belong to the same module (and have the
4211 // same TOC), the NOP will remain unchanged.
4213 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4215 if (CallOpc == PPCISD::BCTRL) {
4216 // This is a call through a function pointer.
4217 // Restore the caller TOC from the save area into R2.
4218 // See PrepareCall() for more information about calls through function
4219 // pointers in the 64-bit SVR4 ABI.
4220 // We are using a target-specific load with r2 hard coded, because the
4221 // result of a target-independent load would never go directly into r2,
4222 // since r2 is a reserved register (which prevents the register allocator
4223 // from allocating it), resulting in an additional register being
4224 // allocated and an unnecessary move instruction being generated.
4225 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4227 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4228 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4229 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4230 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4231 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4233 // The address needs to go after the chain input but before the flag (or
4234 // any other variadic arguments).
4235 Ops.insert(std::next(Ops.begin()), AddTOC);
4236 } else if ((CallOpc == PPCISD::CALL) &&
4237 (!isLocalCall(Callee) ||
4238 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4239 // Otherwise insert NOP for non-local calls.
4240 CallOpc = PPCISD::CALL_NOP;
4243 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4244 InFlag = Chain.getValue(1);
4246 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4247 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4250 InFlag = Chain.getValue(1);
4252 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4253 Ins, dl, DAG, InVals);
4257 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4258 SmallVectorImpl<SDValue> &InVals) const {
4259 SelectionDAG &DAG = CLI.DAG;
4261 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4262 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4263 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4264 SDValue Chain = CLI.Chain;
4265 SDValue Callee = CLI.Callee;
4266 bool &isTailCall = CLI.IsTailCall;
4267 CallingConv::ID CallConv = CLI.CallConv;
4268 bool isVarArg = CLI.IsVarArg;
4269 bool IsPatchPoint = CLI.IsPatchPoint;
4270 ImmutableCallSite *CS = CLI.CS;
4273 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4276 if (!isTailCall && CS && CS->isMustTailCall())
4277 report_fatal_error("failed to perform tail call elimination on a call "
4278 "site marked musttail");
4280 if (Subtarget.isSVR4ABI()) {
4281 if (Subtarget.isPPC64())
4282 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4283 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4284 dl, DAG, InVals, CS);
4286 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4287 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4288 dl, DAG, InVals, CS);
4291 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4292 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4293 dl, DAG, InVals, CS);
4297 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4298 CallingConv::ID CallConv, bool isVarArg,
4299 bool isTailCall, bool IsPatchPoint,
4300 const SmallVectorImpl<ISD::OutputArg> &Outs,
4301 const SmallVectorImpl<SDValue> &OutVals,
4302 const SmallVectorImpl<ISD::InputArg> &Ins,
4303 SDLoc dl, SelectionDAG &DAG,
4304 SmallVectorImpl<SDValue> &InVals,
4305 ImmutableCallSite *CS) const {
4306 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4307 // of the 32-bit SVR4 ABI stack frame layout.
4309 assert((CallConv == CallingConv::C ||
4310 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4312 unsigned PtrByteSize = 4;
4314 MachineFunction &MF = DAG.getMachineFunction();
4316 // Mark this function as potentially containing a function that contains a
4317 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4318 // and restoring the callers stack pointer in this functions epilog. This is
4319 // done because by tail calling the called function might overwrite the value
4320 // in this function's (MF) stack pointer stack slot 0(SP).
4321 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4322 CallConv == CallingConv::Fast)
4323 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4325 // Count how many bytes are to be pushed on the stack, including the linkage
4326 // area, parameter list area and the part of the local variable space which
4327 // contains copies of aggregates which are passed by value.
4329 // Assign locations to all of the outgoing arguments.
4330 SmallVector<CCValAssign, 16> ArgLocs;
4331 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4334 // Reserve space for the linkage area on the stack.
4335 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4339 // Handle fixed and variable vector arguments differently.
4340 // Fixed vector arguments go into registers as long as registers are
4341 // available. Variable vector arguments always go into memory.
4342 unsigned NumArgs = Outs.size();
4344 for (unsigned i = 0; i != NumArgs; ++i) {
4345 MVT ArgVT = Outs[i].VT;
4346 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4349 if (Outs[i].IsFixed) {
4350 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4353 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4359 errs() << "Call operand #" << i << " has unhandled type "
4360 << EVT(ArgVT).getEVTString() << "\n";
4362 llvm_unreachable(nullptr);
4366 // All arguments are treated the same.
4367 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4370 // Assign locations to all of the outgoing aggregate by value arguments.
4371 SmallVector<CCValAssign, 16> ByValArgLocs;
4372 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4373 ByValArgLocs, *DAG.getContext());
4375 // Reserve stack space for the allocations in CCInfo.
4376 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4378 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4380 // Size of the linkage area, parameter list area and the part of the local
4381 // space variable where copies of aggregates which are passed by value are
4383 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4385 // Calculate by how many bytes the stack has to be adjusted in case of tail
4386 // call optimization.
4387 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4389 // Adjust the stack pointer for the new arguments...
4390 // These operations are automatically eliminated by the prolog/epilog pass
4391 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4393 SDValue CallSeqStart = Chain;
4395 // Load the return address and frame pointer so it can be moved somewhere else
4398 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4401 // Set up a copy of the stack pointer for use loading and storing any
4402 // arguments that may not fit in the registers available for argument
4404 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4406 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4407 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4408 SmallVector<SDValue, 8> MemOpChains;
4410 bool seenFloatArg = false;
4411 // Walk the register/memloc assignments, inserting copies/loads.
4412 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4415 CCValAssign &VA = ArgLocs[i];
4416 SDValue Arg = OutVals[i];
4417 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4419 if (Flags.isByVal()) {
4420 // Argument is an aggregate which is passed by value, thus we need to
4421 // create a copy of it in the local variable space of the current stack
4422 // frame (which is the stack frame of the caller) and pass the address of
4423 // this copy to the callee.
4424 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4425 CCValAssign &ByValVA = ByValArgLocs[j++];
4426 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4428 // Memory reserved in the local variable space of the callers stack frame.
4429 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4431 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4432 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4434 // Create a copy of the argument in the local area of the current
4436 SDValue MemcpyCall =
4437 CreateCopyOfByValArgument(Arg, PtrOff,
4438 CallSeqStart.getNode()->getOperand(0),
4441 // This must go outside the CALLSEQ_START..END.
4442 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4443 CallSeqStart.getNode()->getOperand(1),
4445 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4446 NewCallSeqStart.getNode());
4447 Chain = CallSeqStart = NewCallSeqStart;
4449 // Pass the address of the aggregate copy on the stack either in a
4450 // physical register or in the parameter list area of the current stack
4451 // frame to the callee.
4455 if (VA.isRegLoc()) {
4456 if (Arg.getValueType() == MVT::i1)
4457 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4459 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4460 // Put argument in a physical register.
4461 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4463 // Put argument in the parameter list area of the current stack frame.
4464 assert(VA.isMemLoc());
4465 unsigned LocMemOffset = VA.getLocMemOffset();
4468 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4469 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4471 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4472 MachinePointerInfo(),
4475 // Calculate and remember argument location.
4476 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4482 if (!MemOpChains.empty())
4483 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4485 // Build a sequence of copy-to-reg nodes chained together with token chain
4486 // and flag operands which copy the outgoing args into the appropriate regs.
4488 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4489 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4490 RegsToPass[i].second, InFlag);
4491 InFlag = Chain.getValue(1);
4494 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4497 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4498 SDValue Ops[] = { Chain, InFlag };
4500 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4501 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4503 InFlag = Chain.getValue(1);
4507 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4508 false, TailCallArguments);
4510 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4511 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4512 NumBytes, Ins, InVals, CS);
4515 // Copy an argument into memory, being careful to do this outside the
4516 // call sequence for the call to which the argument belongs.
4518 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4519 SDValue CallSeqStart,
4520 ISD::ArgFlagsTy Flags,
4523 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4524 CallSeqStart.getNode()->getOperand(0),
4526 // The MEMCPY must go outside the CALLSEQ_START..END.
4527 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4528 CallSeqStart.getNode()->getOperand(1),
4530 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4531 NewCallSeqStart.getNode());
4532 return NewCallSeqStart;
4536 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4537 CallingConv::ID CallConv, bool isVarArg,
4538 bool isTailCall, bool IsPatchPoint,
4539 const SmallVectorImpl<ISD::OutputArg> &Outs,
4540 const SmallVectorImpl<SDValue> &OutVals,
4541 const SmallVectorImpl<ISD::InputArg> &Ins,
4542 SDLoc dl, SelectionDAG &DAG,
4543 SmallVectorImpl<SDValue> &InVals,
4544 ImmutableCallSite *CS) const {
4546 bool isELFv2ABI = Subtarget.isELFv2ABI();
4547 bool isLittleEndian = Subtarget.isLittleEndian();
4548 unsigned NumOps = Outs.size();
4550 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4551 unsigned PtrByteSize = 8;
4553 MachineFunction &MF = DAG.getMachineFunction();
4555 // Mark this function as potentially containing a function that contains a
4556 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4557 // and restoring the callers stack pointer in this functions epilog. This is
4558 // done because by tail calling the called function might overwrite the value
4559 // in this function's (MF) stack pointer stack slot 0(SP).
4560 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4561 CallConv == CallingConv::Fast)
4562 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4564 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4565 "fastcc not supported on varargs functions");
4567 // Count how many bytes are to be pushed on the stack, including the linkage
4568 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4569 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4570 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4571 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4572 unsigned NumBytes = LinkageSize;
4573 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4574 unsigned &QFPR_idx = FPR_idx;
4576 static const MCPhysReg GPR[] = {
4577 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4578 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4580 static const MCPhysReg VR[] = {
4581 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4582 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4584 static const MCPhysReg VSRH[] = {
4585 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4586 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4589 const unsigned NumGPRs = array_lengthof(GPR);
4590 const unsigned NumFPRs = 13;
4591 const unsigned NumVRs = array_lengthof(VR);
4592 const unsigned NumQFPRs = NumFPRs;
4594 // When using the fast calling convention, we don't provide backing for
4595 // arguments that will be in registers.
4596 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4598 // Add up all the space actually used.
4599 for (unsigned i = 0; i != NumOps; ++i) {
4600 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4601 EVT ArgVT = Outs[i].VT;
4602 EVT OrigVT = Outs[i].ArgVT;
4604 if (CallConv == CallingConv::Fast) {
4605 if (Flags.isByVal())
4606 NumGPRsUsed += (Flags.getByValSize()+7)/8;
4608 switch (ArgVT.getSimpleVT().SimpleTy) {
4609 default: llvm_unreachable("Unexpected ValueType for argument!");
4613 if (++NumGPRsUsed <= NumGPRs)
4622 if (++NumVRsUsed <= NumVRs)
4626 // When using QPX, this is handled like a FP register, otherwise, it
4627 // is an Altivec register.
4628 if (Subtarget.hasQPX()) {
4629 if (++NumFPRsUsed <= NumFPRs)
4632 if (++NumVRsUsed <= NumVRs)
4638 case MVT::v4f64: // QPX
4639 case MVT::v4i1: // QPX
4640 if (++NumFPRsUsed <= NumFPRs)
4646 /* Respect alignment of argument on the stack. */
4648 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4649 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4651 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4652 if (Flags.isInConsecutiveRegsLast())
4653 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4656 unsigned NumBytesActuallyUsed = NumBytes;
4658 // The prolog code of the callee may store up to 8 GPR argument registers to
4659 // the stack, allowing va_start to index over them in memory if its varargs.
4660 // Because we cannot tell if this is needed on the caller side, we have to
4661 // conservatively assume that it is needed. As such, make sure we have at
4662 // least enough stack space for the caller to store the 8 GPRs.
4663 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4664 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4666 // Tail call needs the stack to be aligned.
4667 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4668 CallConv == CallingConv::Fast)
4669 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4671 // Calculate by how many bytes the stack has to be adjusted in case of tail
4672 // call optimization.
4673 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4675 // To protect arguments on the stack from being clobbered in a tail call,
4676 // force all the loads to happen before doing any other lowering.
4678 Chain = DAG.getStackArgumentTokenFactor(Chain);
4680 // Adjust the stack pointer for the new arguments...
4681 // These operations are automatically eliminated by the prolog/epilog pass
4682 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4684 SDValue CallSeqStart = Chain;
4686 // Load the return address and frame pointer so it can be move somewhere else
4689 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4692 // Set up a copy of the stack pointer for use loading and storing any
4693 // arguments that may not fit in the registers available for argument
4695 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4697 // Figure out which arguments are going to go in registers, and which in
4698 // memory. Also, if this is a vararg function, floating point operations
4699 // must be stored to our stack, and loaded into integer regs as well, if
4700 // any integer regs are available for argument passing.
4701 unsigned ArgOffset = LinkageSize;
4703 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4704 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4706 SmallVector<SDValue, 8> MemOpChains;
4707 for (unsigned i = 0; i != NumOps; ++i) {
4708 SDValue Arg = OutVals[i];
4709 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4710 EVT ArgVT = Outs[i].VT;
4711 EVT OrigVT = Outs[i].ArgVT;
4713 // PtrOff will be used to store the current argument to the stack if a
4714 // register cannot be found for it.
4717 // We re-align the argument offset for each argument, except when using the
4718 // fast calling convention, when we need to make sure we do that only when
4719 // we'll actually use a stack slot.
4720 auto ComputePtrOff = [&]() {
4721 /* Respect alignment of argument on the stack. */
4723 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4724 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4726 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
4728 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4731 if (CallConv != CallingConv::Fast) {
4734 /* Compute GPR index associated with argument offset. */
4735 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4736 GPR_idx = std::min(GPR_idx, NumGPRs);
4739 // Promote integers to 64-bit values.
4740 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4741 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4742 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4743 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4746 // FIXME memcpy is used way more than necessary. Correctness first.
4747 // Note: "by value" is code for passing a structure by value, not
4749 if (Flags.isByVal()) {
4750 // Note: Size includes alignment padding, so
4751 // struct x { short a; char b; }
4752 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4753 // These are the proper values we need for right-justifying the
4754 // aggregate in a parameter register.
4755 unsigned Size = Flags.getByValSize();
4757 // An empty aggregate parameter takes up no storage and no
4762 if (CallConv == CallingConv::Fast)
4765 // All aggregates smaller than 8 bytes must be passed right-justified.
4766 if (Size==1 || Size==2 || Size==4) {
4767 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4768 if (GPR_idx != NumGPRs) {
4769 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4770 MachinePointerInfo(), VT,
4771 false, false, false, 0);
4772 MemOpChains.push_back(Load.getValue(1));
4773 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4775 ArgOffset += PtrByteSize;
4780 if (GPR_idx == NumGPRs && Size < 8) {
4781 SDValue AddPtr = PtrOff;
4782 if (!isLittleEndian) {
4783 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
4784 PtrOff.getValueType());
4785 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4787 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4790 ArgOffset += PtrByteSize;
4793 // Copy entire object into memory. There are cases where gcc-generated
4794 // code assumes it is there, even if it could be put entirely into
4795 // registers. (This is not what the doc says.)
4797 // FIXME: The above statement is likely due to a misunderstanding of the
4798 // documents. All arguments must be copied into the parameter area BY
4799 // THE CALLEE in the event that the callee takes the address of any
4800 // formal argument. That has not yet been implemented. However, it is
4801 // reasonable to use the stack area as a staging area for the register
4804 // Skip this for small aggregates, as we will use the same slot for a
4805 // right-justified copy, below.
4807 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4811 // When a register is available, pass a small aggregate right-justified.
4812 if (Size < 8 && GPR_idx != NumGPRs) {
4813 // The easiest way to get this right-justified in a register
4814 // is to copy the structure into the rightmost portion of a
4815 // local variable slot, then load the whole slot into the
4817 // FIXME: The memcpy seems to produce pretty awful code for
4818 // small aggregates, particularly for packed ones.
4819 // FIXME: It would be preferable to use the slot in the
4820 // parameter save area instead of a new local variable.
4821 SDValue AddPtr = PtrOff;
4822 if (!isLittleEndian) {
4823 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
4824 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4826 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4830 // Load the slot into the register.
4831 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4832 MachinePointerInfo(),
4833 false, false, false, 0);
4834 MemOpChains.push_back(Load.getValue(1));
4835 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4837 // Done with this argument.
4838 ArgOffset += PtrByteSize;
4842 // For aggregates larger than PtrByteSize, copy the pieces of the
4843 // object that fit into registers from the parameter save area.
4844 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4845 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
4846 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4847 if (GPR_idx != NumGPRs) {
4848 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4849 MachinePointerInfo(),
4850 false, false, false, 0);
4851 MemOpChains.push_back(Load.getValue(1));
4852 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4853 ArgOffset += PtrByteSize;
4855 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4862 switch (Arg.getSimpleValueType().SimpleTy) {
4863 default: llvm_unreachable("Unexpected ValueType for argument!");
4867 // These can be scalar arguments or elements of an integer array type
4868 // passed directly. Clang may use those instead of "byval" aggregate
4869 // types to avoid forcing arguments to memory unnecessarily.
4870 if (GPR_idx != NumGPRs) {
4871 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4873 if (CallConv == CallingConv::Fast)
4876 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4877 true, isTailCall, false, MemOpChains,
4878 TailCallArguments, dl);
4879 if (CallConv == CallingConv::Fast)
4880 ArgOffset += PtrByteSize;
4882 if (CallConv != CallingConv::Fast)
4883 ArgOffset += PtrByteSize;
4887 // These can be scalar arguments or elements of a float array type
4888 // passed directly. The latter are used to implement ELFv2 homogenous
4889 // float aggregates.
4891 // Named arguments go into FPRs first, and once they overflow, the
4892 // remaining arguments go into GPRs and then the parameter save area.
4893 // Unnamed arguments for vararg functions always go to GPRs and
4894 // then the parameter save area. For now, put all arguments to vararg
4895 // routines always in both locations (FPR *and* GPR or stack slot).
4896 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4897 bool NeededLoad = false;
4899 // First load the argument into the next available FPR.
4900 if (FPR_idx != NumFPRs)
4901 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4903 // Next, load the argument into GPR or stack slot if needed.
4904 if (!NeedGPROrStack)
4906 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4907 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4908 // once we support fp <-> gpr moves.
4910 // In the non-vararg case, this can only ever happen in the
4911 // presence of f32 array types, since otherwise we never run
4912 // out of FPRs before running out of GPRs.
4915 // Double values are always passed in a single GPR.
4916 if (Arg.getValueType() != MVT::f32) {
4917 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4919 // Non-array float values are extended and passed in a GPR.
4920 } else if (!Flags.isInConsecutiveRegs()) {
4921 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4922 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4924 // If we have an array of floats, we collect every odd element
4925 // together with its predecessor into one GPR.
4926 } else if (ArgOffset % PtrByteSize != 0) {
4928 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4929 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4930 if (!isLittleEndian)
4932 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4934 // The final element, if even, goes into the first half of a GPR.
4935 } else if (Flags.isInConsecutiveRegsLast()) {
4936 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4937 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4938 if (!isLittleEndian)
4939 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4940 DAG.getConstant(32, dl, MVT::i32));
4942 // Non-final even elements are skipped; they will be handled
4943 // together the with subsequent argument on the next go-around.
4947 if (ArgVal.getNode())
4948 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4950 if (CallConv == CallingConv::Fast)
4953 // Single-precision floating-point values are mapped to the
4954 // second (rightmost) word of the stack doubleword.
4955 if (Arg.getValueType() == MVT::f32 &&
4956 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4957 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
4958 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4961 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4962 true, isTailCall, false, MemOpChains,
4963 TailCallArguments, dl);
4967 // When passing an array of floats, the array occupies consecutive
4968 // space in the argument area; only round up to the next doubleword
4969 // at the end of the array. Otherwise, each float takes 8 bytes.
4970 if (CallConv != CallingConv::Fast || NeededLoad) {
4971 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4972 Flags.isInConsecutiveRegs()) ? 4 : 8;
4973 if (Flags.isInConsecutiveRegsLast())
4974 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4985 if (!Subtarget.hasQPX()) {
4986 // These can be scalar arguments or elements of a vector array type
4987 // passed directly. The latter are used to implement ELFv2 homogenous
4988 // vector aggregates.
4990 // For a varargs call, named arguments go into VRs or on the stack as
4991 // usual; unnamed arguments always go to the stack or the corresponding
4992 // GPRs when within range. For now, we always put the value in both
4993 // locations (or even all three).
4995 // We could elide this store in the case where the object fits
4996 // entirely in R registers. Maybe later.
4997 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4998 MachinePointerInfo(), false, false, 0);
4999 MemOpChains.push_back(Store);
5000 if (VR_idx != NumVRs) {
5001 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5002 MachinePointerInfo(),
5003 false, false, false, 0);
5004 MemOpChains.push_back(Load.getValue(1));
5006 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5007 Arg.getSimpleValueType() == MVT::v2i64) ?
5008 VSRH[VR_idx] : VR[VR_idx];
5011 RegsToPass.push_back(std::make_pair(VReg, Load));
5014 for (unsigned i=0; i<16; i+=PtrByteSize) {
5015 if (GPR_idx == NumGPRs)
5017 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5018 DAG.getConstant(i, dl, PtrVT));
5019 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5020 false, false, false, 0);
5021 MemOpChains.push_back(Load.getValue(1));
5022 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5027 // Non-varargs Altivec params go into VRs or on the stack.
5028 if (VR_idx != NumVRs) {
5029 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5030 Arg.getSimpleValueType() == MVT::v2i64) ?
5031 VSRH[VR_idx] : VR[VR_idx];
5034 RegsToPass.push_back(std::make_pair(VReg, Arg));
5036 if (CallConv == CallingConv::Fast)
5039 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5040 true, isTailCall, true, MemOpChains,
5041 TailCallArguments, dl);
5042 if (CallConv == CallingConv::Fast)
5046 if (CallConv != CallingConv::Fast)
5051 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5052 "Invalid QPX parameter type");
5057 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5059 // We could elide this store in the case where the object fits
5060 // entirely in R registers. Maybe later.
5061 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5062 MachinePointerInfo(), false, false, 0);
5063 MemOpChains.push_back(Store);
5064 if (QFPR_idx != NumQFPRs) {
5065 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5066 Store, PtrOff, MachinePointerInfo(),
5067 false, false, false, 0);
5068 MemOpChains.push_back(Load.getValue(1));
5069 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5071 ArgOffset += (IsF32 ? 16 : 32);
5072 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5073 if (GPR_idx == NumGPRs)
5075 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5076 DAG.getConstant(i, dl, PtrVT));
5077 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5078 false, false, false, 0);
5079 MemOpChains.push_back(Load.getValue(1));
5080 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5085 // Non-varargs QPX params go into registers or on the stack.
5086 if (QFPR_idx != NumQFPRs) {
5087 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5089 if (CallConv == CallingConv::Fast)
5092 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5093 true, isTailCall, true, MemOpChains,
5094 TailCallArguments, dl);
5095 if (CallConv == CallingConv::Fast)
5096 ArgOffset += (IsF32 ? 16 : 32);
5099 if (CallConv != CallingConv::Fast)
5100 ArgOffset += (IsF32 ? 16 : 32);
5106 assert(NumBytesActuallyUsed == ArgOffset);
5107 (void)NumBytesActuallyUsed;
5109 if (!MemOpChains.empty())
5110 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5112 // Check if this is an indirect call (MTCTR/BCTRL).
5113 // See PrepareCall() for more information about calls through function
5114 // pointers in the 64-bit SVR4 ABI.
5115 if (!isTailCall && !IsPatchPoint &&
5116 !isFunctionGlobalAddress(Callee) &&
5117 !isa<ExternalSymbolSDNode>(Callee)) {
5118 // Load r2 into a virtual register and store it to the TOC save area.
5119 setUsesTOCBasePtr(DAG);
5120 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5121 // TOC save area offset.
5122 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5123 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5124 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5125 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5126 MachinePointerInfo::getStack(TOCSaveOffset),
5128 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5129 // This does not mean the MTCTR instruction must use R12; it's easier
5130 // to model this as an extra parameter, so do that.
5131 if (isELFv2ABI && !IsPatchPoint)
5132 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5135 // Build a sequence of copy-to-reg nodes chained together with token chain
5136 // and flag operands which copy the outgoing args into the appropriate regs.
5138 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5139 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5140 RegsToPass[i].second, InFlag);
5141 InFlag = Chain.getValue(1);
5145 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5146 FPOp, true, TailCallArguments);
5148 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5149 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5150 NumBytes, Ins, InVals, CS);
5154 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5155 CallingConv::ID CallConv, bool isVarArg,
5156 bool isTailCall, bool IsPatchPoint,
5157 const SmallVectorImpl<ISD::OutputArg> &Outs,
5158 const SmallVectorImpl<SDValue> &OutVals,
5159 const SmallVectorImpl<ISD::InputArg> &Ins,
5160 SDLoc dl, SelectionDAG &DAG,
5161 SmallVectorImpl<SDValue> &InVals,
5162 ImmutableCallSite *CS) const {
5164 unsigned NumOps = Outs.size();
5166 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5167 bool isPPC64 = PtrVT == MVT::i64;
5168 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5170 MachineFunction &MF = DAG.getMachineFunction();
5172 // Mark this function as potentially containing a function that contains a
5173 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5174 // and restoring the callers stack pointer in this functions epilog. This is
5175 // done because by tail calling the called function might overwrite the value
5176 // in this function's (MF) stack pointer stack slot 0(SP).
5177 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5178 CallConv == CallingConv::Fast)
5179 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5181 // Count how many bytes are to be pushed on the stack, including the linkage
5182 // area, and parameter passing area. We start with 24/48 bytes, which is
5183 // prereserved space for [SP][CR][LR][3 x unused].
5184 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5185 unsigned NumBytes = LinkageSize;
5187 // Add up all the space actually used.
5188 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5189 // they all go in registers, but we must reserve stack space for them for
5190 // possible use by the caller. In varargs or 64-bit calls, parameters are
5191 // assigned stack space in order, with padding so Altivec parameters are
5193 unsigned nAltivecParamsAtEnd = 0;
5194 for (unsigned i = 0; i != NumOps; ++i) {
5195 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5196 EVT ArgVT = Outs[i].VT;
5197 // Varargs Altivec parameters are padded to a 16 byte boundary.
5198 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5199 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5200 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5201 if (!isVarArg && !isPPC64) {
5202 // Non-varargs Altivec parameters go after all the non-Altivec
5203 // parameters; handle those later so we know how much padding we need.
5204 nAltivecParamsAtEnd++;
5207 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5208 NumBytes = ((NumBytes+15)/16)*16;
5210 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5213 // Allow for Altivec parameters at the end, if needed.
5214 if (nAltivecParamsAtEnd) {
5215 NumBytes = ((NumBytes+15)/16)*16;
5216 NumBytes += 16*nAltivecParamsAtEnd;
5219 // The prolog code of the callee may store up to 8 GPR argument registers to
5220 // the stack, allowing va_start to index over them in memory if its varargs.
5221 // Because we cannot tell if this is needed on the caller side, we have to
5222 // conservatively assume that it is needed. As such, make sure we have at
5223 // least enough stack space for the caller to store the 8 GPRs.
5224 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5226 // Tail call needs the stack to be aligned.
5227 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5228 CallConv == CallingConv::Fast)
5229 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5231 // Calculate by how many bytes the stack has to be adjusted in case of tail
5232 // call optimization.
5233 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5235 // To protect arguments on the stack from being clobbered in a tail call,
5236 // force all the loads to happen before doing any other lowering.
5238 Chain = DAG.getStackArgumentTokenFactor(Chain);
5240 // Adjust the stack pointer for the new arguments...
5241 // These operations are automatically eliminated by the prolog/epilog pass
5242 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5244 SDValue CallSeqStart = Chain;
5246 // Load the return address and frame pointer so it can be move somewhere else
5249 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5252 // Set up a copy of the stack pointer for use loading and storing any
5253 // arguments that may not fit in the registers available for argument
5257 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5259 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5261 // Figure out which arguments are going to go in registers, and which in
5262 // memory. Also, if this is a vararg function, floating point operations
5263 // must be stored to our stack, and loaded into integer regs as well, if
5264 // any integer regs are available for argument passing.
5265 unsigned ArgOffset = LinkageSize;
5266 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5268 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5269 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5270 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5272 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5273 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5274 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5276 static const MCPhysReg VR[] = {
5277 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5278 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5280 const unsigned NumGPRs = array_lengthof(GPR_32);
5281 const unsigned NumFPRs = 13;
5282 const unsigned NumVRs = array_lengthof(VR);
5284 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5286 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5287 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5289 SmallVector<SDValue, 8> MemOpChains;
5290 for (unsigned i = 0; i != NumOps; ++i) {
5291 SDValue Arg = OutVals[i];
5292 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5294 // PtrOff will be used to store the current argument to the stack if a
5295 // register cannot be found for it.
5298 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5300 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5302 // On PPC64, promote integers to 64-bit values.
5303 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5304 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5305 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5306 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5309 // FIXME memcpy is used way more than necessary. Correctness first.
5310 // Note: "by value" is code for passing a structure by value, not
5312 if (Flags.isByVal()) {
5313 unsigned Size = Flags.getByValSize();
5314 // Very small objects are passed right-justified. Everything else is
5315 // passed left-justified.
5316 if (Size==1 || Size==2) {
5317 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5318 if (GPR_idx != NumGPRs) {
5319 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5320 MachinePointerInfo(), VT,
5321 false, false, false, 0);
5322 MemOpChains.push_back(Load.getValue(1));
5323 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5325 ArgOffset += PtrByteSize;
5327 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5328 PtrOff.getValueType());
5329 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5330 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5333 ArgOffset += PtrByteSize;
5337 // Copy entire object into memory. There are cases where gcc-generated
5338 // code assumes it is there, even if it could be put entirely into
5339 // registers. (This is not what the doc says.)
5340 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5344 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5345 // copy the pieces of the object that fit into registers from the
5346 // parameter save area.
5347 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5348 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5349 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5350 if (GPR_idx != NumGPRs) {
5351 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5352 MachinePointerInfo(),
5353 false, false, false, 0);
5354 MemOpChains.push_back(Load.getValue(1));
5355 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5356 ArgOffset += PtrByteSize;
5358 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5365 switch (Arg.getSimpleValueType().SimpleTy) {
5366 default: llvm_unreachable("Unexpected ValueType for argument!");
5370 if (GPR_idx != NumGPRs) {
5371 if (Arg.getValueType() == MVT::i1)
5372 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5374 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5376 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5377 isPPC64, isTailCall, false, MemOpChains,
5378 TailCallArguments, dl);
5380 ArgOffset += PtrByteSize;
5384 if (FPR_idx != NumFPRs) {
5385 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5388 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5389 MachinePointerInfo(), false, false, 0);
5390 MemOpChains.push_back(Store);
5392 // Float varargs are always shadowed in available integer registers
5393 if (GPR_idx != NumGPRs) {
5394 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5395 MachinePointerInfo(), false, false,
5397 MemOpChains.push_back(Load.getValue(1));
5398 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5400 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5401 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5402 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5403 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5404 MachinePointerInfo(),
5405 false, false, false, 0);
5406 MemOpChains.push_back(Load.getValue(1));
5407 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5410 // If we have any FPRs remaining, we may also have GPRs remaining.
5411 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5413 if (GPR_idx != NumGPRs)
5415 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5416 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
5420 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5421 isPPC64, isTailCall, false, MemOpChains,
5422 TailCallArguments, dl);
5426 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5433 // These go aligned on the stack, or in the corresponding R registers
5434 // when within range. The Darwin PPC ABI doc claims they also go in
5435 // V registers; in fact gcc does this only for arguments that are
5436 // prototyped, not for those that match the ... We do it for all
5437 // arguments, seems to work.
5438 while (ArgOffset % 16 !=0) {
5439 ArgOffset += PtrByteSize;
5440 if (GPR_idx != NumGPRs)
5443 // We could elide this store in the case where the object fits
5444 // entirely in R registers. Maybe later.
5445 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5446 DAG.getConstant(ArgOffset, dl, PtrVT));
5447 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5448 MachinePointerInfo(), false, false, 0);
5449 MemOpChains.push_back(Store);
5450 if (VR_idx != NumVRs) {
5451 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5452 MachinePointerInfo(),
5453 false, false, false, 0);
5454 MemOpChains.push_back(Load.getValue(1));
5455 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5458 for (unsigned i=0; i<16; i+=PtrByteSize) {
5459 if (GPR_idx == NumGPRs)
5461 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5462 DAG.getConstant(i, dl, PtrVT));
5463 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5464 false, false, false, 0);
5465 MemOpChains.push_back(Load.getValue(1));
5466 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5471 // Non-varargs Altivec params generally go in registers, but have
5472 // stack space allocated at the end.
5473 if (VR_idx != NumVRs) {
5474 // Doesn't have GPR space allocated.
5475 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5476 } else if (nAltivecParamsAtEnd==0) {
5477 // We are emitting Altivec params in order.
5478 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5479 isPPC64, isTailCall, true, MemOpChains,
5480 TailCallArguments, dl);
5486 // If all Altivec parameters fit in registers, as they usually do,
5487 // they get stack space following the non-Altivec parameters. We
5488 // don't track this here because nobody below needs it.
5489 // If there are more Altivec parameters than fit in registers emit
5491 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5493 // Offset is aligned; skip 1st 12 params which go in V registers.
5494 ArgOffset = ((ArgOffset+15)/16)*16;
5496 for (unsigned i = 0; i != NumOps; ++i) {
5497 SDValue Arg = OutVals[i];
5498 EVT ArgType = Outs[i].VT;
5499 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5500 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5503 // We are emitting Altivec params in order.
5504 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5505 isPPC64, isTailCall, true, MemOpChains,
5506 TailCallArguments, dl);
5513 if (!MemOpChains.empty())
5514 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5516 // On Darwin, R12 must contain the address of an indirect callee. This does
5517 // not mean the MTCTR instruction must use R12; it's easier to model this as
5518 // an extra parameter, so do that.
5520 !isFunctionGlobalAddress(Callee) &&
5521 !isa<ExternalSymbolSDNode>(Callee) &&
5522 !isBLACompatibleAddress(Callee, DAG))
5523 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5524 PPC::R12), Callee));
5526 // Build a sequence of copy-to-reg nodes chained together with token chain
5527 // and flag operands which copy the outgoing args into the appropriate regs.
5529 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5530 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5531 RegsToPass[i].second, InFlag);
5532 InFlag = Chain.getValue(1);
5536 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5537 FPOp, true, TailCallArguments);
5539 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5540 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5541 NumBytes, Ins, InVals, CS);
5545 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5546 MachineFunction &MF, bool isVarArg,
5547 const SmallVectorImpl<ISD::OutputArg> &Outs,
5548 LLVMContext &Context) const {
5549 SmallVector<CCValAssign, 16> RVLocs;
5550 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5551 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5555 PPCTargetLowering::LowerReturn(SDValue Chain,
5556 CallingConv::ID CallConv, bool isVarArg,
5557 const SmallVectorImpl<ISD::OutputArg> &Outs,
5558 const SmallVectorImpl<SDValue> &OutVals,
5559 SDLoc dl, SelectionDAG &DAG) const {
5561 SmallVector<CCValAssign, 16> RVLocs;
5562 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5564 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5567 SmallVector<SDValue, 4> RetOps(1, Chain);
5569 // Copy the result values into the output registers.
5570 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5571 CCValAssign &VA = RVLocs[i];
5572 assert(VA.isRegLoc() && "Can only return in registers!");
5574 SDValue Arg = OutVals[i];
5576 switch (VA.getLocInfo()) {
5577 default: llvm_unreachable("Unknown loc info!");
5578 case CCValAssign::Full: break;
5579 case CCValAssign::AExt:
5580 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5582 case CCValAssign::ZExt:
5583 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5585 case CCValAssign::SExt:
5586 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5590 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5591 Flag = Chain.getValue(1);
5592 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5595 RetOps[0] = Chain; // Update chain.
5597 // Add the flag if we have it.
5599 RetOps.push_back(Flag);
5601 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5604 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5605 const PPCSubtarget &Subtarget) const {
5606 // When we pop the dynamic allocation we need to restore the SP link.
5609 // Get the corect type for pointers.
5610 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5612 // Construct the stack pointer operand.
5613 bool isPPC64 = Subtarget.isPPC64();
5614 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5615 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5617 // Get the operands for the STACKRESTORE.
5618 SDValue Chain = Op.getOperand(0);
5619 SDValue SaveSP = Op.getOperand(1);
5621 // Load the old link SP.
5622 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5623 MachinePointerInfo(),
5624 false, false, false, 0);
5626 // Restore the stack pointer.
5627 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5629 // Store the old link SP.
5630 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5637 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5638 MachineFunction &MF = DAG.getMachineFunction();
5639 bool isPPC64 = Subtarget.isPPC64();
5640 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5642 // Get current frame pointer save index. The users of this index will be
5643 // primarily DYNALLOC instructions.
5644 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5645 int RASI = FI->getReturnAddrSaveIndex();
5647 // If the frame pointer save index hasn't been defined yet.
5649 // Find out what the fix offset of the frame pointer save area.
5650 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5651 // Allocate the frame index for frame pointer save area.
5652 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5654 FI->setReturnAddrSaveIndex(RASI);
5656 return DAG.getFrameIndex(RASI, PtrVT);
5660 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5661 MachineFunction &MF = DAG.getMachineFunction();
5662 bool isPPC64 = Subtarget.isPPC64();
5663 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5665 // Get current frame pointer save index. The users of this index will be
5666 // primarily DYNALLOC instructions.
5667 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5668 int FPSI = FI->getFramePointerSaveIndex();
5670 // If the frame pointer save index hasn't been defined yet.
5672 // Find out what the fix offset of the frame pointer save area.
5673 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5674 // Allocate the frame index for frame pointer save area.
5675 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5677 FI->setFramePointerSaveIndex(FPSI);
5679 return DAG.getFrameIndex(FPSI, PtrVT);
5682 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5684 const PPCSubtarget &Subtarget) const {
5686 SDValue Chain = Op.getOperand(0);
5687 SDValue Size = Op.getOperand(1);
5690 // Get the corect type for pointers.
5691 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5693 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5694 DAG.getConstant(0, dl, PtrVT), Size);
5695 // Construct a node for the frame pointer save index.
5696 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5697 // Build a DYNALLOC node.
5698 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5699 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5700 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5703 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5704 SelectionDAG &DAG) const {
5706 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5707 DAG.getVTList(MVT::i32, MVT::Other),
5708 Op.getOperand(0), Op.getOperand(1));
5711 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5712 SelectionDAG &DAG) const {
5714 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5715 Op.getOperand(0), Op.getOperand(1));
5718 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5719 if (Op.getValueType().isVector())
5720 return LowerVectorLoad(Op, DAG);
5722 assert(Op.getValueType() == MVT::i1 &&
5723 "Custom lowering only for i1 loads");
5725 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5728 LoadSDNode *LD = cast<LoadSDNode>(Op);
5730 SDValue Chain = LD->getChain();
5731 SDValue BasePtr = LD->getBasePtr();
5732 MachineMemOperand *MMO = LD->getMemOperand();
5734 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5735 BasePtr, MVT::i8, MMO);
5736 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5738 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5739 return DAG.getMergeValues(Ops, dl);
5742 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5743 if (Op.getOperand(1).getValueType().isVector())
5744 return LowerVectorStore(Op, DAG);
5746 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5747 "Custom lowering only for i1 stores");
5749 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5752 StoreSDNode *ST = cast<StoreSDNode>(Op);
5754 SDValue Chain = ST->getChain();
5755 SDValue BasePtr = ST->getBasePtr();
5756 SDValue Value = ST->getValue();
5757 MachineMemOperand *MMO = ST->getMemOperand();
5759 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5760 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5763 // FIXME: Remove this once the ANDI glue bug is fixed:
5764 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5765 assert(Op.getValueType() == MVT::i1 &&
5766 "Custom lowering only for i1 results");
5769 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5773 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5775 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5776 // Not FP? Not a fsel.
5777 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5778 !Op.getOperand(2).getValueType().isFloatingPoint())
5781 // We might be able to do better than this under some circumstances, but in
5782 // general, fsel-based lowering of select is a finite-math-only optimization.
5783 // For more information, see section F.3 of the 2.06 ISA specification.
5784 if (!DAG.getTarget().Options.NoInfsFPMath ||
5785 !DAG.getTarget().Options.NoNaNsFPMath)
5788 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5790 EVT ResVT = Op.getValueType();
5791 EVT CmpVT = Op.getOperand(0).getValueType();
5792 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5793 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5796 // If the RHS of the comparison is a 0.0, we don't need to do the
5797 // subtraction at all.
5799 if (isFloatingPointZero(RHS))
5801 default: break; // SETUO etc aren't handled by fsel.
5805 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5806 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5807 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5808 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5809 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5810 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5811 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5814 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5817 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5818 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5819 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5822 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5825 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5826 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5827 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5828 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5833 default: break; // SETUO etc aren't handled by fsel.
5837 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5838 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5839 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5840 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5841 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5842 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5843 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5844 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5847 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5848 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5849 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5850 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5853 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5854 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5855 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5856 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5859 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5860 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5861 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5862 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5865 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5866 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5867 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5868 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5873 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5876 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5877 SDValue Src = Op.getOperand(0);
5878 if (Src.getValueType() == MVT::f32)
5879 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5882 switch (Op.getSimpleValueType().SimpleTy) {
5883 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5886 Op.getOpcode() == ISD::FP_TO_SINT
5888 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5892 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5893 "i64 FP_TO_UINT is supported only with FPCVT");
5894 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5900 // Convert the FP value to an int value through memory.
5901 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5902 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5903 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5904 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5905 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5907 // Emit a store to the stack slot.
5910 MachineFunction &MF = DAG.getMachineFunction();
5911 MachineMemOperand *MMO =
5912 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5913 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5914 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5915 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5917 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5918 MPI, false, false, 0);
5920 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5922 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5923 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5924 DAG.getConstant(4, dl, FIPtr.getValueType()));
5925 MPI = MPI.getWithOffset(4);
5933 /// \brief Custom lowers floating point to integer conversions to use
5934 /// the direct move instructions available in ISA 2.07 to avoid the
5935 /// need for load/store combinations.
5936 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
5939 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5940 SDValue Src = Op.getOperand(0);
5942 if (Src.getValueType() == MVT::f32)
5943 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5946 switch (Op.getSimpleValueType().SimpleTy) {
5947 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5950 Op.getOpcode() == ISD::FP_TO_SINT
5952 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5954 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
5957 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5958 "i64 FP_TO_UINT is supported only with FPCVT");
5959 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5962 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
5968 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5970 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
5971 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
5974 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5976 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5977 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5981 // We're trying to insert a regular store, S, and then a load, L. If the
5982 // incoming value, O, is a load, we might just be able to have our load use the
5983 // address used by O. However, we don't know if anything else will store to
5984 // that address before we can load from it. To prevent this situation, we need
5985 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5986 // the same chain operand as O, we create a token factor from the chain results
5987 // of O and L, and we replace all uses of O's chain result with that token
5988 // factor (see spliceIntoChain below for this last part).
5989 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5992 ISD::LoadExtType ET) const {
5994 if (ET == ISD::NON_EXTLOAD &&
5995 (Op.getOpcode() == ISD::FP_TO_UINT ||
5996 Op.getOpcode() == ISD::FP_TO_SINT) &&
5997 isOperationLegalOrCustom(Op.getOpcode(),
5998 Op.getOperand(0).getValueType())) {
6000 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6004 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6005 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6006 LD->isNonTemporal())
6008 if (LD->getMemoryVT() != MemVT)
6011 RLI.Ptr = LD->getBasePtr();
6012 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
6013 assert(LD->getAddressingMode() == ISD::PRE_INC &&
6014 "Non-pre-inc AM on PPC?");
6015 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6019 RLI.Chain = LD->getChain();
6020 RLI.MPI = LD->getPointerInfo();
6021 RLI.IsInvariant = LD->isInvariant();
6022 RLI.Alignment = LD->getAlignment();
6023 RLI.AAInfo = LD->getAAInfo();
6024 RLI.Ranges = LD->getRanges();
6026 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6030 // Given the head of the old chain, ResChain, insert a token factor containing
6031 // it and NewResChain, and make users of ResChain now be users of that token
6033 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6034 SDValue NewResChain,
6035 SelectionDAG &DAG) const {
6039 SDLoc dl(NewResChain);
6041 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6042 NewResChain, DAG.getUNDEF(MVT::Other));
6043 assert(TF.getNode() != NewResChain.getNode() &&
6044 "A new TF really is required here");
6046 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6047 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6050 /// \brief Custom lowers integer to floating point conversions to use
6051 /// the direct move instructions available in ISA 2.07 to avoid the
6052 /// need for load/store combinations.
6053 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6056 assert((Op.getValueType() == MVT::f32 ||
6057 Op.getValueType() == MVT::f64) &&
6058 "Invalid floating point type as target of conversion");
6059 assert(Subtarget.hasFPCVT() &&
6060 "Int to FP conversions with direct moves require FPCVT");
6062 SDValue Src = Op.getOperand(0);
6063 bool SinglePrec = Op.getValueType() == MVT::f32;
6064 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6065 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6066 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6067 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6070 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6072 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6075 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6076 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6082 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6083 SelectionDAG &DAG) const {
6086 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6087 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6090 SDValue Value = Op.getOperand(0);
6091 // The values are now known to be -1 (false) or 1 (true). To convert this
6092 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6093 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6094 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6096 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
6097 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6098 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6100 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6102 if (Op.getValueType() != MVT::v4f64)
6103 Value = DAG.getNode(ISD::FP_ROUND, dl,
6104 Op.getValueType(), Value,
6105 DAG.getIntPtrConstant(1, dl));
6109 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6110 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6113 if (Op.getOperand(0).getValueType() == MVT::i1)
6114 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6115 DAG.getConstantFP(1.0, dl, Op.getValueType()),
6116 DAG.getConstantFP(0.0, dl, Op.getValueType()));
6118 // If we have direct moves, we can do all the conversion, skip the store/load
6119 // however, without FPCVT we can't do most conversions.
6120 if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6121 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6123 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6124 "UINT_TO_FP is supported only with FPCVT");
6126 // If we have FCFIDS, then use it when converting to single-precision.
6127 // Otherwise, convert to double-precision and then round.
6128 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6129 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6131 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6133 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6137 if (Op.getOperand(0).getValueType() == MVT::i64) {
6138 SDValue SINT = Op.getOperand(0);
6139 // When converting to single-precision, we actually need to convert
6140 // to double-precision first and then round to single-precision.
6141 // To avoid double-rounding effects during that operation, we have
6142 // to prepare the input operand. Bits that might be truncated when
6143 // converting to double-precision are replaced by a bit that won't
6144 // be lost at this stage, but is below the single-precision rounding
6147 // However, if -enable-unsafe-fp-math is in effect, accept double
6148 // rounding to avoid the extra overhead.
6149 if (Op.getValueType() == MVT::f32 &&
6150 !Subtarget.hasFPCVT() &&
6151 !DAG.getTarget().Options.UnsafeFPMath) {
6153 // Twiddle input to make sure the low 11 bits are zero. (If this
6154 // is the case, we are guaranteed the value will fit into the 53 bit
6155 // mantissa of an IEEE double-precision value without rounding.)
6156 // If any of those low 11 bits were not zero originally, make sure
6157 // bit 12 (value 2048) is set instead, so that the final rounding
6158 // to single-precision gets the correct result.
6159 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6160 SINT, DAG.getConstant(2047, dl, MVT::i64));
6161 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6162 Round, DAG.getConstant(2047, dl, MVT::i64));
6163 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6164 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6165 Round, DAG.getConstant(-2048, dl, MVT::i64));
6167 // However, we cannot use that value unconditionally: if the magnitude
6168 // of the input value is small, the bit-twiddling we did above might
6169 // end up visibly changing the output. Fortunately, in that case, we
6170 // don't need to twiddle bits since the original input will convert
6171 // exactly to double-precision floating-point already. Therefore,
6172 // construct a conditional to use the original value if the top 11
6173 // bits are all sign-bit copies, and use the rounded value computed
6175 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6176 SINT, DAG.getConstant(53, dl, MVT::i32));
6177 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6178 Cond, DAG.getConstant(1, dl, MVT::i64));
6179 Cond = DAG.getSetCC(dl, MVT::i32,
6180 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6182 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6188 MachineFunction &MF = DAG.getMachineFunction();
6189 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6190 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6191 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6193 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6194 } else if (Subtarget.hasLFIWAX() &&
6195 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6196 MachineMemOperand *MMO =
6197 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6198 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6199 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6200 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6201 DAG.getVTList(MVT::f64, MVT::Other),
6202 Ops, MVT::i32, MMO);
6203 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6204 } else if (Subtarget.hasFPCVT() &&
6205 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6206 MachineMemOperand *MMO =
6207 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6208 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6209 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6210 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6211 DAG.getVTList(MVT::f64, MVT::Other),
6212 Ops, MVT::i32, MMO);
6213 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6214 } else if (((Subtarget.hasLFIWAX() &&
6215 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6216 (Subtarget.hasFPCVT() &&
6217 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6218 SINT.getOperand(0).getValueType() == MVT::i32) {
6219 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6220 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6222 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6223 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6226 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6227 MachinePointerInfo::getFixedStack(FrameIdx),
6230 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6231 "Expected an i32 store");
6235 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6238 MachineMemOperand *MMO =
6239 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6240 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6241 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6242 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6243 PPCISD::LFIWZX : PPCISD::LFIWAX,
6244 dl, DAG.getVTList(MVT::f64, MVT::Other),
6245 Ops, MVT::i32, MMO);
6247 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6249 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6251 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6252 FP = DAG.getNode(ISD::FP_ROUND, dl,
6253 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6257 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6258 "Unhandled INT_TO_FP type in custom expander!");
6259 // Since we only generate this in 64-bit mode, we can take advantage of
6260 // 64-bit registers. In particular, sign extend the input value into the
6261 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6262 // then lfd it and fcfid it.
6263 MachineFunction &MF = DAG.getMachineFunction();
6264 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6265 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6268 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6271 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6273 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6274 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6276 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6277 MachinePointerInfo::getFixedStack(FrameIdx),
6280 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6281 "Expected an i32 store");
6285 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6289 MachineMemOperand *MMO =
6290 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6291 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6292 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6293 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6294 PPCISD::LFIWZX : PPCISD::LFIWAX,
6295 dl, DAG.getVTList(MVT::f64, MVT::Other),
6296 Ops, MVT::i32, MMO);
6298 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6300 assert(Subtarget.isPPC64() &&
6301 "i32->FP without LFIWAX supported only on PPC64");
6303 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6304 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6306 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6309 // STD the extended value into the stack slot.
6310 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6311 MachinePointerInfo::getFixedStack(FrameIdx),
6314 // Load the value as a double.
6315 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6316 MachinePointerInfo::getFixedStack(FrameIdx),
6317 false, false, false, 0);
6320 // FCFID it and return it.
6321 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6322 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6323 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6324 DAG.getIntPtrConstant(0, dl));
6328 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6329 SelectionDAG &DAG) const {
6332 The rounding mode is in bits 30:31 of FPSR, and has the following
6339 FLT_ROUNDS, on the other hand, expects the following:
6346 To perform the conversion, we do:
6347 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6350 MachineFunction &MF = DAG.getMachineFunction();
6351 EVT VT = Op.getValueType();
6352 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6354 // Save FP Control Word to register
6356 MVT::f64, // return register
6357 MVT::Glue // unused in this context
6359 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6361 // Save FP register to stack slot
6362 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6363 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6364 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6365 StackSlot, MachinePointerInfo(), false, false,0);
6367 // Load FP Control Word from low 32 bits of stack slot.
6368 SDValue Four = DAG.getConstant(4, dl, PtrVT);
6369 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6370 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6371 false, false, false, 0);
6373 // Transform as necessary
6375 DAG.getNode(ISD::AND, dl, MVT::i32,
6376 CWD, DAG.getConstant(3, dl, MVT::i32));
6378 DAG.getNode(ISD::SRL, dl, MVT::i32,
6379 DAG.getNode(ISD::AND, dl, MVT::i32,
6380 DAG.getNode(ISD::XOR, dl, MVT::i32,
6381 CWD, DAG.getConstant(3, dl, MVT::i32)),
6382 DAG.getConstant(3, dl, MVT::i32)),
6383 DAG.getConstant(1, dl, MVT::i32));
6386 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6388 return DAG.getNode((VT.getSizeInBits() < 16 ?
6389 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6392 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6393 EVT VT = Op.getValueType();
6394 unsigned BitWidth = VT.getSizeInBits();
6396 assert(Op.getNumOperands() == 3 &&
6397 VT == Op.getOperand(1).getValueType() &&
6400 // Expand into a bunch of logical ops. Note that these ops
6401 // depend on the PPC behavior for oversized shift amounts.
6402 SDValue Lo = Op.getOperand(0);
6403 SDValue Hi = Op.getOperand(1);
6404 SDValue Amt = Op.getOperand(2);
6405 EVT AmtVT = Amt.getValueType();
6407 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6408 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6409 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6410 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6411 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6412 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6413 DAG.getConstant(-BitWidth, dl, AmtVT));
6414 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6415 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6416 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6417 SDValue OutOps[] = { OutLo, OutHi };
6418 return DAG.getMergeValues(OutOps, dl);
6421 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6422 EVT VT = Op.getValueType();
6424 unsigned BitWidth = VT.getSizeInBits();
6425 assert(Op.getNumOperands() == 3 &&
6426 VT == Op.getOperand(1).getValueType() &&
6429 // Expand into a bunch of logical ops. Note that these ops
6430 // depend on the PPC behavior for oversized shift amounts.
6431 SDValue Lo = Op.getOperand(0);
6432 SDValue Hi = Op.getOperand(1);
6433 SDValue Amt = Op.getOperand(2);
6434 EVT AmtVT = Amt.getValueType();
6436 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6437 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6438 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6439 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6440 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6441 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6442 DAG.getConstant(-BitWidth, dl, AmtVT));
6443 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6444 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6445 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6446 SDValue OutOps[] = { OutLo, OutHi };
6447 return DAG.getMergeValues(OutOps, dl);
6450 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6452 EVT VT = Op.getValueType();
6453 unsigned BitWidth = VT.getSizeInBits();
6454 assert(Op.getNumOperands() == 3 &&
6455 VT == Op.getOperand(1).getValueType() &&
6458 // Expand into a bunch of logical ops, followed by a select_cc.
6459 SDValue Lo = Op.getOperand(0);
6460 SDValue Hi = Op.getOperand(1);
6461 SDValue Amt = Op.getOperand(2);
6462 EVT AmtVT = Amt.getValueType();
6464 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6465 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6466 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6467 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6468 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6469 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6470 DAG.getConstant(-BitWidth, dl, AmtVT));
6471 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6472 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6473 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6474 Tmp4, Tmp6, ISD::SETLE);
6475 SDValue OutOps[] = { OutLo, OutHi };
6476 return DAG.getMergeValues(OutOps, dl);
6479 //===----------------------------------------------------------------------===//
6480 // Vector related lowering.
6483 /// BuildSplatI - Build a canonical splati of Val with an element size of
6484 /// SplatSize. Cast the result to VT.
6485 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6486 SelectionDAG &DAG, SDLoc dl) {
6487 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6489 static const MVT VTys[] = { // canonical VT to use for each size.
6490 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6493 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6495 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6499 EVT CanonicalVT = VTys[SplatSize-1];
6501 // Build a canonical splat for this value.
6502 SDValue Elt = DAG.getConstant(Val, dl, MVT::i32);
6503 SmallVector<SDValue, 8> Ops;
6504 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6505 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6506 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6509 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6510 /// specified intrinsic ID.
6511 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6512 SelectionDAG &DAG, SDLoc dl,
6513 EVT DestVT = MVT::Other) {
6514 if (DestVT == MVT::Other) DestVT = Op.getValueType();
6515 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6516 DAG.getConstant(IID, dl, MVT::i32), Op);
6519 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6520 /// specified intrinsic ID.
6521 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6522 SelectionDAG &DAG, SDLoc dl,
6523 EVT DestVT = MVT::Other) {
6524 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6525 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6526 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6529 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6530 /// specified intrinsic ID.
6531 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6532 SDValue Op2, SelectionDAG &DAG,
6533 SDLoc dl, EVT DestVT = MVT::Other) {
6534 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6535 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6536 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6540 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6541 /// amount. The result has the specified value type.
6542 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6543 EVT VT, SelectionDAG &DAG, SDLoc dl) {
6544 // Force LHS/RHS to be the right type.
6545 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6546 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6549 for (unsigned i = 0; i != 16; ++i)
6551 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6552 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6555 // If this is a case we can't handle, return null and let the default
6556 // expansion code take care of it. If we CAN select this case, and if it
6557 // selects to a single instruction, return Op. Otherwise, if we can codegen
6558 // this case more efficiently than a constant pool load, lower it to the
6559 // sequence of ops that should be used.
6560 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6561 SelectionDAG &DAG) const {
6563 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6564 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6566 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6567 // We first build an i32 vector, load it into a QPX register,
6568 // then convert it to a floating-point vector and compare it
6569 // to a zero vector to get the boolean result.
6570 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6571 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6572 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6573 EVT PtrVT = getPointerTy();
6574 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6576 assert(BVN->getNumOperands() == 4 &&
6577 "BUILD_VECTOR for v4i1 does not have 4 operands");
6579 bool IsConst = true;
6580 for (unsigned i = 0; i < 4; ++i) {
6581 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6582 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6590 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6592 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6594 SmallVector<Constant*, 4> CV(4, NegOne);
6595 for (unsigned i = 0; i < 4; ++i) {
6596 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6597 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6598 else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6599 getConstantIntValue()->isZero())
6605 Constant *CP = ConstantVector::get(CV);
6606 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6607 16 /* alignment */);
6609 SmallVector<SDValue, 2> Ops;
6610 Ops.push_back(DAG.getEntryNode());
6611 Ops.push_back(CPIdx);
6613 SmallVector<EVT, 2> ValueVTs;
6614 ValueVTs.push_back(MVT::v4i1);
6615 ValueVTs.push_back(MVT::Other); // chain
6616 SDVTList VTs = DAG.getVTList(ValueVTs);
6618 return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6619 dl, VTs, Ops, MVT::v4f32,
6620 MachinePointerInfo::getConstantPool());
6623 SmallVector<SDValue, 4> Stores;
6624 for (unsigned i = 0; i < 4; ++i) {
6625 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6627 unsigned Offset = 4*i;
6628 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
6629 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6631 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6632 if (StoreSize > 4) {
6633 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6634 BVN->getOperand(i), Idx,
6635 PtrInfo.getWithOffset(Offset),
6636 MVT::i32, false, false, 0));
6638 SDValue StoreValue = BVN->getOperand(i);
6640 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6642 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6644 PtrInfo.getWithOffset(Offset),
6650 if (!Stores.empty())
6651 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6653 StoreChain = DAG.getEntryNode();
6655 // Now load from v4i32 into the QPX register; this will extend it to
6656 // v4i64 but not yet convert it to a floating point. Nevertheless, this
6657 // is typed as v4f64 because the QPX register integer states are not
6658 // explicitly represented.
6660 SmallVector<SDValue, 2> Ops;
6661 Ops.push_back(StoreChain);
6662 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
6663 Ops.push_back(FIdx);
6665 SmallVector<EVT, 2> ValueVTs;
6666 ValueVTs.push_back(MVT::v4f64);
6667 ValueVTs.push_back(MVT::Other); // chain
6668 SDVTList VTs = DAG.getVTList(ValueVTs);
6670 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6671 dl, VTs, Ops, MVT::v4i32, PtrInfo);
6672 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6673 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
6676 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64);
6677 FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6678 FPZeros, FPZeros, FPZeros, FPZeros);
6680 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6683 // All other QPX vectors are handled by generic code.
6684 if (Subtarget.hasQPX())
6687 // Check if this is a splat of a constant value.
6688 APInt APSplatBits, APSplatUndef;
6689 unsigned SplatBitSize;
6691 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6692 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6696 unsigned SplatBits = APSplatBits.getZExtValue();
6697 unsigned SplatUndef = APSplatUndef.getZExtValue();
6698 unsigned SplatSize = SplatBitSize / 8;
6700 // First, handle single instruction cases.
6703 if (SplatBits == 0) {
6704 // Canonicalize all zero vectors to be v4i32.
6705 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6706 SDValue Z = DAG.getConstant(0, dl, MVT::i32);
6707 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6708 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6713 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6714 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6716 if (SextVal >= -16 && SextVal <= 15)
6717 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6720 // Two instruction sequences.
6722 // If this value is in the range [-32,30] and is even, use:
6723 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6724 // If this value is in the range [17,31] and is odd, use:
6725 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6726 // If this value is in the range [-31,-17] and is odd, use:
6727 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6728 // Note the last two are three-instruction sequences.
6729 if (SextVal >= -32 && SextVal <= 31) {
6730 // To avoid having these optimizations undone by constant folding,
6731 // we convert to a pseudo that will be expanded later into one of
6733 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
6734 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6735 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6736 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
6737 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6738 if (VT == Op.getValueType())
6741 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6744 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6745 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6747 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6748 // Make -1 and vspltisw -1:
6749 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6751 // Make the VSLW intrinsic, computing 0x8000_0000.
6752 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6755 // xor by OnesV to invert it.
6756 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6757 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6760 // Check to see if this is a wide variety of vsplti*, binop self cases.
6761 static const signed char SplatCsts[] = {
6762 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6763 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6766 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6767 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6768 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6769 int i = SplatCsts[idx];
6771 // Figure out what shift amount will be used by altivec if shifted by i in
6773 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6775 // vsplti + shl self.
6776 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6777 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6778 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6779 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6780 Intrinsic::ppc_altivec_vslw
6782 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6783 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6786 // vsplti + srl self.
6787 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6788 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6789 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6790 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6791 Intrinsic::ppc_altivec_vsrw
6793 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6794 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6797 // vsplti + sra self.
6798 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6799 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6800 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6801 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6802 Intrinsic::ppc_altivec_vsraw
6804 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6805 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6808 // vsplti + rol self.
6809 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6810 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6811 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6812 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6813 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6814 Intrinsic::ppc_altivec_vrlw
6816 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6817 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6820 // t = vsplti c, result = vsldoi t, t, 1
6821 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6822 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6823 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6825 // t = vsplti c, result = vsldoi t, t, 2
6826 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6827 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6828 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6830 // t = vsplti c, result = vsldoi t, t, 3
6831 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6832 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6833 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6840 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6841 /// the specified operations to build the shuffle.
6842 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6843 SDValue RHS, SelectionDAG &DAG,
6845 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6846 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6847 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6850 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6862 if (OpNum == OP_COPY) {
6863 if (LHSID == (1*9+2)*9+3) return LHS;
6864 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6868 SDValue OpLHS, OpRHS;
6869 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6870 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6874 default: llvm_unreachable("Unknown i32 permute!");
6876 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6877 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6878 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6879 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6882 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6883 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6884 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6885 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6888 for (unsigned i = 0; i != 16; ++i)
6889 ShufIdxs[i] = (i&3)+0;
6892 for (unsigned i = 0; i != 16; ++i)
6893 ShufIdxs[i] = (i&3)+4;
6896 for (unsigned i = 0; i != 16; ++i)
6897 ShufIdxs[i] = (i&3)+8;
6900 for (unsigned i = 0; i != 16; ++i)
6901 ShufIdxs[i] = (i&3)+12;
6904 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6906 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6908 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6910 EVT VT = OpLHS.getValueType();
6911 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6912 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6913 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6914 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6917 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6918 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6919 /// return the code it can be lowered into. Worst case, it can always be
6920 /// lowered into a vperm.
6921 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6922 SelectionDAG &DAG) const {
6924 SDValue V1 = Op.getOperand(0);
6925 SDValue V2 = Op.getOperand(1);
6926 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6927 EVT VT = Op.getValueType();
6928 bool isLittleEndian = Subtarget.isLittleEndian();
6930 if (Subtarget.hasQPX()) {
6931 if (VT.getVectorNumElements() != 4)
6934 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6936 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6937 if (AlignIdx != -1) {
6938 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6939 DAG.getConstant(AlignIdx, dl, MVT::i32));
6940 } else if (SVOp->isSplat()) {
6941 int SplatIdx = SVOp->getSplatIndex();
6942 if (SplatIdx >= 4) {
6947 // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6950 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6951 DAG.getConstant(SplatIdx, dl, MVT::i32));
6954 // Lower this into a qvgpci/qvfperm pair.
6956 // Compute the qvgpci literal
6958 for (unsigned i = 0; i < 4; ++i) {
6959 int m = SVOp->getMaskElt(i);
6960 unsigned mm = m >= 0 ? (unsigned) m : i;
6961 idx |= mm << (3-i)*3;
6964 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6965 DAG.getConstant(idx, dl, MVT::i32));
6966 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6969 // Cases that are handled by instructions that take permute immediates
6970 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6971 // selected by the instruction selector.
6972 if (V2.getOpcode() == ISD::UNDEF) {
6973 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6974 PPC::isSplatShuffleMask(SVOp, 2) ||
6975 PPC::isSplatShuffleMask(SVOp, 4) ||
6976 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6977 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6978 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6979 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6980 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6981 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6982 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6983 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6984 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6989 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6990 // and produce a fixed permutation. If any of these match, do not lower to
6992 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6993 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6994 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6995 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6996 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6997 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6998 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6999 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7000 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7001 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
7004 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
7005 // perfect shuffle table to emit an optimal matching sequence.
7006 ArrayRef<int> PermMask = SVOp->getMask();
7008 unsigned PFIndexes[4];
7009 bool isFourElementShuffle = true;
7010 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7011 unsigned EltNo = 8; // Start out undef.
7012 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
7013 if (PermMask[i*4+j] < 0)
7014 continue; // Undef, ignore it.
7016 unsigned ByteSource = PermMask[i*4+j];
7017 if ((ByteSource & 3) != j) {
7018 isFourElementShuffle = false;
7023 EltNo = ByteSource/4;
7024 } else if (EltNo != ByteSource/4) {
7025 isFourElementShuffle = false;
7029 PFIndexes[i] = EltNo;
7032 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7033 // perfect shuffle vector to determine if it is cost effective to do this as
7034 // discrete instructions, or whether we should use a vperm.
7035 // For now, we skip this for little endian until such time as we have a
7036 // little-endian perfect shuffle table.
7037 if (isFourElementShuffle && !isLittleEndian) {
7038 // Compute the index in the perfect shuffle table.
7039 unsigned PFTableIndex =
7040 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7042 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7043 unsigned Cost = (PFEntry >> 30);
7045 // Determining when to avoid vperm is tricky. Many things affect the cost
7046 // of vperm, particularly how many times the perm mask needs to be computed.
7047 // For example, if the perm mask can be hoisted out of a loop or is already
7048 // used (perhaps because there are multiple permutes with the same shuffle
7049 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
7050 // the loop requires an extra register.
7052 // As a compromise, we only emit discrete instructions if the shuffle can be
7053 // generated in 3 or fewer operations. When we have loop information
7054 // available, if this block is within a loop, we should avoid using vperm
7055 // for 3-operation perms and use a constant pool load instead.
7057 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7060 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7061 // vector that will get spilled to the constant pool.
7062 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7064 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7065 // that it is in input element units, not in bytes. Convert now.
7067 // For little endian, the order of the input vectors is reversed, and
7068 // the permutation mask is complemented with respect to 31. This is
7069 // necessary to produce proper semantics with the big-endian-biased vperm
7071 EVT EltVT = V1.getValueType().getVectorElementType();
7072 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7074 SmallVector<SDValue, 16> ResultMask;
7075 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7076 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7078 for (unsigned j = 0; j != BytesPerElement; ++j)
7080 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7083 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7087 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7090 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7093 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7097 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7098 /// altivec comparison. If it is, return true and fill in Opc/isDot with
7099 /// information about the intrinsic.
7100 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7101 bool &isDot, const PPCSubtarget &Subtarget) {
7102 unsigned IntrinsicID =
7103 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7106 switch (IntrinsicID) {
7107 default: return false;
7108 // Comparison predicates.
7109 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
7110 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7111 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
7112 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
7113 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7114 case Intrinsic::ppc_altivec_vcmpequd_p:
7115 if (Subtarget.hasP8Altivec()) {
7123 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7124 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7125 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7126 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7127 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7128 case Intrinsic::ppc_altivec_vcmpgtsd_p:
7129 if (Subtarget.hasP8Altivec()) {
7137 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7138 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7139 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7140 case Intrinsic::ppc_altivec_vcmpgtud_p:
7141 if (Subtarget.hasP8Altivec()) {
7150 // Normal Comparisons.
7151 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
7152 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
7153 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
7154 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
7155 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
7156 case Intrinsic::ppc_altivec_vcmpequd:
7157 if (Subtarget.hasP8Altivec()) {
7165 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
7166 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
7167 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
7168 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
7169 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
7170 case Intrinsic::ppc_altivec_vcmpgtsd:
7171 if (Subtarget.hasP8Altivec()) {
7179 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
7180 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
7181 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
7182 case Intrinsic::ppc_altivec_vcmpgtud:
7183 if (Subtarget.hasP8Altivec()) {
7195 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7196 /// lower, do it, otherwise return null.
7197 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7198 SelectionDAG &DAG) const {
7199 // If this is a lowered altivec predicate compare, CompareOpc is set to the
7200 // opcode number of the comparison.
7204 if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7205 return SDValue(); // Don't custom lower most intrinsics.
7207 // If this is a non-dot comparison, make the VCMP node and we are done.
7209 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7210 Op.getOperand(1), Op.getOperand(2),
7211 DAG.getConstant(CompareOpc, dl, MVT::i32));
7212 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7215 // Create the PPCISD altivec 'dot' comparison node.
7217 Op.getOperand(2), // LHS
7218 Op.getOperand(3), // RHS
7219 DAG.getConstant(CompareOpc, dl, MVT::i32)
7221 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7222 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7224 // Now that we have the comparison, emit a copy from the CR to a GPR.
7225 // This is flagged to the above dot comparison.
7226 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7227 DAG.getRegister(PPC::CR6, MVT::i32),
7228 CompNode.getValue(1));
7230 // Unpack the result based on how the target uses it.
7231 unsigned BitNo; // Bit # of CR6.
7232 bool InvertBit; // Invert result?
7233 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7234 default: // Can't happen, don't crash on invalid number though.
7235 case 0: // Return the value of the EQ bit of CR6.
7236 BitNo = 0; InvertBit = false;
7238 case 1: // Return the inverted value of the EQ bit of CR6.
7239 BitNo = 0; InvertBit = true;
7241 case 2: // Return the value of the LT bit of CR6.
7242 BitNo = 2; InvertBit = false;
7244 case 3: // Return the inverted value of the LT bit of CR6.
7245 BitNo = 2; InvertBit = true;
7249 // Shift the bit into the low position.
7250 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7251 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7253 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7254 DAG.getConstant(1, dl, MVT::i32));
7256 // If we are supposed to, toggle the bit.
7258 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7259 DAG.getConstant(1, dl, MVT::i32));
7263 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7264 SelectionDAG &DAG) const {
7266 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7267 // instructions), but for smaller types, we need to first extend up to v2i32
7268 // before doing going farther.
7269 if (Op.getValueType() == MVT::v2i64) {
7270 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7271 if (ExtVT != MVT::v2i32) {
7272 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7273 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7274 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7275 ExtVT.getVectorElementType(), 4)));
7276 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7277 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7278 DAG.getValueType(MVT::v2i32));
7287 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7288 SelectionDAG &DAG) const {
7290 // Create a stack slot that is 16-byte aligned.
7291 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7292 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7293 EVT PtrVT = getPointerTy();
7294 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7296 // Store the input value into Value#0 of the stack slot.
7297 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7298 Op.getOperand(0), FIdx, MachinePointerInfo(),
7301 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7302 false, false, false, 0);
7305 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7306 SelectionDAG &DAG) const {
7308 SDNode *N = Op.getNode();
7310 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7311 "Unknown extract_vector_elt type");
7313 SDValue Value = N->getOperand(0);
7315 // The first part of this is like the store lowering except that we don't
7316 // need to track the chain.
7318 // The values are now known to be -1 (false) or 1 (true). To convert this
7319 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7320 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7321 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7323 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7324 // understand how to form the extending load.
7325 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7326 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7327 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7329 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7331 // Now convert to an integer and store.
7332 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7333 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7336 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7337 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7338 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7339 EVT PtrVT = getPointerTy();
7340 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7342 SDValue StoreChain = DAG.getEntryNode();
7343 SmallVector<SDValue, 2> Ops;
7344 Ops.push_back(StoreChain);
7345 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7346 Ops.push_back(Value);
7347 Ops.push_back(FIdx);
7349 SmallVector<EVT, 2> ValueVTs;
7350 ValueVTs.push_back(MVT::Other); // chain
7351 SDVTList VTs = DAG.getVTList(ValueVTs);
7353 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7354 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7356 // Extract the value requested.
7357 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7358 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7359 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7361 SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7362 PtrInfo.getWithOffset(Offset),
7363 false, false, false, 0);
7365 if (!Subtarget.useCRBits())
7368 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7371 /// Lowering for QPX v4i1 loads
7372 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7373 SelectionDAG &DAG) const {
7375 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7376 SDValue LoadChain = LN->getChain();
7377 SDValue BasePtr = LN->getBasePtr();
7379 if (Op.getValueType() == MVT::v4f64 ||
7380 Op.getValueType() == MVT::v4f32) {
7381 EVT MemVT = LN->getMemoryVT();
7382 unsigned Alignment = LN->getAlignment();
7384 // If this load is properly aligned, then it is legal.
7385 if (Alignment >= MemVT.getStoreSize())
7388 EVT ScalarVT = Op.getValueType().getScalarType(),
7389 ScalarMemVT = MemVT.getScalarType();
7390 unsigned Stride = ScalarMemVT.getStoreSize();
7392 SmallVector<SDValue, 8> Vals, LoadChains;
7393 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7395 if (ScalarVT != ScalarMemVT)
7397 DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7399 LN->getPointerInfo().getWithOffset(Idx*Stride),
7400 ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7401 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7405 DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7406 LN->getPointerInfo().getWithOffset(Idx*Stride),
7407 LN->isVolatile(), LN->isNonTemporal(),
7408 LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7411 if (Idx == 0 && LN->isIndexed()) {
7412 assert(LN->getAddressingMode() == ISD::PRE_INC &&
7413 "Unknown addressing mode on vector load");
7414 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7415 LN->getAddressingMode());
7418 Vals.push_back(Load);
7419 LoadChains.push_back(Load.getValue(1));
7421 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7422 DAG.getConstant(Stride, dl,
7423 BasePtr.getValueType()));
7426 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7427 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7428 Op.getValueType(), Vals);
7430 if (LN->isIndexed()) {
7431 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7432 return DAG.getMergeValues(RetOps, dl);
7435 SDValue RetOps[] = { Value, TF };
7436 return DAG.getMergeValues(RetOps, dl);
7439 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7440 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7442 // To lower v4i1 from a byte array, we load the byte elements of the
7443 // vector and then reuse the BUILD_VECTOR logic.
7445 SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7446 for (unsigned i = 0; i < 4; ++i) {
7447 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7448 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7450 VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7451 dl, MVT::i32, LoadChain, Idx,
7452 LN->getPointerInfo().getWithOffset(i),
7453 MVT::i8 /* memory type */,
7454 LN->isVolatile(), LN->isNonTemporal(),
7456 1 /* alignment */, LN->getAAInfo()));
7457 VectElmtChains.push_back(VectElmts[i].getValue(1));
7460 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7461 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7463 SDValue RVals[] = { Value, LoadChain };
7464 return DAG.getMergeValues(RVals, dl);
7467 /// Lowering for QPX v4i1 stores
7468 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7469 SelectionDAG &DAG) const {
7471 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7472 SDValue StoreChain = SN->getChain();
7473 SDValue BasePtr = SN->getBasePtr();
7474 SDValue Value = SN->getValue();
7476 if (Value.getValueType() == MVT::v4f64 ||
7477 Value.getValueType() == MVT::v4f32) {
7478 EVT MemVT = SN->getMemoryVT();
7479 unsigned Alignment = SN->getAlignment();
7481 // If this store is properly aligned, then it is legal.
7482 if (Alignment >= MemVT.getStoreSize())
7485 EVT ScalarVT = Value.getValueType().getScalarType(),
7486 ScalarMemVT = MemVT.getScalarType();
7487 unsigned Stride = ScalarMemVT.getStoreSize();
7489 SmallVector<SDValue, 8> Stores;
7490 for (unsigned Idx = 0; Idx < 4; ++Idx) {
7492 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7493 DAG.getConstant(Idx, dl, getVectorIdxTy()));
7495 if (ScalarVT != ScalarMemVT)
7497 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7498 SN->getPointerInfo().getWithOffset(Idx*Stride),
7499 ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7500 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7503 DAG.getStore(StoreChain, dl, Ex, BasePtr,
7504 SN->getPointerInfo().getWithOffset(Idx*Stride),
7505 SN->isVolatile(), SN->isNonTemporal(),
7506 MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7508 if (Idx == 0 && SN->isIndexed()) {
7509 assert(SN->getAddressingMode() == ISD::PRE_INC &&
7510 "Unknown addressing mode on vector store");
7511 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7512 SN->getAddressingMode());
7515 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7516 DAG.getConstant(Stride, dl,
7517 BasePtr.getValueType()));
7518 Stores.push_back(Store);
7521 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7523 if (SN->isIndexed()) {
7524 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7525 return DAG.getMergeValues(RetOps, dl);
7531 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7532 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7534 // The values are now known to be -1 (false) or 1 (true). To convert this
7535 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7536 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7537 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7539 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7540 // understand how to form the extending load.
7541 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7542 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7543 FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7545 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7547 // Now convert to an integer and store.
7548 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7549 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7552 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7553 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7554 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7555 EVT PtrVT = getPointerTy();
7556 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7558 SmallVector<SDValue, 2> Ops;
7559 Ops.push_back(StoreChain);
7560 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7561 Ops.push_back(Value);
7562 Ops.push_back(FIdx);
7564 SmallVector<EVT, 2> ValueVTs;
7565 ValueVTs.push_back(MVT::Other); // chain
7566 SDVTList VTs = DAG.getVTList(ValueVTs);
7568 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7569 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7571 // Move data into the byte array.
7572 SmallVector<SDValue, 4> Loads, LoadChains;
7573 for (unsigned i = 0; i < 4; ++i) {
7574 unsigned Offset = 4*i;
7575 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7576 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7578 Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7579 PtrInfo.getWithOffset(Offset),
7580 false, false, false, 0));
7581 LoadChains.push_back(Loads[i].getValue(1));
7584 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7586 SmallVector<SDValue, 4> Stores;
7587 for (unsigned i = 0; i < 4; ++i) {
7588 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7589 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7591 Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7592 SN->getPointerInfo().getWithOffset(i),
7593 MVT::i8 /* memory type */,
7594 SN->isNonTemporal(), SN->isVolatile(),
7595 1 /* alignment */, SN->getAAInfo()));
7598 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7603 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7605 if (Op.getValueType() == MVT::v4i32) {
7606 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7608 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
7609 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7611 SDValue RHSSwap = // = vrlw RHS, 16
7612 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7614 // Shrinkify inputs to v8i16.
7615 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7616 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7617 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7619 // Low parts multiplied together, generating 32-bit results (we ignore the
7621 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7622 LHS, RHS, DAG, dl, MVT::v4i32);
7624 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7625 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7626 // Shift the high parts up 16 bits.
7627 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7629 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7630 } else if (Op.getValueType() == MVT::v8i16) {
7631 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7633 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7635 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7636 LHS, RHS, Zero, DAG, dl);
7637 } else if (Op.getValueType() == MVT::v16i8) {
7638 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7639 bool isLittleEndian = Subtarget.isLittleEndian();
7641 // Multiply the even 8-bit parts, producing 16-bit sums.
7642 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7643 LHS, RHS, DAG, dl, MVT::v8i16);
7644 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7646 // Multiply the odd 8-bit parts, producing 16-bit sums.
7647 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7648 LHS, RHS, DAG, dl, MVT::v8i16);
7649 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7651 // Merge the results together. Because vmuleub and vmuloub are
7652 // instructions with a big-endian bias, we must reverse the
7653 // element numbering and reverse the meaning of "odd" and "even"
7654 // when generating little endian code.
7656 for (unsigned i = 0; i != 8; ++i) {
7657 if (isLittleEndian) {
7659 Ops[i*2+1] = 2*i+16;
7662 Ops[i*2+1] = 2*i+1+16;
7666 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7668 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7670 llvm_unreachable("Unknown mul to lower!");
7674 /// LowerOperation - Provide custom lowering hooks for some operations.
7676 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7677 switch (Op.getOpcode()) {
7678 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7679 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7680 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7681 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7682 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7683 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7684 case ISD::SETCC: return LowerSETCC(Op, DAG);
7685 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
7686 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
7688 return LowerVASTART(Op, DAG, Subtarget);
7691 return LowerVAARG(Op, DAG, Subtarget);
7694 return LowerVACOPY(Op, DAG, Subtarget);
7696 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
7697 case ISD::DYNAMIC_STACKALLOC:
7698 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7700 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
7701 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
7703 case ISD::LOAD: return LowerLOAD(Op, DAG);
7704 case ISD::STORE: return LowerSTORE(Op, DAG);
7705 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
7706 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7707 case ISD::FP_TO_UINT:
7708 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
7710 case ISD::UINT_TO_FP:
7711 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7712 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7714 // Lower 64-bit shifts.
7715 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
7716 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
7717 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
7719 // Vector-related lowering.
7720 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7721 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7722 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7723 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7724 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
7725 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7726 case ISD::MUL: return LowerMUL(Op, DAG);
7728 // For counter-based loop handling.
7729 case ISD::INTRINSIC_W_CHAIN: return SDValue();
7731 // Frame & Return address.
7732 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7733 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7737 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7738 SmallVectorImpl<SDValue>&Results,
7739 SelectionDAG &DAG) const {
7741 switch (N->getOpcode()) {
7743 llvm_unreachable("Do not know how to custom type legalize this operation!");
7744 case ISD::READCYCLECOUNTER: {
7745 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7746 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7748 Results.push_back(RTB);
7749 Results.push_back(RTB.getValue(1));
7750 Results.push_back(RTB.getValue(2));
7753 case ISD::INTRINSIC_W_CHAIN: {
7754 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7755 Intrinsic::ppc_is_decremented_ctr_nonzero)
7758 assert(N->getValueType(0) == MVT::i1 &&
7759 "Unexpected result type for CTR decrement intrinsic");
7760 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7761 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7762 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7765 Results.push_back(NewInt);
7766 Results.push_back(NewInt.getValue(1));
7770 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7773 EVT VT = N->getValueType(0);
7775 if (VT == MVT::i64) {
7776 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7778 Results.push_back(NewNode);
7779 Results.push_back(NewNode.getValue(1));
7783 case ISD::FP_ROUND_INREG: {
7784 assert(N->getValueType(0) == MVT::ppcf128);
7785 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7786 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7787 MVT::f64, N->getOperand(0),
7788 DAG.getIntPtrConstant(0, dl));
7789 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7790 MVT::f64, N->getOperand(0),
7791 DAG.getIntPtrConstant(1, dl));
7793 // Add the two halves of the long double in round-to-zero mode.
7794 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7796 // We know the low half is about to be thrown away, so just use something
7798 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7802 case ISD::FP_TO_SINT:
7803 case ISD::FP_TO_UINT:
7804 // LowerFP_TO_INT() can only handle f32 and f64.
7805 if (N->getOperand(0).getValueType() == MVT::ppcf128)
7807 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7813 //===----------------------------------------------------------------------===//
7814 // Other Lowering Code
7815 //===----------------------------------------------------------------------===//
7817 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7818 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7819 Function *Func = Intrinsic::getDeclaration(M, Id);
7820 return Builder.CreateCall(Func);
7823 // The mappings for emitLeading/TrailingFence is taken from
7824 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7825 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7826 AtomicOrdering Ord, bool IsStore,
7827 bool IsLoad) const {
7828 if (Ord == SequentiallyConsistent)
7829 return callIntrinsic(Builder, Intrinsic::ppc_sync);
7830 else if (isAtLeastRelease(Ord))
7831 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7836 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7837 AtomicOrdering Ord, bool IsStore,
7838 bool IsLoad) const {
7839 if (IsLoad && isAtLeastAcquire(Ord))
7840 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7841 // FIXME: this is too conservative, a dependent branch + isync is enough.
7842 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7843 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7844 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7850 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7851 unsigned AtomicSize,
7852 unsigned BinOpcode) const {
7853 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7854 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7856 auto LoadMnemonic = PPC::LDARX;
7857 auto StoreMnemonic = PPC::STDCX;
7858 switch (AtomicSize) {
7860 llvm_unreachable("Unexpected size of atomic entity");
7862 LoadMnemonic = PPC::LBARX;
7863 StoreMnemonic = PPC::STBCX;
7864 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7867 LoadMnemonic = PPC::LHARX;
7868 StoreMnemonic = PPC::STHCX;
7869 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7872 LoadMnemonic = PPC::LWARX;
7873 StoreMnemonic = PPC::STWCX;
7876 LoadMnemonic = PPC::LDARX;
7877 StoreMnemonic = PPC::STDCX;
7881 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7882 MachineFunction *F = BB->getParent();
7883 MachineFunction::iterator It = BB;
7886 unsigned dest = MI->getOperand(0).getReg();
7887 unsigned ptrA = MI->getOperand(1).getReg();
7888 unsigned ptrB = MI->getOperand(2).getReg();
7889 unsigned incr = MI->getOperand(3).getReg();
7890 DebugLoc dl = MI->getDebugLoc();
7892 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7893 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7894 F->insert(It, loopMBB);
7895 F->insert(It, exitMBB);
7896 exitMBB->splice(exitMBB->begin(), BB,
7897 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7898 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7900 MachineRegisterInfo &RegInfo = F->getRegInfo();
7901 unsigned TmpReg = (!BinOpcode) ? incr :
7902 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7903 : &PPC::GPRCRegClass);
7907 // fallthrough --> loopMBB
7908 BB->addSuccessor(loopMBB);
7911 // l[wd]arx dest, ptr
7912 // add r0, dest, incr
7913 // st[wd]cx. r0, ptr
7915 // fallthrough --> exitMBB
7917 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7918 .addReg(ptrA).addReg(ptrB);
7920 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7921 BuildMI(BB, dl, TII->get(StoreMnemonic))
7922 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7923 BuildMI(BB, dl, TII->get(PPC::BCC))
7924 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7925 BB->addSuccessor(loopMBB);
7926 BB->addSuccessor(exitMBB);
7935 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7936 MachineBasicBlock *BB,
7937 bool is8bit, // operation
7938 unsigned BinOpcode) const {
7939 // If we support part-word atomic mnemonics, just use them
7940 if (Subtarget.hasPartwordAtomics())
7941 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
7943 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7944 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7945 // In 64 bit mode we have to use 64 bits for addresses, even though the
7946 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
7947 // registers without caring whether they're 32 or 64, but here we're
7948 // doing actual arithmetic on the addresses.
7949 bool is64bit = Subtarget.isPPC64();
7950 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7952 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7953 MachineFunction *F = BB->getParent();
7954 MachineFunction::iterator It = BB;
7957 unsigned dest = MI->getOperand(0).getReg();
7958 unsigned ptrA = MI->getOperand(1).getReg();
7959 unsigned ptrB = MI->getOperand(2).getReg();
7960 unsigned incr = MI->getOperand(3).getReg();
7961 DebugLoc dl = MI->getDebugLoc();
7963 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7964 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7965 F->insert(It, loopMBB);
7966 F->insert(It, exitMBB);
7967 exitMBB->splice(exitMBB->begin(), BB,
7968 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7969 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7971 MachineRegisterInfo &RegInfo = F->getRegInfo();
7972 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7973 : &PPC::GPRCRegClass;
7974 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7975 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7976 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7977 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7978 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7979 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7980 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7981 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7982 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7983 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7984 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7986 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7990 // fallthrough --> loopMBB
7991 BB->addSuccessor(loopMBB);
7993 // The 4-byte load must be aligned, while a char or short may be
7994 // anywhere in the word. Hence all this nasty bookkeeping code.
7995 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7996 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7997 // xori shift, shift1, 24 [16]
7998 // rlwinm ptr, ptr1, 0, 0, 29
7999 // slw incr2, incr, shift
8000 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8001 // slw mask, mask2, shift
8003 // lwarx tmpDest, ptr
8004 // add tmp, tmpDest, incr2
8005 // andc tmp2, tmpDest, mask
8006 // and tmp3, tmp, mask
8007 // or tmp4, tmp3, tmp2
8010 // fallthrough --> exitMBB
8011 // srw dest, tmpDest, shift
8012 if (ptrA != ZeroReg) {
8013 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8014 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8015 .addReg(ptrA).addReg(ptrB);
8019 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8020 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8021 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8022 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8024 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8025 .addReg(Ptr1Reg).addImm(0).addImm(61);
8027 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8028 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8029 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8030 .addReg(incr).addReg(ShiftReg);
8032 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8034 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8035 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8037 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8038 .addReg(Mask2Reg).addReg(ShiftReg);
8041 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8042 .addReg(ZeroReg).addReg(PtrReg);
8044 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8045 .addReg(Incr2Reg).addReg(TmpDestReg);
8046 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8047 .addReg(TmpDestReg).addReg(MaskReg);
8048 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8049 .addReg(TmpReg).addReg(MaskReg);
8050 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8051 .addReg(Tmp3Reg).addReg(Tmp2Reg);
8052 BuildMI(BB, dl, TII->get(PPC::STWCX))
8053 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8054 BuildMI(BB, dl, TII->get(PPC::BCC))
8055 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8056 BB->addSuccessor(loopMBB);
8057 BB->addSuccessor(exitMBB);
8062 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8067 llvm::MachineBasicBlock*
8068 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8069 MachineBasicBlock *MBB) const {
8070 DebugLoc DL = MI->getDebugLoc();
8071 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8073 MachineFunction *MF = MBB->getParent();
8074 MachineRegisterInfo &MRI = MF->getRegInfo();
8076 const BasicBlock *BB = MBB->getBasicBlock();
8077 MachineFunction::iterator I = MBB;
8081 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8082 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8084 unsigned DstReg = MI->getOperand(0).getReg();
8085 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8086 assert(RC->hasType(MVT::i32) && "Invalid destination!");
8087 unsigned mainDstReg = MRI.createVirtualRegister(RC);
8088 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8090 MVT PVT = getPointerTy();
8091 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8092 "Invalid Pointer Size!");
8093 // For v = setjmp(buf), we generate
8096 // SjLjSetup mainMBB
8102 // buf[LabelOffset] = LR
8106 // v = phi(main, restore)
8109 MachineBasicBlock *thisMBB = MBB;
8110 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8111 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8112 MF->insert(I, mainMBB);
8113 MF->insert(I, sinkMBB);
8115 MachineInstrBuilder MIB;
8117 // Transfer the remainder of BB and its successor edges to sinkMBB.
8118 sinkMBB->splice(sinkMBB->begin(), MBB,
8119 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8120 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8122 // Note that the structure of the jmp_buf used here is not compatible
8123 // with that used by libc, and is not designed to be. Specifically, it
8124 // stores only those 'reserved' registers that LLVM does not otherwise
8125 // understand how to spill. Also, by convention, by the time this
8126 // intrinsic is called, Clang has already stored the frame address in the
8127 // first slot of the buffer and stack address in the third. Following the
8128 // X86 target code, we'll store the jump address in the second slot. We also
8129 // need to save the TOC pointer (R2) to handle jumps between shared
8130 // libraries, and that will be stored in the fourth slot. The thread
8131 // identifier (R13) is not affected.
8134 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8135 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8136 const int64_t BPOffset = 4 * PVT.getStoreSize();
8138 // Prepare IP either in reg.
8139 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8140 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8141 unsigned BufReg = MI->getOperand(1).getReg();
8143 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8144 setUsesTOCBasePtr(*MBB->getParent());
8145 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8149 MIB.setMemRefs(MMOBegin, MMOEnd);
8152 // Naked functions never have a base pointer, and so we use r1. For all
8153 // other functions, this decision must be delayed until during PEI.
8155 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8156 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8158 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8160 MIB = BuildMI(*thisMBB, MI, DL,
8161 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8165 MIB.setMemRefs(MMOBegin, MMOEnd);
8168 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8169 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8170 MIB.addRegMask(TRI->getNoPreservedMask());
8172 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8174 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8176 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8178 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8179 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8184 BuildMI(mainMBB, DL,
8185 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8188 if (Subtarget.isPPC64()) {
8189 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8191 .addImm(LabelOffset)
8194 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8196 .addImm(LabelOffset)
8200 MIB.setMemRefs(MMOBegin, MMOEnd);
8202 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8203 mainMBB->addSuccessor(sinkMBB);
8206 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8207 TII->get(PPC::PHI), DstReg)
8208 .addReg(mainDstReg).addMBB(mainMBB)
8209 .addReg(restoreDstReg).addMBB(thisMBB);
8211 MI->eraseFromParent();
8216 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8217 MachineBasicBlock *MBB) const {
8218 DebugLoc DL = MI->getDebugLoc();
8219 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8221 MachineFunction *MF = MBB->getParent();
8222 MachineRegisterInfo &MRI = MF->getRegInfo();
8225 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8226 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8228 MVT PVT = getPointerTy();
8229 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8230 "Invalid Pointer Size!");
8232 const TargetRegisterClass *RC =
8233 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8234 unsigned Tmp = MRI.createVirtualRegister(RC);
8235 // Since FP is only updated here but NOT referenced, it's treated as GPR.
8236 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8237 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8241 : (Subtarget.isSVR4ABI() &&
8242 MF->getTarget().getRelocationModel() == Reloc::PIC_
8246 MachineInstrBuilder MIB;
8248 const int64_t LabelOffset = 1 * PVT.getStoreSize();
8249 const int64_t SPOffset = 2 * PVT.getStoreSize();
8250 const int64_t TOCOffset = 3 * PVT.getStoreSize();
8251 const int64_t BPOffset = 4 * PVT.getStoreSize();
8253 unsigned BufReg = MI->getOperand(0).getReg();
8255 // Reload FP (the jumped-to function may not have had a
8256 // frame pointer, and if so, then its r31 will be restored
8258 if (PVT == MVT::i64) {
8259 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8263 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8267 MIB.setMemRefs(MMOBegin, MMOEnd);
8270 if (PVT == MVT::i64) {
8271 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8272 .addImm(LabelOffset)
8275 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8276 .addImm(LabelOffset)
8279 MIB.setMemRefs(MMOBegin, MMOEnd);
8282 if (PVT == MVT::i64) {
8283 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8287 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8291 MIB.setMemRefs(MMOBegin, MMOEnd);
8294 if (PVT == MVT::i64) {
8295 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8299 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8303 MIB.setMemRefs(MMOBegin, MMOEnd);
8306 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8307 setUsesTOCBasePtr(*MBB->getParent());
8308 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8312 MIB.setMemRefs(MMOBegin, MMOEnd);
8316 BuildMI(*MBB, MI, DL,
8317 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8318 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8320 MI->eraseFromParent();
8325 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8326 MachineBasicBlock *BB) const {
8327 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8328 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8329 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8330 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8331 // Call lowering should have added an r2 operand to indicate a dependence
8332 // on the TOC base pointer value. It can't however, because there is no
8333 // way to mark the dependence as implicit there, and so the stackmap code
8334 // will confuse it with a regular operand. Instead, add the dependence
8336 setUsesTOCBasePtr(*BB->getParent());
8337 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8340 return emitPatchPoint(MI, BB);
8343 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8344 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8345 return emitEHSjLjSetJmp(MI, BB);
8346 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8347 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8348 return emitEHSjLjLongJmp(MI, BB);
8351 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8353 // To "insert" these instructions we actually have to insert their
8354 // control-flow patterns.
8355 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8356 MachineFunction::iterator It = BB;
8359 MachineFunction *F = BB->getParent();
8361 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8362 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8363 MI->getOpcode() == PPC::SELECT_I4 ||
8364 MI->getOpcode() == PPC::SELECT_I8)) {
8365 SmallVector<MachineOperand, 2> Cond;
8366 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8367 MI->getOpcode() == PPC::SELECT_CC_I8)
8368 Cond.push_back(MI->getOperand(4));
8370 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8371 Cond.push_back(MI->getOperand(1));
8373 DebugLoc dl = MI->getDebugLoc();
8374 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8375 Cond, MI->getOperand(2).getReg(),
8376 MI->getOperand(3).getReg());
8377 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8378 MI->getOpcode() == PPC::SELECT_CC_I8 ||
8379 MI->getOpcode() == PPC::SELECT_CC_F4 ||
8380 MI->getOpcode() == PPC::SELECT_CC_F8 ||
8381 MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8382 MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8383 MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8384 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8385 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8386 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8387 MI->getOpcode() == PPC::SELECT_I4 ||
8388 MI->getOpcode() == PPC::SELECT_I8 ||
8389 MI->getOpcode() == PPC::SELECT_F4 ||
8390 MI->getOpcode() == PPC::SELECT_F8 ||
8391 MI->getOpcode() == PPC::SELECT_QFRC ||
8392 MI->getOpcode() == PPC::SELECT_QSRC ||
8393 MI->getOpcode() == PPC::SELECT_QBRC ||
8394 MI->getOpcode() == PPC::SELECT_VRRC ||
8395 MI->getOpcode() == PPC::SELECT_VSFRC ||
8396 MI->getOpcode() == PPC::SELECT_VSRC) {
8397 // The incoming instruction knows the destination vreg to set, the
8398 // condition code register to branch on, the true/false values to
8399 // select between, and a branch opcode to use.
8404 // cmpTY ccX, r1, r2
8406 // fallthrough --> copy0MBB
8407 MachineBasicBlock *thisMBB = BB;
8408 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8409 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8410 DebugLoc dl = MI->getDebugLoc();
8411 F->insert(It, copy0MBB);
8412 F->insert(It, sinkMBB);
8414 // Transfer the remainder of BB and its successor edges to sinkMBB.
8415 sinkMBB->splice(sinkMBB->begin(), BB,
8416 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8417 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8419 // Next, add the true and fallthrough blocks as its successors.
8420 BB->addSuccessor(copy0MBB);
8421 BB->addSuccessor(sinkMBB);
8423 if (MI->getOpcode() == PPC::SELECT_I4 ||
8424 MI->getOpcode() == PPC::SELECT_I8 ||
8425 MI->getOpcode() == PPC::SELECT_F4 ||
8426 MI->getOpcode() == PPC::SELECT_F8 ||
8427 MI->getOpcode() == PPC::SELECT_QFRC ||
8428 MI->getOpcode() == PPC::SELECT_QSRC ||
8429 MI->getOpcode() == PPC::SELECT_QBRC ||
8430 MI->getOpcode() == PPC::SELECT_VRRC ||
8431 MI->getOpcode() == PPC::SELECT_VSFRC ||
8432 MI->getOpcode() == PPC::SELECT_VSRC) {
8433 BuildMI(BB, dl, TII->get(PPC::BC))
8434 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8436 unsigned SelectPred = MI->getOperand(4).getImm();
8437 BuildMI(BB, dl, TII->get(PPC::BCC))
8438 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8442 // %FalseValue = ...
8443 // # fallthrough to sinkMBB
8446 // Update machine-CFG edges
8447 BB->addSuccessor(sinkMBB);
8450 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8453 BuildMI(*BB, BB->begin(), dl,
8454 TII->get(PPC::PHI), MI->getOperand(0).getReg())
8455 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8456 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8457 } else if (MI->getOpcode() == PPC::ReadTB) {
8458 // To read the 64-bit time-base register on a 32-bit target, we read the
8459 // two halves. Should the counter have wrapped while it was being read, we
8460 // need to try again.
8463 // mfspr Rx,TBU # load from TBU
8464 // mfspr Ry,TB # load from TB
8465 // mfspr Rz,TBU # load from TBU
8466 // cmpw crX,Rx,Rz # check if ‘old’=’new’
8467 // bne readLoop # branch if they're not equal
8470 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8471 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8472 DebugLoc dl = MI->getDebugLoc();
8473 F->insert(It, readMBB);
8474 F->insert(It, sinkMBB);
8476 // Transfer the remainder of BB and its successor edges to sinkMBB.
8477 sinkMBB->splice(sinkMBB->begin(), BB,
8478 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8479 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8481 BB->addSuccessor(readMBB);
8484 MachineRegisterInfo &RegInfo = F->getRegInfo();
8485 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8486 unsigned LoReg = MI->getOperand(0).getReg();
8487 unsigned HiReg = MI->getOperand(1).getReg();
8489 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8490 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8491 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8493 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8495 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8496 .addReg(HiReg).addReg(ReadAgainReg);
8497 BuildMI(BB, dl, TII->get(PPC::BCC))
8498 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8500 BB->addSuccessor(readMBB);
8501 BB->addSuccessor(sinkMBB);
8503 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8504 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8505 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8506 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8507 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8508 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8509 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8510 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8512 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8513 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8514 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8515 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8516 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8517 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8518 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8519 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8521 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8522 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8523 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8524 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8525 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8526 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8527 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8528 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8530 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8531 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8532 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8533 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8534 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8535 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8536 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8537 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8539 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8540 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8541 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8542 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8543 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8544 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8545 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8546 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8548 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8549 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8550 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8551 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8552 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8553 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8554 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8555 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8557 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8558 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8559 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8560 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8561 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8562 BB = EmitAtomicBinary(MI, BB, 4, 0);
8563 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8564 BB = EmitAtomicBinary(MI, BB, 8, 0);
8566 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8567 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8568 (Subtarget.hasPartwordAtomics() &&
8569 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8570 (Subtarget.hasPartwordAtomics() &&
8571 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8572 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8574 auto LoadMnemonic = PPC::LDARX;
8575 auto StoreMnemonic = PPC::STDCX;
8576 switch(MI->getOpcode()) {
8578 llvm_unreachable("Compare and swap of unknown size");
8579 case PPC::ATOMIC_CMP_SWAP_I8:
8580 LoadMnemonic = PPC::LBARX;
8581 StoreMnemonic = PPC::STBCX;
8582 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8584 case PPC::ATOMIC_CMP_SWAP_I16:
8585 LoadMnemonic = PPC::LHARX;
8586 StoreMnemonic = PPC::STHCX;
8587 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8589 case PPC::ATOMIC_CMP_SWAP_I32:
8590 LoadMnemonic = PPC::LWARX;
8591 StoreMnemonic = PPC::STWCX;
8593 case PPC::ATOMIC_CMP_SWAP_I64:
8594 LoadMnemonic = PPC::LDARX;
8595 StoreMnemonic = PPC::STDCX;
8598 unsigned dest = MI->getOperand(0).getReg();
8599 unsigned ptrA = MI->getOperand(1).getReg();
8600 unsigned ptrB = MI->getOperand(2).getReg();
8601 unsigned oldval = MI->getOperand(3).getReg();
8602 unsigned newval = MI->getOperand(4).getReg();
8603 DebugLoc dl = MI->getDebugLoc();
8605 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8606 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8607 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8608 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8609 F->insert(It, loop1MBB);
8610 F->insert(It, loop2MBB);
8611 F->insert(It, midMBB);
8612 F->insert(It, exitMBB);
8613 exitMBB->splice(exitMBB->begin(), BB,
8614 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8615 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8619 // fallthrough --> loopMBB
8620 BB->addSuccessor(loop1MBB);
8623 // l[bhwd]arx dest, ptr
8624 // cmp[wd] dest, oldval
8627 // st[bhwd]cx. newval, ptr
8631 // st[bhwd]cx. dest, ptr
8634 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8635 .addReg(ptrA).addReg(ptrB);
8636 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8637 .addReg(oldval).addReg(dest);
8638 BuildMI(BB, dl, TII->get(PPC::BCC))
8639 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8640 BB->addSuccessor(loop2MBB);
8641 BB->addSuccessor(midMBB);
8644 BuildMI(BB, dl, TII->get(StoreMnemonic))
8645 .addReg(newval).addReg(ptrA).addReg(ptrB);
8646 BuildMI(BB, dl, TII->get(PPC::BCC))
8647 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8648 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8649 BB->addSuccessor(loop1MBB);
8650 BB->addSuccessor(exitMBB);
8653 BuildMI(BB, dl, TII->get(StoreMnemonic))
8654 .addReg(dest).addReg(ptrA).addReg(ptrB);
8655 BB->addSuccessor(exitMBB);
8660 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8661 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8662 // We must use 64-bit registers for addresses when targeting 64-bit,
8663 // since we're actually doing arithmetic on them. Other registers
8665 bool is64bit = Subtarget.isPPC64();
8666 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8668 unsigned dest = MI->getOperand(0).getReg();
8669 unsigned ptrA = MI->getOperand(1).getReg();
8670 unsigned ptrB = MI->getOperand(2).getReg();
8671 unsigned oldval = MI->getOperand(3).getReg();
8672 unsigned newval = MI->getOperand(4).getReg();
8673 DebugLoc dl = MI->getDebugLoc();
8675 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8676 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8677 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8678 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8679 F->insert(It, loop1MBB);
8680 F->insert(It, loop2MBB);
8681 F->insert(It, midMBB);
8682 F->insert(It, exitMBB);
8683 exitMBB->splice(exitMBB->begin(), BB,
8684 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8685 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8687 MachineRegisterInfo &RegInfo = F->getRegInfo();
8688 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8689 : &PPC::GPRCRegClass;
8690 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8691 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8692 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8693 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8694 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8695 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8696 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8697 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8698 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8699 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8700 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8701 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8702 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8704 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8705 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8708 // fallthrough --> loopMBB
8709 BB->addSuccessor(loop1MBB);
8711 // The 4-byte load must be aligned, while a char or short may be
8712 // anywhere in the word. Hence all this nasty bookkeeping code.
8713 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8714 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8715 // xori shift, shift1, 24 [16]
8716 // rlwinm ptr, ptr1, 0, 0, 29
8717 // slw newval2, newval, shift
8718 // slw oldval2, oldval,shift
8719 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8720 // slw mask, mask2, shift
8721 // and newval3, newval2, mask
8722 // and oldval3, oldval2, mask
8724 // lwarx tmpDest, ptr
8725 // and tmp, tmpDest, mask
8726 // cmpw tmp, oldval3
8729 // andc tmp2, tmpDest, mask
8730 // or tmp4, tmp2, newval3
8735 // stwcx. tmpDest, ptr
8737 // srw dest, tmpDest, shift
8738 if (ptrA != ZeroReg) {
8739 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8740 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8741 .addReg(ptrA).addReg(ptrB);
8745 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8746 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8747 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8748 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8750 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8751 .addReg(Ptr1Reg).addImm(0).addImm(61);
8753 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8754 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8755 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8756 .addReg(newval).addReg(ShiftReg);
8757 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8758 .addReg(oldval).addReg(ShiftReg);
8760 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8762 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8763 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8764 .addReg(Mask3Reg).addImm(65535);
8766 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8767 .addReg(Mask2Reg).addReg(ShiftReg);
8768 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8769 .addReg(NewVal2Reg).addReg(MaskReg);
8770 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8771 .addReg(OldVal2Reg).addReg(MaskReg);
8774 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8775 .addReg(ZeroReg).addReg(PtrReg);
8776 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8777 .addReg(TmpDestReg).addReg(MaskReg);
8778 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8779 .addReg(TmpReg).addReg(OldVal3Reg);
8780 BuildMI(BB, dl, TII->get(PPC::BCC))
8781 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8782 BB->addSuccessor(loop2MBB);
8783 BB->addSuccessor(midMBB);
8786 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8787 .addReg(TmpDestReg).addReg(MaskReg);
8788 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8789 .addReg(Tmp2Reg).addReg(NewVal3Reg);
8790 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8791 .addReg(ZeroReg).addReg(PtrReg);
8792 BuildMI(BB, dl, TII->get(PPC::BCC))
8793 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8794 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8795 BB->addSuccessor(loop1MBB);
8796 BB->addSuccessor(exitMBB);
8799 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8800 .addReg(ZeroReg).addReg(PtrReg);
8801 BB->addSuccessor(exitMBB);
8806 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8808 } else if (MI->getOpcode() == PPC::FADDrtz) {
8809 // This pseudo performs an FADD with rounding mode temporarily forced
8810 // to round-to-zero. We emit this via custom inserter since the FPSCR
8811 // is not modeled at the SelectionDAG level.
8812 unsigned Dest = MI->getOperand(0).getReg();
8813 unsigned Src1 = MI->getOperand(1).getReg();
8814 unsigned Src2 = MI->getOperand(2).getReg();
8815 DebugLoc dl = MI->getDebugLoc();
8817 MachineRegisterInfo &RegInfo = F->getRegInfo();
8818 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8820 // Save FPSCR value.
8821 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8823 // Set rounding mode to round-to-zero.
8824 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8825 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8827 // Perform addition.
8828 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8830 // Restore FPSCR value.
8831 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8832 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8833 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8834 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8835 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8836 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8837 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8838 PPC::ANDIo8 : PPC::ANDIo;
8839 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8840 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8842 MachineRegisterInfo &RegInfo = F->getRegInfo();
8843 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8844 &PPC::GPRCRegClass :
8845 &PPC::G8RCRegClass);
8847 DebugLoc dl = MI->getDebugLoc();
8848 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8849 .addReg(MI->getOperand(1).getReg()).addImm(1);
8850 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8851 MI->getOperand(0).getReg())
8852 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8853 } else if (MI->getOpcode() == PPC::TCHECK_RET) {
8854 DebugLoc Dl = MI->getDebugLoc();
8855 MachineRegisterInfo &RegInfo = F->getRegInfo();
8856 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8857 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
8860 llvm_unreachable("Unexpected instr type to insert");
8863 MI->eraseFromParent(); // The pseudo instruction is gone now.
8867 //===----------------------------------------------------------------------===//
8868 // Target Optimization Hooks
8869 //===----------------------------------------------------------------------===//
8871 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8872 DAGCombinerInfo &DCI,
8873 unsigned &RefinementSteps,
8874 bool &UseOneConstNR) const {
8875 EVT VT = Operand.getValueType();
8876 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8877 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8878 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8879 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8880 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8881 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8882 // Convergence is quadratic, so we essentially double the number of digits
8883 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8884 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8885 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8886 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8887 if (VT.getScalarType() == MVT::f64)
8889 UseOneConstNR = true;
8890 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8895 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8896 DAGCombinerInfo &DCI,
8897 unsigned &RefinementSteps) const {
8898 EVT VT = Operand.getValueType();
8899 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8900 (VT == MVT::f64 && Subtarget.hasFRE()) ||
8901 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8902 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8903 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8904 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8905 // Convergence is quadratic, so we essentially double the number of digits
8906 // correct after every iteration. For both FRE and FRSQRTE, the minimum
8907 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8908 // 2^-14. IEEE float has 23 digits and double has 52 digits.
8909 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8910 if (VT.getScalarType() == MVT::f64)
8912 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8917 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8918 // Note: This functionality is used only when unsafe-fp-math is enabled, and
8919 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8920 // enabled for division), this functionality is redundant with the default
8921 // combiner logic (once the division -> reciprocal/multiply transformation
8922 // has taken place). As a result, this matters more for older cores than for
8925 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8926 // reciprocal if there are two or more FDIVs (for embedded cores with only
8927 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8928 switch (Subtarget.getDarwinDirective()) {
8930 return NumUsers > 2;
8933 case PPC::DIR_E500mc:
8934 case PPC::DIR_E5500:
8935 return NumUsers > 1;
8939 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8940 unsigned Bytes, int Dist,
8941 SelectionDAG &DAG) {
8942 if (VT.getSizeInBits() / 8 != Bytes)
8945 SDValue BaseLoc = Base->getBasePtr();
8946 if (Loc.getOpcode() == ISD::FrameIndex) {
8947 if (BaseLoc.getOpcode() != ISD::FrameIndex)
8949 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8950 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
8951 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8952 int FS = MFI->getObjectSize(FI);
8953 int BFS = MFI->getObjectSize(BFI);
8954 if (FS != BFS || FS != (int)Bytes) return false;
8955 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8959 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8960 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8963 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8964 const GlobalValue *GV1 = nullptr;
8965 const GlobalValue *GV2 = nullptr;
8966 int64_t Offset1 = 0;
8967 int64_t Offset2 = 0;
8968 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8969 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8970 if (isGA1 && isGA2 && GV1 == GV2)
8971 return Offset1 == (Offset2 + Dist*Bytes);
8975 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8976 // not enforce equality of the chain operands.
8977 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8978 unsigned Bytes, int Dist,
8979 SelectionDAG &DAG) {
8980 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8981 EVT VT = LS->getMemoryVT();
8982 SDValue Loc = LS->getBasePtr();
8983 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8986 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8988 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8989 default: return false;
8990 case Intrinsic::ppc_qpx_qvlfd:
8991 case Intrinsic::ppc_qpx_qvlfda:
8994 case Intrinsic::ppc_qpx_qvlfs:
8995 case Intrinsic::ppc_qpx_qvlfsa:
8998 case Intrinsic::ppc_qpx_qvlfcd:
8999 case Intrinsic::ppc_qpx_qvlfcda:
9002 case Intrinsic::ppc_qpx_qvlfcs:
9003 case Intrinsic::ppc_qpx_qvlfcsa:
9006 case Intrinsic::ppc_qpx_qvlfiwa:
9007 case Intrinsic::ppc_qpx_qvlfiwz:
9008 case Intrinsic::ppc_altivec_lvx:
9009 case Intrinsic::ppc_altivec_lvxl:
9010 case Intrinsic::ppc_vsx_lxvw4x:
9013 case Intrinsic::ppc_vsx_lxvd2x:
9016 case Intrinsic::ppc_altivec_lvebx:
9019 case Intrinsic::ppc_altivec_lvehx:
9022 case Intrinsic::ppc_altivec_lvewx:
9027 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9030 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9032 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9033 default: return false;
9034 case Intrinsic::ppc_qpx_qvstfd:
9035 case Intrinsic::ppc_qpx_qvstfda:
9038 case Intrinsic::ppc_qpx_qvstfs:
9039 case Intrinsic::ppc_qpx_qvstfsa:
9042 case Intrinsic::ppc_qpx_qvstfcd:
9043 case Intrinsic::ppc_qpx_qvstfcda:
9046 case Intrinsic::ppc_qpx_qvstfcs:
9047 case Intrinsic::ppc_qpx_qvstfcsa:
9050 case Intrinsic::ppc_qpx_qvstfiw:
9051 case Intrinsic::ppc_qpx_qvstfiwa:
9052 case Intrinsic::ppc_altivec_stvx:
9053 case Intrinsic::ppc_altivec_stvxl:
9054 case Intrinsic::ppc_vsx_stxvw4x:
9057 case Intrinsic::ppc_vsx_stxvd2x:
9060 case Intrinsic::ppc_altivec_stvebx:
9063 case Intrinsic::ppc_altivec_stvehx:
9066 case Intrinsic::ppc_altivec_stvewx:
9071 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9077 // Return true is there is a nearyby consecutive load to the one provided
9078 // (regardless of alignment). We search up and down the chain, looking though
9079 // token factors and other loads (but nothing else). As a result, a true result
9080 // indicates that it is safe to create a new consecutive load adjacent to the
9082 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9083 SDValue Chain = LD->getChain();
9084 EVT VT = LD->getMemoryVT();
9086 SmallSet<SDNode *, 16> LoadRoots;
9087 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9088 SmallSet<SDNode *, 16> Visited;
9090 // First, search up the chain, branching to follow all token-factor operands.
9091 // If we find a consecutive load, then we're done, otherwise, record all
9092 // nodes just above the top-level loads and token factors.
9093 while (!Queue.empty()) {
9094 SDNode *ChainNext = Queue.pop_back_val();
9095 if (!Visited.insert(ChainNext).second)
9098 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9099 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9102 if (!Visited.count(ChainLD->getChain().getNode()))
9103 Queue.push_back(ChainLD->getChain().getNode());
9104 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9105 for (const SDUse &O : ChainNext->ops())
9106 if (!Visited.count(O.getNode()))
9107 Queue.push_back(O.getNode());
9109 LoadRoots.insert(ChainNext);
9112 // Second, search down the chain, starting from the top-level nodes recorded
9113 // in the first phase. These top-level nodes are the nodes just above all
9114 // loads and token factors. Starting with their uses, recursively look though
9115 // all loads (just the chain uses) and token factors to find a consecutive
9120 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9121 IE = LoadRoots.end(); I != IE; ++I) {
9122 Queue.push_back(*I);
9124 while (!Queue.empty()) {
9125 SDNode *LoadRoot = Queue.pop_back_val();
9126 if (!Visited.insert(LoadRoot).second)
9129 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9130 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9133 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9134 UE = LoadRoot->use_end(); UI != UE; ++UI)
9135 if (((isa<MemSDNode>(*UI) &&
9136 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9137 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9138 Queue.push_back(*UI);
9145 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9146 DAGCombinerInfo &DCI) const {
9147 SelectionDAG &DAG = DCI.DAG;
9150 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9151 // If we're tracking CR bits, we need to be careful that we don't have:
9152 // trunc(binary-ops(zext(x), zext(y)))
9154 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9155 // such that we're unnecessarily moving things into GPRs when it would be
9156 // better to keep them in CR bits.
9158 // Note that trunc here can be an actual i1 trunc, or can be the effective
9159 // truncation that comes from a setcc or select_cc.
9160 if (N->getOpcode() == ISD::TRUNCATE &&
9161 N->getValueType(0) != MVT::i1)
9164 if (N->getOperand(0).getValueType() != MVT::i32 &&
9165 N->getOperand(0).getValueType() != MVT::i64)
9168 if (N->getOpcode() == ISD::SETCC ||
9169 N->getOpcode() == ISD::SELECT_CC) {
9170 // If we're looking at a comparison, then we need to make sure that the
9171 // high bits (all except for the first) don't matter the result.
9173 cast<CondCodeSDNode>(N->getOperand(
9174 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9175 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9177 if (ISD::isSignedIntSetCC(CC)) {
9178 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9179 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9181 } else if (ISD::isUnsignedIntSetCC(CC)) {
9182 if (!DAG.MaskedValueIsZero(N->getOperand(0),
9183 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9184 !DAG.MaskedValueIsZero(N->getOperand(1),
9185 APInt::getHighBitsSet(OpBits, OpBits-1)))
9188 // This is neither a signed nor an unsigned comparison, just make sure
9189 // that the high bits are equal.
9190 APInt Op1Zero, Op1One;
9191 APInt Op2Zero, Op2One;
9192 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9193 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9195 // We don't really care about what is known about the first bit (if
9196 // anything), so clear it in all masks prior to comparing them.
9197 Op1Zero.clearBit(0); Op1One.clearBit(0);
9198 Op2Zero.clearBit(0); Op2One.clearBit(0);
9200 if (Op1Zero != Op2Zero || Op1One != Op2One)
9205 // We now know that the higher-order bits are irrelevant, we just need to
9206 // make sure that all of the intermediate operations are bit operations, and
9207 // all inputs are extensions.
9208 if (N->getOperand(0).getOpcode() != ISD::AND &&
9209 N->getOperand(0).getOpcode() != ISD::OR &&
9210 N->getOperand(0).getOpcode() != ISD::XOR &&
9211 N->getOperand(0).getOpcode() != ISD::SELECT &&
9212 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9213 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9214 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9215 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9216 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9219 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9220 N->getOperand(1).getOpcode() != ISD::AND &&
9221 N->getOperand(1).getOpcode() != ISD::OR &&
9222 N->getOperand(1).getOpcode() != ISD::XOR &&
9223 N->getOperand(1).getOpcode() != ISD::SELECT &&
9224 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9225 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9226 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9227 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9228 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9231 SmallVector<SDValue, 4> Inputs;
9232 SmallVector<SDValue, 8> BinOps, PromOps;
9233 SmallPtrSet<SDNode *, 16> Visited;
9235 for (unsigned i = 0; i < 2; ++i) {
9236 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9237 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9238 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9239 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9240 isa<ConstantSDNode>(N->getOperand(i)))
9241 Inputs.push_back(N->getOperand(i));
9243 BinOps.push_back(N->getOperand(i));
9245 if (N->getOpcode() == ISD::TRUNCATE)
9249 // Visit all inputs, collect all binary operations (and, or, xor and
9250 // select) that are all fed by extensions.
9251 while (!BinOps.empty()) {
9252 SDValue BinOp = BinOps.back();
9255 if (!Visited.insert(BinOp.getNode()).second)
9258 PromOps.push_back(BinOp);
9260 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9261 // The condition of the select is not promoted.
9262 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9264 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9267 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9268 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9269 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9270 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9271 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9272 Inputs.push_back(BinOp.getOperand(i));
9273 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9274 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9275 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9276 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9277 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9278 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9279 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9280 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9281 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9282 BinOps.push_back(BinOp.getOperand(i));
9284 // We have an input that is not an extension or another binary
9285 // operation; we'll abort this transformation.
9291 // Make sure that this is a self-contained cluster of operations (which
9292 // is not quite the same thing as saying that everything has only one
9294 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9295 if (isa<ConstantSDNode>(Inputs[i]))
9298 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9299 UE = Inputs[i].getNode()->use_end();
9302 if (User != N && !Visited.count(User))
9305 // Make sure that we're not going to promote the non-output-value
9306 // operand(s) or SELECT or SELECT_CC.
9307 // FIXME: Although we could sometimes handle this, and it does occur in
9308 // practice that one of the condition inputs to the select is also one of
9309 // the outputs, we currently can't deal with this.
9310 if (User->getOpcode() == ISD::SELECT) {
9311 if (User->getOperand(0) == Inputs[i])
9313 } else if (User->getOpcode() == ISD::SELECT_CC) {
9314 if (User->getOperand(0) == Inputs[i] ||
9315 User->getOperand(1) == Inputs[i])
9321 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9322 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9323 UE = PromOps[i].getNode()->use_end();
9326 if (User != N && !Visited.count(User))
9329 // Make sure that we're not going to promote the non-output-value
9330 // operand(s) or SELECT or SELECT_CC.
9331 // FIXME: Although we could sometimes handle this, and it does occur in
9332 // practice that one of the condition inputs to the select is also one of
9333 // the outputs, we currently can't deal with this.
9334 if (User->getOpcode() == ISD::SELECT) {
9335 if (User->getOperand(0) == PromOps[i])
9337 } else if (User->getOpcode() == ISD::SELECT_CC) {
9338 if (User->getOperand(0) == PromOps[i] ||
9339 User->getOperand(1) == PromOps[i])
9345 // Replace all inputs with the extension operand.
9346 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9347 // Constants may have users outside the cluster of to-be-promoted nodes,
9348 // and so we need to replace those as we do the promotions.
9349 if (isa<ConstantSDNode>(Inputs[i]))
9352 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9355 // Replace all operations (these are all the same, but have a different
9356 // (i1) return type). DAG.getNode will validate that the types of
9357 // a binary operator match, so go through the list in reverse so that
9358 // we've likely promoted both operands first. Any intermediate truncations or
9359 // extensions disappear.
9360 while (!PromOps.empty()) {
9361 SDValue PromOp = PromOps.back();
9364 if (PromOp.getOpcode() == ISD::TRUNCATE ||
9365 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9366 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9367 PromOp.getOpcode() == ISD::ANY_EXTEND) {
9368 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9369 PromOp.getOperand(0).getValueType() != MVT::i1) {
9370 // The operand is not yet ready (see comment below).
9371 PromOps.insert(PromOps.begin(), PromOp);
9375 SDValue RepValue = PromOp.getOperand(0);
9376 if (isa<ConstantSDNode>(RepValue))
9377 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9379 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9384 switch (PromOp.getOpcode()) {
9385 default: C = 0; break;
9386 case ISD::SELECT: C = 1; break;
9387 case ISD::SELECT_CC: C = 2; break;
9390 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9391 PromOp.getOperand(C).getValueType() != MVT::i1) ||
9392 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9393 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9394 // The to-be-promoted operands of this node have not yet been
9395 // promoted (this should be rare because we're going through the
9396 // list backward, but if one of the operands has several users in
9397 // this cluster of to-be-promoted nodes, it is possible).
9398 PromOps.insert(PromOps.begin(), PromOp);
9402 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9403 PromOp.getNode()->op_end());
9405 // If there are any constant inputs, make sure they're replaced now.
9406 for (unsigned i = 0; i < 2; ++i)
9407 if (isa<ConstantSDNode>(Ops[C+i]))
9408 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9410 DAG.ReplaceAllUsesOfValueWith(PromOp,
9411 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9414 // Now we're left with the initial truncation itself.
9415 if (N->getOpcode() == ISD::TRUNCATE)
9416 return N->getOperand(0);
9418 // Otherwise, this is a comparison. The operands to be compared have just
9419 // changed type (to i1), but everything else is the same.
9420 return SDValue(N, 0);
9423 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9424 DAGCombinerInfo &DCI) const {
9425 SelectionDAG &DAG = DCI.DAG;
9428 // If we're tracking CR bits, we need to be careful that we don't have:
9429 // zext(binary-ops(trunc(x), trunc(y)))
9431 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9432 // such that we're unnecessarily moving things into CR bits that can more
9433 // efficiently stay in GPRs. Note that if we're not certain that the high
9434 // bits are set as required by the final extension, we still may need to do
9435 // some masking to get the proper behavior.
9437 // This same functionality is important on PPC64 when dealing with
9438 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9439 // the return values of functions. Because it is so similar, it is handled
9442 if (N->getValueType(0) != MVT::i32 &&
9443 N->getValueType(0) != MVT::i64)
9446 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9447 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9450 if (N->getOperand(0).getOpcode() != ISD::AND &&
9451 N->getOperand(0).getOpcode() != ISD::OR &&
9452 N->getOperand(0).getOpcode() != ISD::XOR &&
9453 N->getOperand(0).getOpcode() != ISD::SELECT &&
9454 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9457 SmallVector<SDValue, 4> Inputs;
9458 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9459 SmallPtrSet<SDNode *, 16> Visited;
9461 // Visit all inputs, collect all binary operations (and, or, xor and
9462 // select) that are all fed by truncations.
9463 while (!BinOps.empty()) {
9464 SDValue BinOp = BinOps.back();
9467 if (!Visited.insert(BinOp.getNode()).second)
9470 PromOps.push_back(BinOp);
9472 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9473 // The condition of the select is not promoted.
9474 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9476 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9479 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9480 isa<ConstantSDNode>(BinOp.getOperand(i))) {
9481 Inputs.push_back(BinOp.getOperand(i));
9482 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9483 BinOp.getOperand(i).getOpcode() == ISD::OR ||
9484 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9485 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9486 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9487 BinOps.push_back(BinOp.getOperand(i));
9489 // We have an input that is not a truncation or another binary
9490 // operation; we'll abort this transformation.
9496 // The operands of a select that must be truncated when the select is
9497 // promoted because the operand is actually part of the to-be-promoted set.
9498 DenseMap<SDNode *, EVT> SelectTruncOp[2];
9500 // Make sure that this is a self-contained cluster of operations (which
9501 // is not quite the same thing as saying that everything has only one
9503 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9504 if (isa<ConstantSDNode>(Inputs[i]))
9507 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9508 UE = Inputs[i].getNode()->use_end();
9511 if (User != N && !Visited.count(User))
9514 // If we're going to promote the non-output-value operand(s) or SELECT or
9515 // SELECT_CC, record them for truncation.
9516 if (User->getOpcode() == ISD::SELECT) {
9517 if (User->getOperand(0) == Inputs[i])
9518 SelectTruncOp[0].insert(std::make_pair(User,
9519 User->getOperand(0).getValueType()));
9520 } else if (User->getOpcode() == ISD::SELECT_CC) {
9521 if (User->getOperand(0) == Inputs[i])
9522 SelectTruncOp[0].insert(std::make_pair(User,
9523 User->getOperand(0).getValueType()));
9524 if (User->getOperand(1) == Inputs[i])
9525 SelectTruncOp[1].insert(std::make_pair(User,
9526 User->getOperand(1).getValueType()));
9531 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9532 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9533 UE = PromOps[i].getNode()->use_end();
9536 if (User != N && !Visited.count(User))
9539 // If we're going to promote the non-output-value operand(s) or SELECT or
9540 // SELECT_CC, record them for truncation.
9541 if (User->getOpcode() == ISD::SELECT) {
9542 if (User->getOperand(0) == PromOps[i])
9543 SelectTruncOp[0].insert(std::make_pair(User,
9544 User->getOperand(0).getValueType()));
9545 } else if (User->getOpcode() == ISD::SELECT_CC) {
9546 if (User->getOperand(0) == PromOps[i])
9547 SelectTruncOp[0].insert(std::make_pair(User,
9548 User->getOperand(0).getValueType()));
9549 if (User->getOperand(1) == PromOps[i])
9550 SelectTruncOp[1].insert(std::make_pair(User,
9551 User->getOperand(1).getValueType()));
9556 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9557 bool ReallyNeedsExt = false;
9558 if (N->getOpcode() != ISD::ANY_EXTEND) {
9559 // If all of the inputs are not already sign/zero extended, then
9560 // we'll still need to do that at the end.
9561 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9562 if (isa<ConstantSDNode>(Inputs[i]))
9566 Inputs[i].getOperand(0).getValueSizeInBits();
9567 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9569 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9570 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9571 APInt::getHighBitsSet(OpBits,
9572 OpBits-PromBits))) ||
9573 (N->getOpcode() == ISD::SIGN_EXTEND &&
9574 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9575 (OpBits-(PromBits-1)))) {
9576 ReallyNeedsExt = true;
9582 // Replace all inputs, either with the truncation operand, or a
9583 // truncation or extension to the final output type.
9584 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9585 // Constant inputs need to be replaced with the to-be-promoted nodes that
9586 // use them because they might have users outside of the cluster of
9588 if (isa<ConstantSDNode>(Inputs[i]))
9591 SDValue InSrc = Inputs[i].getOperand(0);
9592 if (Inputs[i].getValueType() == N->getValueType(0))
9593 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9594 else if (N->getOpcode() == ISD::SIGN_EXTEND)
9595 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9596 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9597 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9598 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9599 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9601 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9602 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9605 // Replace all operations (these are all the same, but have a different
9606 // (promoted) return type). DAG.getNode will validate that the types of
9607 // a binary operator match, so go through the list in reverse so that
9608 // we've likely promoted both operands first.
9609 while (!PromOps.empty()) {
9610 SDValue PromOp = PromOps.back();
9614 switch (PromOp.getOpcode()) {
9615 default: C = 0; break;
9616 case ISD::SELECT: C = 1; break;
9617 case ISD::SELECT_CC: C = 2; break;
9620 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9621 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9622 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9623 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9624 // The to-be-promoted operands of this node have not yet been
9625 // promoted (this should be rare because we're going through the
9626 // list backward, but if one of the operands has several users in
9627 // this cluster of to-be-promoted nodes, it is possible).
9628 PromOps.insert(PromOps.begin(), PromOp);
9632 // For SELECT and SELECT_CC nodes, we do a similar check for any
9633 // to-be-promoted comparison inputs.
9634 if (PromOp.getOpcode() == ISD::SELECT ||
9635 PromOp.getOpcode() == ISD::SELECT_CC) {
9636 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9637 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9638 (SelectTruncOp[1].count(PromOp.getNode()) &&
9639 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9640 PromOps.insert(PromOps.begin(), PromOp);
9645 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9646 PromOp.getNode()->op_end());
9648 // If this node has constant inputs, then they'll need to be promoted here.
9649 for (unsigned i = 0; i < 2; ++i) {
9650 if (!isa<ConstantSDNode>(Ops[C+i]))
9652 if (Ops[C+i].getValueType() == N->getValueType(0))
9655 if (N->getOpcode() == ISD::SIGN_EXTEND)
9656 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9657 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9658 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9660 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9663 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9664 // truncate them again to the original value type.
9665 if (PromOp.getOpcode() == ISD::SELECT ||
9666 PromOp.getOpcode() == ISD::SELECT_CC) {
9667 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9668 if (SI0 != SelectTruncOp[0].end())
9669 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9670 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9671 if (SI1 != SelectTruncOp[1].end())
9672 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9675 DAG.ReplaceAllUsesOfValueWith(PromOp,
9676 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9679 // Now we're left with the initial extension itself.
9680 if (!ReallyNeedsExt)
9681 return N->getOperand(0);
9683 // To zero extend, just mask off everything except for the first bit (in the
9685 if (N->getOpcode() == ISD::ZERO_EXTEND)
9686 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9687 DAG.getConstant(APInt::getLowBitsSet(
9688 N->getValueSizeInBits(0), PromBits),
9689 dl, N->getValueType(0)));
9691 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9692 "Invalid extension type");
9693 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9695 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
9696 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
9697 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9698 N->getOperand(0), ShiftCst), ShiftCst);
9701 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9702 DAGCombinerInfo &DCI) const {
9703 assert((N->getOpcode() == ISD::SINT_TO_FP ||
9704 N->getOpcode() == ISD::UINT_TO_FP) &&
9705 "Need an int -> FP conversion node here");
9707 if (!Subtarget.has64BitSupport())
9710 SelectionDAG &DAG = DCI.DAG;
9714 // Don't handle ppc_fp128 here or i1 conversions.
9715 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9717 if (Op.getOperand(0).getValueType() == MVT::i1)
9720 // For i32 intermediate values, unfortunately, the conversion functions
9721 // leave the upper 32 bits of the value are undefined. Within the set of
9722 // scalar instructions, we have no method for zero- or sign-extending the
9723 // value. Thus, we cannot handle i32 intermediate values here.
9724 if (Op.getOperand(0).getValueType() == MVT::i32)
9727 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9728 "UINT_TO_FP is supported only with FPCVT");
9730 // If we have FCFIDS, then use it when converting to single-precision.
9731 // Otherwise, convert to double-precision and then round.
9732 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9733 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9735 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9737 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9741 // If we're converting from a float, to an int, and back to a float again,
9742 // then we don't need the store/load pair at all.
9743 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9744 Subtarget.hasFPCVT()) ||
9745 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9746 SDValue Src = Op.getOperand(0).getOperand(0);
9747 if (Src.getValueType() == MVT::f32) {
9748 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9749 DCI.AddToWorklist(Src.getNode());
9753 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9756 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9757 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9759 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9760 FP = DAG.getNode(ISD::FP_ROUND, dl,
9761 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
9762 DCI.AddToWorklist(FP.getNode());
9771 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9772 // builtins) into loads with swaps.
9773 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9774 DAGCombinerInfo &DCI) const {
9775 SelectionDAG &DAG = DCI.DAG;
9779 MachineMemOperand *MMO;
9781 switch (N->getOpcode()) {
9783 llvm_unreachable("Unexpected opcode for little endian VSX load");
9785 LoadSDNode *LD = cast<LoadSDNode>(N);
9786 Chain = LD->getChain();
9787 Base = LD->getBasePtr();
9788 MMO = LD->getMemOperand();
9789 // If the MMO suggests this isn't a load of a full vector, leave
9790 // things alone. For a built-in, we have to make the change for
9791 // correctness, so if there is a size problem that will be a bug.
9792 if (MMO->getSize() < 16)
9796 case ISD::INTRINSIC_W_CHAIN: {
9797 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9798 Chain = Intrin->getChain();
9799 Base = Intrin->getBasePtr();
9800 MMO = Intrin->getMemOperand();
9805 MVT VecTy = N->getValueType(0).getSimpleVT();
9806 SDValue LoadOps[] = { Chain, Base };
9807 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9808 DAG.getVTList(VecTy, MVT::Other),
9809 LoadOps, VecTy, MMO);
9810 DCI.AddToWorklist(Load.getNode());
9811 Chain = Load.getValue(1);
9812 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9813 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9814 DCI.AddToWorklist(Swap.getNode());
9818 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9819 // builtins) into stores with swaps.
9820 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9821 DAGCombinerInfo &DCI) const {
9822 SelectionDAG &DAG = DCI.DAG;
9827 MachineMemOperand *MMO;
9829 switch (N->getOpcode()) {
9831 llvm_unreachable("Unexpected opcode for little endian VSX store");
9833 StoreSDNode *ST = cast<StoreSDNode>(N);
9834 Chain = ST->getChain();
9835 Base = ST->getBasePtr();
9836 MMO = ST->getMemOperand();
9838 // If the MMO suggests this isn't a store of a full vector, leave
9839 // things alone. For a built-in, we have to make the change for
9840 // correctness, so if there is a size problem that will be a bug.
9841 if (MMO->getSize() < 16)
9845 case ISD::INTRINSIC_VOID: {
9846 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9847 Chain = Intrin->getChain();
9848 // Intrin->getBasePtr() oddly does not get what we want.
9849 Base = Intrin->getOperand(3);
9850 MMO = Intrin->getMemOperand();
9856 SDValue Src = N->getOperand(SrcOpnd);
9857 MVT VecTy = Src.getValueType().getSimpleVT();
9858 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9859 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9860 DCI.AddToWorklist(Swap.getNode());
9861 Chain = Swap.getValue(1);
9862 SDValue StoreOps[] = { Chain, Swap, Base };
9863 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9864 DAG.getVTList(MVT::Other),
9865 StoreOps, VecTy, MMO);
9866 DCI.AddToWorklist(Store.getNode());
9870 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9871 DAGCombinerInfo &DCI) const {
9872 SelectionDAG &DAG = DCI.DAG;
9874 switch (N->getOpcode()) {
9877 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9878 if (C->isNullValue()) // 0 << V -> 0.
9879 return N->getOperand(0);
9883 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9884 if (C->isNullValue()) // 0 >>u V -> 0.
9885 return N->getOperand(0);
9889 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9890 if (C->isNullValue() || // 0 >>s V -> 0.
9891 C->isAllOnesValue()) // -1 >>s V -> -1.
9892 return N->getOperand(0);
9895 case ISD::SIGN_EXTEND:
9896 case ISD::ZERO_EXTEND:
9897 case ISD::ANY_EXTEND:
9898 return DAGCombineExtBoolTrunc(N, DCI);
9901 case ISD::SELECT_CC:
9902 return DAGCombineTruncBoolExt(N, DCI);
9903 case ISD::SINT_TO_FP:
9904 case ISD::UINT_TO_FP:
9905 return combineFPToIntToFP(N, DCI);
9907 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9908 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9909 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9910 N->getOperand(1).getValueType() == MVT::i32 &&
9911 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9912 SDValue Val = N->getOperand(1).getOperand(0);
9913 if (Val.getValueType() == MVT::f32) {
9914 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9915 DCI.AddToWorklist(Val.getNode());
9917 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9918 DCI.AddToWorklist(Val.getNode());
9921 N->getOperand(0), Val, N->getOperand(2),
9922 DAG.getValueType(N->getOperand(1).getValueType())
9925 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9926 DAG.getVTList(MVT::Other), Ops,
9927 cast<StoreSDNode>(N)->getMemoryVT(),
9928 cast<StoreSDNode>(N)->getMemOperand());
9929 DCI.AddToWorklist(Val.getNode());
9933 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9934 if (cast<StoreSDNode>(N)->isUnindexed() &&
9935 N->getOperand(1).getOpcode() == ISD::BSWAP &&
9936 N->getOperand(1).getNode()->hasOneUse() &&
9937 (N->getOperand(1).getValueType() == MVT::i32 ||
9938 N->getOperand(1).getValueType() == MVT::i16 ||
9939 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9940 N->getOperand(1).getValueType() == MVT::i64))) {
9941 SDValue BSwapOp = N->getOperand(1).getOperand(0);
9942 // Do an any-extend to 32-bits if this is a half-word input.
9943 if (BSwapOp.getValueType() == MVT::i16)
9944 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9947 N->getOperand(0), BSwapOp, N->getOperand(2),
9948 DAG.getValueType(N->getOperand(1).getValueType())
9951 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9952 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9953 cast<StoreSDNode>(N)->getMemOperand());
9956 // For little endian, VSX stores require generating xxswapd/lxvd2x.
9957 EVT VT = N->getOperand(1).getValueType();
9958 if (VT.isSimple()) {
9959 MVT StoreVT = VT.getSimpleVT();
9960 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9961 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9962 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9963 return expandVSXStoreForLE(N, DCI);
9968 LoadSDNode *LD = cast<LoadSDNode>(N);
9969 EVT VT = LD->getValueType(0);
9971 // For little endian, VSX loads require generating lxvd2x/xxswapd.
9972 if (VT.isSimple()) {
9973 MVT LoadVT = VT.getSimpleVT();
9974 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9975 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9976 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9977 return expandVSXLoadForLE(N, DCI);
9980 EVT MemVT = LD->getMemoryVT();
9981 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9982 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9983 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9984 unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9985 if (LD->isUnindexed() && VT.isVector() &&
9986 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9987 // P8 and later hardware should just use LOAD.
9988 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9989 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9990 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9991 LD->getAlignment() >= ScalarABIAlignment)) &&
9992 LD->getAlignment() < ABIAlignment) {
9993 // This is a type-legal unaligned Altivec or QPX load.
9994 SDValue Chain = LD->getChain();
9995 SDValue Ptr = LD->getBasePtr();
9996 bool isLittleEndian = Subtarget.isLittleEndian();
9998 // This implements the loading of unaligned vectors as described in
9999 // the venerable Apple Velocity Engine overview. Specifically:
10000 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10001 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10003 // The general idea is to expand a sequence of one or more unaligned
10004 // loads into an alignment-based permutation-control instruction (lvsl
10005 // or lvsr), a series of regular vector loads (which always truncate
10006 // their input address to an aligned address), and a series of
10007 // permutations. The results of these permutations are the requested
10008 // loaded values. The trick is that the last "extra" load is not taken
10009 // from the address you might suspect (sizeof(vector) bytes after the
10010 // last requested load), but rather sizeof(vector) - 1 bytes after the
10011 // last requested vector. The point of this is to avoid a page fault if
10012 // the base address happened to be aligned. This works because if the
10013 // base address is aligned, then adding less than a full vector length
10014 // will cause the last vector in the sequence to be (re)loaded.
10015 // Otherwise, the next vector will be fetched as you might suspect was
10018 // We might be able to reuse the permutation generation from
10019 // a different base address offset from this one by an aligned amount.
10020 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10021 // optimization later.
10022 Intrinsic::ID Intr, IntrLD, IntrPerm;
10023 MVT PermCntlTy, PermTy, LDTy;
10024 if (Subtarget.hasAltivec()) {
10025 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
10026 Intrinsic::ppc_altivec_lvsl;
10027 IntrLD = Intrinsic::ppc_altivec_lvx;
10028 IntrPerm = Intrinsic::ppc_altivec_vperm;
10029 PermCntlTy = MVT::v16i8;
10030 PermTy = MVT::v4i32;
10033 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10034 Intrinsic::ppc_qpx_qvlpcls;
10035 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10036 Intrinsic::ppc_qpx_qvlfs;
10037 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10038 PermCntlTy = MVT::v4f64;
10039 PermTy = MVT::v4f64;
10040 LDTy = MemVT.getSimpleVT();
10043 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10045 // Create the new MMO for the new base load. It is like the original MMO,
10046 // but represents an area in memory almost twice the vector size centered
10047 // on the original address. If the address is unaligned, we might start
10048 // reading up to (sizeof(vector)-1) bytes below the address of the
10049 // original unaligned load.
10050 MachineFunction &MF = DAG.getMachineFunction();
10051 MachineMemOperand *BaseMMO =
10052 MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
10053 2*MemVT.getStoreSize()-1);
10055 // Create the new base load.
10056 SDValue LDXIntID = DAG.getTargetConstant(IntrLD, dl, getPointerTy());
10057 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10059 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10060 DAG.getVTList(PermTy, MVT::Other),
10061 BaseLoadOps, LDTy, BaseMMO);
10063 // Note that the value of IncOffset (which is provided to the next
10064 // load's pointer info offset value, and thus used to calculate the
10065 // alignment), and the value of IncValue (which is actually used to
10066 // increment the pointer value) are different! This is because we
10067 // require the next load to appear to be aligned, even though it
10068 // is actually offset from the base pointer by a lesser amount.
10069 int IncOffset = VT.getSizeInBits() / 8;
10070 int IncValue = IncOffset;
10072 // Walk (both up and down) the chain looking for another load at the real
10073 // (aligned) offset (the alignment of the other load does not matter in
10074 // this case). If found, then do not use the offset reduction trick, as
10075 // that will prevent the loads from being later combined (as they would
10076 // otherwise be duplicates).
10077 if (!findConsecutiveLoad(LD, DAG))
10080 SDValue Increment = DAG.getConstant(IncValue, dl, getPointerTy());
10081 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10083 MachineMemOperand *ExtraMMO =
10084 MF.getMachineMemOperand(LD->getMemOperand(),
10085 1, 2*MemVT.getStoreSize()-1);
10086 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10087 SDValue ExtraLoad =
10088 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10089 DAG.getVTList(PermTy, MVT::Other),
10090 ExtraLoadOps, LDTy, ExtraMMO);
10092 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10093 BaseLoad.getValue(1), ExtraLoad.getValue(1));
10095 // Because vperm has a big-endian bias, we must reverse the order
10096 // of the input vectors and complement the permute control vector
10097 // when generating little endian code. We have already handled the
10098 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10099 // and ExtraLoad here.
10101 if (isLittleEndian)
10102 Perm = BuildIntrinsicOp(IntrPerm,
10103 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10105 Perm = BuildIntrinsicOp(IntrPerm,
10106 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10109 Perm = Subtarget.hasAltivec() ?
10110 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10111 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10112 DAG.getTargetConstant(1, dl, MVT::i64));
10113 // second argument is 1 because this rounding
10114 // is always exact.
10116 // The output of the permutation is our loaded result, the TokenFactor is
10118 DCI.CombineTo(N, Perm, TF);
10119 return SDValue(N, 0);
10123 case ISD::INTRINSIC_WO_CHAIN: {
10124 bool isLittleEndian = Subtarget.isLittleEndian();
10125 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10126 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10127 : Intrinsic::ppc_altivec_lvsl);
10128 if ((IID == Intr ||
10129 IID == Intrinsic::ppc_qpx_qvlpcld ||
10130 IID == Intrinsic::ppc_qpx_qvlpcls) &&
10131 N->getOperand(1)->getOpcode() == ISD::ADD) {
10132 SDValue Add = N->getOperand(1);
10134 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10135 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10137 if (DAG.MaskedValueIsZero(
10138 Add->getOperand(1),
10139 APInt::getAllOnesValue(Bits /* alignment */)
10141 Add.getValueType().getScalarType().getSizeInBits()))) {
10142 SDNode *BasePtr = Add->getOperand(0).getNode();
10143 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10144 UE = BasePtr->use_end();
10146 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10147 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10148 // We've found another LVSL/LVSR, and this address is an aligned
10149 // multiple of that one. The results will be the same, so use the
10150 // one we've just found instead.
10152 return SDValue(*UI, 0);
10157 if (isa<ConstantSDNode>(Add->getOperand(1))) {
10158 SDNode *BasePtr = Add->getOperand(0).getNode();
10159 for (SDNode::use_iterator UI = BasePtr->use_begin(),
10160 UE = BasePtr->use_end(); UI != UE; ++UI) {
10161 if (UI->getOpcode() == ISD::ADD &&
10162 isa<ConstantSDNode>(UI->getOperand(1)) &&
10163 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10164 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10165 (1ULL << Bits) == 0) {
10166 SDNode *OtherAdd = *UI;
10167 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10168 VE = OtherAdd->use_end(); VI != VE; ++VI) {
10169 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10170 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10171 return SDValue(*VI, 0);
10181 case ISD::INTRINSIC_W_CHAIN: {
10182 // For little endian, VSX loads require generating lxvd2x/xxswapd.
10183 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10184 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10187 case Intrinsic::ppc_vsx_lxvw4x:
10188 case Intrinsic::ppc_vsx_lxvd2x:
10189 return expandVSXLoadForLE(N, DCI);
10194 case ISD::INTRINSIC_VOID: {
10195 // For little endian, VSX stores require generating xxswapd/stxvd2x.
10196 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10197 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10200 case Intrinsic::ppc_vsx_stxvw4x:
10201 case Intrinsic::ppc_vsx_stxvd2x:
10202 return expandVSXStoreForLE(N, DCI);
10208 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10209 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10210 N->getOperand(0).hasOneUse() &&
10211 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10212 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10213 N->getValueType(0) == MVT::i64))) {
10214 SDValue Load = N->getOperand(0);
10215 LoadSDNode *LD = cast<LoadSDNode>(Load);
10216 // Create the byte-swapping load.
10218 LD->getChain(), // Chain
10219 LD->getBasePtr(), // Ptr
10220 DAG.getValueType(N->getValueType(0)) // VT
10223 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10224 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10225 MVT::i64 : MVT::i32, MVT::Other),
10226 Ops, LD->getMemoryVT(), LD->getMemOperand());
10228 // If this is an i16 load, insert the truncate.
10229 SDValue ResVal = BSLoad;
10230 if (N->getValueType(0) == MVT::i16)
10231 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10233 // First, combine the bswap away. This makes the value produced by the
10235 DCI.CombineTo(N, ResVal);
10237 // Next, combine the load away, we give it a bogus result value but a real
10238 // chain result. The result value is dead because the bswap is dead.
10239 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10241 // Return N so it doesn't get rechecked!
10242 return SDValue(N, 0);
10246 case PPCISD::VCMP: {
10247 // If a VCMPo node already exists with exactly the same operands as this
10248 // node, use its result instead of this node (VCMPo computes both a CR6 and
10249 // a normal output).
10251 if (!N->getOperand(0).hasOneUse() &&
10252 !N->getOperand(1).hasOneUse() &&
10253 !N->getOperand(2).hasOneUse()) {
10255 // Scan all of the users of the LHS, looking for VCMPo's that match.
10256 SDNode *VCMPoNode = nullptr;
10258 SDNode *LHSN = N->getOperand(0).getNode();
10259 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10261 if (UI->getOpcode() == PPCISD::VCMPo &&
10262 UI->getOperand(1) == N->getOperand(1) &&
10263 UI->getOperand(2) == N->getOperand(2) &&
10264 UI->getOperand(0) == N->getOperand(0)) {
10269 // If there is no VCMPo node, or if the flag value has a single use, don't
10271 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10274 // Look at the (necessarily single) use of the flag value. If it has a
10275 // chain, this transformation is more complex. Note that multiple things
10276 // could use the value result, which we should ignore.
10277 SDNode *FlagUser = nullptr;
10278 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10279 FlagUser == nullptr; ++UI) {
10280 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10281 SDNode *User = *UI;
10282 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10283 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10290 // If the user is a MFOCRF instruction, we know this is safe.
10291 // Otherwise we give up for right now.
10292 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10293 return SDValue(VCMPoNode, 0);
10297 case ISD::BRCOND: {
10298 SDValue Cond = N->getOperand(1);
10299 SDValue Target = N->getOperand(2);
10301 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10302 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10303 Intrinsic::ppc_is_decremented_ctr_nonzero) {
10305 // We now need to make the intrinsic dead (it cannot be instruction
10307 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10308 assert(Cond.getNode()->hasOneUse() &&
10309 "Counter decrement has more than one use");
10311 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10312 N->getOperand(0), Target);
10317 // If this is a branch on an altivec predicate comparison, lower this so
10318 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
10319 // lowering is done pre-legalize, because the legalizer lowers the predicate
10320 // compare down to code that is difficult to reassemble.
10321 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10322 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10324 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10325 // value. If so, pass-through the AND to get to the intrinsic.
10326 if (LHS.getOpcode() == ISD::AND &&
10327 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10328 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10329 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10330 isa<ConstantSDNode>(LHS.getOperand(1)) &&
10331 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10333 LHS = LHS.getOperand(0);
10335 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10336 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10337 Intrinsic::ppc_is_decremented_ctr_nonzero &&
10338 isa<ConstantSDNode>(RHS)) {
10339 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10340 "Counter decrement comparison is not EQ or NE");
10342 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10343 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10344 (CC == ISD::SETNE && !Val);
10346 // We now need to make the intrinsic dead (it cannot be instruction
10348 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10349 assert(LHS.getNode()->hasOneUse() &&
10350 "Counter decrement has more than one use");
10352 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10353 N->getOperand(0), N->getOperand(4));
10359 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10360 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10361 getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10362 assert(isDot && "Can't compare against a vector result!");
10364 // If this is a comparison against something other than 0/1, then we know
10365 // that the condition is never/always true.
10366 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10367 if (Val != 0 && Val != 1) {
10368 if (CC == ISD::SETEQ) // Cond never true, remove branch.
10369 return N->getOperand(0);
10370 // Always !=, turn it into an unconditional branch.
10371 return DAG.getNode(ISD::BR, dl, MVT::Other,
10372 N->getOperand(0), N->getOperand(4));
10375 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10377 // Create the PPCISD altivec 'dot' comparison node.
10379 LHS.getOperand(2), // LHS of compare
10380 LHS.getOperand(3), // RHS of compare
10381 DAG.getConstant(CompareOpc, dl, MVT::i32)
10383 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10384 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10386 // Unpack the result based on how the target uses it.
10387 PPC::Predicate CompOpc;
10388 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10389 default: // Can't happen, don't crash on invalid number though.
10390 case 0: // Branch on the value of the EQ bit of CR6.
10391 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10393 case 1: // Branch on the inverted value of the EQ bit of CR6.
10394 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10396 case 2: // Branch on the value of the LT bit of CR6.
10397 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10399 case 3: // Branch on the inverted value of the LT bit of CR6.
10400 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10404 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10405 DAG.getConstant(CompOpc, dl, MVT::i32),
10406 DAG.getRegister(PPC::CR6, MVT::i32),
10407 N->getOperand(4), CompNode.getValue(1));
10417 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10419 std::vector<SDNode *> *Created) const {
10420 // fold (sdiv X, pow2)
10421 EVT VT = N->getValueType(0);
10422 if (VT == MVT::i64 && !Subtarget.isPPC64())
10424 if ((VT != MVT::i32 && VT != MVT::i64) ||
10425 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10429 SDValue N0 = N->getOperand(0);
10431 bool IsNegPow2 = (-Divisor).isPowerOf2();
10432 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10433 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
10435 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10437 Created->push_back(Op.getNode());
10440 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10442 Created->push_back(Op.getNode());
10448 //===----------------------------------------------------------------------===//
10449 // Inline Assembly Support
10450 //===----------------------------------------------------------------------===//
10452 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10455 const SelectionDAG &DAG,
10456 unsigned Depth) const {
10457 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10458 switch (Op.getOpcode()) {
10460 case PPCISD::LBRX: {
10461 // lhbrx is known to have the top bits cleared out.
10462 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10463 KnownZero = 0xFFFF0000;
10466 case ISD::INTRINSIC_WO_CHAIN: {
10467 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10469 case Intrinsic::ppc_altivec_vcmpbfp_p:
10470 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10471 case Intrinsic::ppc_altivec_vcmpequb_p:
10472 case Intrinsic::ppc_altivec_vcmpequh_p:
10473 case Intrinsic::ppc_altivec_vcmpequw_p:
10474 case Intrinsic::ppc_altivec_vcmpequd_p:
10475 case Intrinsic::ppc_altivec_vcmpgefp_p:
10476 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10477 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10478 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10479 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10480 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10481 case Intrinsic::ppc_altivec_vcmpgtub_p:
10482 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10483 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10484 case Intrinsic::ppc_altivec_vcmpgtud_p:
10485 KnownZero = ~1U; // All bits but the low one are known to be zero.
10492 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10493 switch (Subtarget.getDarwinDirective()) {
10496 case PPC::DIR_PWR4:
10497 case PPC::DIR_PWR5:
10498 case PPC::DIR_PWR5X:
10499 case PPC::DIR_PWR6:
10500 case PPC::DIR_PWR6X:
10501 case PPC::DIR_PWR7:
10502 case PPC::DIR_PWR8: {
10506 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10508 // For small loops (between 5 and 8 instructions), align to a 32-byte
10509 // boundary so that the entire loop fits in one instruction-cache line.
10510 uint64_t LoopSize = 0;
10511 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10512 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10513 LoopSize += TII->GetInstSizeInBytes(J);
10515 if (LoopSize > 16 && LoopSize <= 32)
10522 return TargetLowering::getPrefLoopAlignment(ML);
10525 /// getConstraintType - Given a constraint, return the type of
10526 /// constraint it is for this target.
10527 PPCTargetLowering::ConstraintType
10528 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10529 if (Constraint.size() == 1) {
10530 switch (Constraint[0]) {
10537 return C_RegisterClass;
10539 // FIXME: While Z does indicate a memory constraint, it specifically
10540 // indicates an r+r address (used in conjunction with the 'y' modifier
10541 // in the replacement string). Currently, we're forcing the base
10542 // register to be r0 in the asm printer (which is interpreted as zero)
10543 // and forming the complete address in the second register. This is
10547 } else if (Constraint == "wc") { // individual CR bits.
10548 return C_RegisterClass;
10549 } else if (Constraint == "wa" || Constraint == "wd" ||
10550 Constraint == "wf" || Constraint == "ws") {
10551 return C_RegisterClass; // VSX registers.
10553 return TargetLowering::getConstraintType(Constraint);
10556 /// Examine constraint type and operand type and determine a weight value.
10557 /// This object must already have been set up with the operand type
10558 /// and the current alternative constraint selected.
10559 TargetLowering::ConstraintWeight
10560 PPCTargetLowering::getSingleConstraintMatchWeight(
10561 AsmOperandInfo &info, const char *constraint) const {
10562 ConstraintWeight weight = CW_Invalid;
10563 Value *CallOperandVal = info.CallOperandVal;
10564 // If we don't have a value, we can't do a match,
10565 // but allow it at the lowest weight.
10566 if (!CallOperandVal)
10568 Type *type = CallOperandVal->getType();
10570 // Look at the constraint type.
10571 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10572 return CW_Register; // an individual CR bit.
10573 else if ((StringRef(constraint) == "wa" ||
10574 StringRef(constraint) == "wd" ||
10575 StringRef(constraint) == "wf") &&
10576 type->isVectorTy())
10577 return CW_Register;
10578 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10579 return CW_Register;
10581 switch (*constraint) {
10583 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10586 if (type->isIntegerTy())
10587 weight = CW_Register;
10590 if (type->isFloatTy())
10591 weight = CW_Register;
10594 if (type->isDoubleTy())
10595 weight = CW_Register;
10598 if (type->isVectorTy())
10599 weight = CW_Register;
10602 weight = CW_Register;
10605 weight = CW_Memory;
10611 std::pair<unsigned, const TargetRegisterClass *>
10612 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10613 const std::string &Constraint,
10615 if (Constraint.size() == 1) {
10616 // GCC RS6000 Constraint Letters
10617 switch (Constraint[0]) {
10618 case 'b': // R1-R31
10619 if (VT == MVT::i64 && Subtarget.isPPC64())
10620 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10621 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10622 case 'r': // R0-R31
10623 if (VT == MVT::i64 && Subtarget.isPPC64())
10624 return std::make_pair(0U, &PPC::G8RCRegClass);
10625 return std::make_pair(0U, &PPC::GPRCRegClass);
10627 if (VT == MVT::f32 || VT == MVT::i32)
10628 return std::make_pair(0U, &PPC::F4RCRegClass);
10629 if (VT == MVT::f64 || VT == MVT::i64)
10630 return std::make_pair(0U, &PPC::F8RCRegClass);
10631 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10632 return std::make_pair(0U, &PPC::QFRCRegClass);
10633 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10634 return std::make_pair(0U, &PPC::QSRCRegClass);
10637 if (VT == MVT::v4f64 && Subtarget.hasQPX())
10638 return std::make_pair(0U, &PPC::QFRCRegClass);
10639 if (VT == MVT::v4f32 && Subtarget.hasQPX())
10640 return std::make_pair(0U, &PPC::QSRCRegClass);
10641 return std::make_pair(0U, &PPC::VRRCRegClass);
10643 return std::make_pair(0U, &PPC::CRRCRegClass);
10645 } else if (Constraint == "wc") { // an individual CR bit.
10646 return std::make_pair(0U, &PPC::CRBITRCRegClass);
10647 } else if (Constraint == "wa" || Constraint == "wd" ||
10648 Constraint == "wf") {
10649 return std::make_pair(0U, &PPC::VSRCRegClass);
10650 } else if (Constraint == "ws") {
10651 return std::make_pair(0U, &PPC::VSFRCRegClass);
10654 std::pair<unsigned, const TargetRegisterClass *> R =
10655 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10657 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10658 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10659 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10661 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10662 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10663 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10664 PPC::GPRCRegClass.contains(R.first))
10665 return std::make_pair(TRI->getMatchingSuperReg(R.first,
10666 PPC::sub_32, &PPC::G8RCRegClass),
10667 &PPC::G8RCRegClass);
10669 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10670 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10671 R.first = PPC::CR0;
10672 R.second = &PPC::CRRCRegClass;
10679 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10680 /// vector. If it is invalid, don't add anything to Ops.
10681 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10682 std::string &Constraint,
10683 std::vector<SDValue>&Ops,
10684 SelectionDAG &DAG) const {
10687 // Only support length 1 constraints.
10688 if (Constraint.length() > 1) return;
10690 char Letter = Constraint[0];
10701 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10702 if (!CST) return; // Must be an immediate to match.
10704 int64_t Value = CST->getSExtValue();
10705 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10706 // numbers are printed as such.
10708 default: llvm_unreachable("Unknown constraint letter!");
10709 case 'I': // "I" is a signed 16-bit constant.
10710 if (isInt<16>(Value))
10711 Result = DAG.getTargetConstant(Value, dl, TCVT);
10713 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
10714 if (isShiftedUInt<16, 16>(Value))
10715 Result = DAG.getTargetConstant(Value, dl, TCVT);
10717 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
10718 if (isShiftedInt<16, 16>(Value))
10719 Result = DAG.getTargetConstant(Value, dl, TCVT);
10721 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
10722 if (isUInt<16>(Value))
10723 Result = DAG.getTargetConstant(Value, dl, TCVT);
10725 case 'M': // "M" is a constant that is greater than 31.
10727 Result = DAG.getTargetConstant(Value, dl, TCVT);
10729 case 'N': // "N" is a positive constant that is an exact power of two.
10730 if (Value > 0 && isPowerOf2_64(Value))
10731 Result = DAG.getTargetConstant(Value, dl, TCVT);
10733 case 'O': // "O" is the constant zero.
10735 Result = DAG.getTargetConstant(Value, dl, TCVT);
10737 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
10738 if (isInt<16>(-Value))
10739 Result = DAG.getTargetConstant(Value, dl, TCVT);
10746 if (Result.getNode()) {
10747 Ops.push_back(Result);
10751 // Handle standard constraint letters.
10752 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10755 // isLegalAddressingMode - Return true if the addressing mode represented
10756 // by AM is legal for this target, for a load/store of the specified type.
10757 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10759 // PPC does not allow r+i addressing modes for vectors!
10760 if (Ty->isVectorTy() && AM.BaseOffs != 0)
10763 // PPC allows a sign-extended 16-bit immediate field.
10764 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10767 // No global is ever allowed as a base.
10771 // PPC only support r+r,
10772 switch (AM.Scale) {
10773 case 0: // "r+i" or just "i", depending on HasBaseReg.
10776 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
10778 // Otherwise we have r+r or r+i.
10781 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
10783 // Allow 2*r as r+r.
10786 // No other scales are supported.
10793 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10794 SelectionDAG &DAG) const {
10795 MachineFunction &MF = DAG.getMachineFunction();
10796 MachineFrameInfo *MFI = MF.getFrameInfo();
10797 MFI->setReturnAddressIsTaken(true);
10799 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10803 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10805 // Make sure the function does not optimize away the store of the RA to
10807 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10808 FuncInfo->setLRStoreRequired();
10809 bool isPPC64 = Subtarget.isPPC64();
10812 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10814 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
10815 isPPC64 ? MVT::i64 : MVT::i32);
10816 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10817 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10818 FrameAddr, Offset),
10819 MachinePointerInfo(), false, false, false, 0);
10822 // Just load the return address off the stack.
10823 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10824 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10825 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10828 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10829 SelectionDAG &DAG) const {
10831 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10833 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10834 bool isPPC64 = PtrVT == MVT::i64;
10836 MachineFunction &MF = DAG.getMachineFunction();
10837 MachineFrameInfo *MFI = MF.getFrameInfo();
10838 MFI->setFrameAddressIsTaken(true);
10840 // Naked functions never have a frame pointer, and so we use r1. For all
10841 // other functions, this decision must be delayed until during PEI.
10843 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10844 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10846 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10848 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10851 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10852 FrameAddr, MachinePointerInfo(), false, false,
10857 // FIXME? Maybe this could be a TableGen attribute on some registers and
10858 // this table could be generated automatically from RegInfo.
10859 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10861 bool isPPC64 = Subtarget.isPPC64();
10862 bool isDarwinABI = Subtarget.isDarwinABI();
10864 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10865 (!isPPC64 && VT != MVT::i32))
10866 report_fatal_error("Invalid register global variable type");
10868 bool is64Bit = isPPC64 && VT == MVT::i64;
10869 unsigned Reg = StringSwitch<unsigned>(RegName)
10870 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10871 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10872 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10873 (is64Bit ? PPC::X13 : PPC::R13))
10878 report_fatal_error("Invalid register name global variable");
10882 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10883 // The PowerPC target isn't yet aware of offsets.
10887 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10889 unsigned Intrinsic) const {
10891 switch (Intrinsic) {
10892 case Intrinsic::ppc_qpx_qvlfd:
10893 case Intrinsic::ppc_qpx_qvlfs:
10894 case Intrinsic::ppc_qpx_qvlfcd:
10895 case Intrinsic::ppc_qpx_qvlfcs:
10896 case Intrinsic::ppc_qpx_qvlfiwa:
10897 case Intrinsic::ppc_qpx_qvlfiwz:
10898 case Intrinsic::ppc_altivec_lvx:
10899 case Intrinsic::ppc_altivec_lvxl:
10900 case Intrinsic::ppc_altivec_lvebx:
10901 case Intrinsic::ppc_altivec_lvehx:
10902 case Intrinsic::ppc_altivec_lvewx:
10903 case Intrinsic::ppc_vsx_lxvd2x:
10904 case Intrinsic::ppc_vsx_lxvw4x: {
10906 switch (Intrinsic) {
10907 case Intrinsic::ppc_altivec_lvebx:
10910 case Intrinsic::ppc_altivec_lvehx:
10913 case Intrinsic::ppc_altivec_lvewx:
10916 case Intrinsic::ppc_vsx_lxvd2x:
10919 case Intrinsic::ppc_qpx_qvlfd:
10922 case Intrinsic::ppc_qpx_qvlfs:
10925 case Intrinsic::ppc_qpx_qvlfcd:
10928 case Intrinsic::ppc_qpx_qvlfcs:
10936 Info.opc = ISD::INTRINSIC_W_CHAIN;
10938 Info.ptrVal = I.getArgOperand(0);
10939 Info.offset = -VT.getStoreSize()+1;
10940 Info.size = 2*VT.getStoreSize()-1;
10943 Info.readMem = true;
10944 Info.writeMem = false;
10947 case Intrinsic::ppc_qpx_qvlfda:
10948 case Intrinsic::ppc_qpx_qvlfsa:
10949 case Intrinsic::ppc_qpx_qvlfcda:
10950 case Intrinsic::ppc_qpx_qvlfcsa:
10951 case Intrinsic::ppc_qpx_qvlfiwaa:
10952 case Intrinsic::ppc_qpx_qvlfiwza: {
10954 switch (Intrinsic) {
10955 case Intrinsic::ppc_qpx_qvlfda:
10958 case Intrinsic::ppc_qpx_qvlfsa:
10961 case Intrinsic::ppc_qpx_qvlfcda:
10964 case Intrinsic::ppc_qpx_qvlfcsa:
10972 Info.opc = ISD::INTRINSIC_W_CHAIN;
10974 Info.ptrVal = I.getArgOperand(0);
10976 Info.size = VT.getStoreSize();
10979 Info.readMem = true;
10980 Info.writeMem = false;
10983 case Intrinsic::ppc_qpx_qvstfd:
10984 case Intrinsic::ppc_qpx_qvstfs:
10985 case Intrinsic::ppc_qpx_qvstfcd:
10986 case Intrinsic::ppc_qpx_qvstfcs:
10987 case Intrinsic::ppc_qpx_qvstfiw:
10988 case Intrinsic::ppc_altivec_stvx:
10989 case Intrinsic::ppc_altivec_stvxl:
10990 case Intrinsic::ppc_altivec_stvebx:
10991 case Intrinsic::ppc_altivec_stvehx:
10992 case Intrinsic::ppc_altivec_stvewx:
10993 case Intrinsic::ppc_vsx_stxvd2x:
10994 case Intrinsic::ppc_vsx_stxvw4x: {
10996 switch (Intrinsic) {
10997 case Intrinsic::ppc_altivec_stvebx:
11000 case Intrinsic::ppc_altivec_stvehx:
11003 case Intrinsic::ppc_altivec_stvewx:
11006 case Intrinsic::ppc_vsx_stxvd2x:
11009 case Intrinsic::ppc_qpx_qvstfd:
11012 case Intrinsic::ppc_qpx_qvstfs:
11015 case Intrinsic::ppc_qpx_qvstfcd:
11018 case Intrinsic::ppc_qpx_qvstfcs:
11026 Info.opc = ISD::INTRINSIC_VOID;
11028 Info.ptrVal = I.getArgOperand(1);
11029 Info.offset = -VT.getStoreSize()+1;
11030 Info.size = 2*VT.getStoreSize()-1;
11033 Info.readMem = false;
11034 Info.writeMem = true;
11037 case Intrinsic::ppc_qpx_qvstfda:
11038 case Intrinsic::ppc_qpx_qvstfsa:
11039 case Intrinsic::ppc_qpx_qvstfcda:
11040 case Intrinsic::ppc_qpx_qvstfcsa:
11041 case Intrinsic::ppc_qpx_qvstfiwa: {
11043 switch (Intrinsic) {
11044 case Intrinsic::ppc_qpx_qvstfda:
11047 case Intrinsic::ppc_qpx_qvstfsa:
11050 case Intrinsic::ppc_qpx_qvstfcda:
11053 case Intrinsic::ppc_qpx_qvstfcsa:
11061 Info.opc = ISD::INTRINSIC_VOID;
11063 Info.ptrVal = I.getArgOperand(1);
11065 Info.size = VT.getStoreSize();
11068 Info.readMem = false;
11069 Info.writeMem = true;
11079 /// getOptimalMemOpType - Returns the target specific optimal type for load
11080 /// and store operations as a result of memset, memcpy, and memmove
11081 /// lowering. If DstAlign is zero that means it's safe to destination
11082 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11083 /// means there isn't a need to check it against alignment requirement,
11084 /// probably because the source does not need to be loaded. If 'IsMemset' is
11085 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11086 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11087 /// source is constant so it does not need to be loaded.
11088 /// It returns EVT::Other if the type should be determined using generic
11089 /// target-independent logic.
11090 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11091 unsigned DstAlign, unsigned SrcAlign,
11092 bool IsMemset, bool ZeroMemset,
11094 MachineFunction &MF) const {
11095 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11096 const Function *F = MF.getFunction();
11097 // When expanding a memset, require at least two QPX instructions to cover
11098 // the cost of loading the value to be stored from the constant pool.
11099 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11100 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11101 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11105 // We should use Altivec/VSX loads and stores when available. For unaligned
11106 // addresses, unaligned VSX loads are only fast starting with the P8.
11107 if (Subtarget.hasAltivec() && Size >= 16 &&
11108 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11109 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11113 if (Subtarget.isPPC64()) {
11120 /// \brief Returns true if it is beneficial to convert a load of a constant
11121 /// to just the constant itself.
11122 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11124 assert(Ty->isIntegerTy());
11126 unsigned BitSize = Ty->getPrimitiveSizeInBits();
11127 if (BitSize == 0 || BitSize > 64)
11132 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11133 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11135 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11136 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11137 return NumBits1 == 64 && NumBits2 == 32;
11140 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11141 if (!VT1.isInteger() || !VT2.isInteger())
11143 unsigned NumBits1 = VT1.getSizeInBits();
11144 unsigned NumBits2 = VT2.getSizeInBits();
11145 return NumBits1 == 64 && NumBits2 == 32;
11148 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11149 // Generally speaking, zexts are not free, but they are free when they can be
11150 // folded with other operations.
11151 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11152 EVT MemVT = LD->getMemoryVT();
11153 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11154 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11155 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11156 LD->getExtensionType() == ISD::ZEXTLOAD))
11160 // FIXME: Add other cases...
11161 // - 32-bit shifts with a zext to i64
11162 // - zext after ctlz, bswap, etc.
11163 // - zext after and by a constant mask
11165 return TargetLowering::isZExtFree(Val, VT2);
11168 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11169 assert(VT.isFloatingPoint());
11173 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11174 return isInt<16>(Imm) || isUInt<16>(Imm);
11177 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11178 return isInt<16>(Imm) || isUInt<16>(Imm);
11181 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11184 bool *Fast) const {
11185 if (DisablePPCUnaligned)
11188 // PowerPC supports unaligned memory access for simple non-vector types.
11189 // Although accessing unaligned addresses is not as efficient as accessing
11190 // aligned addresses, it is generally more efficient than manual expansion,
11191 // and generally only traps for software emulation when crossing page
11194 if (!VT.isSimple())
11197 if (VT.getSimpleVT().isVector()) {
11198 if (Subtarget.hasVSX()) {
11199 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11200 VT != MVT::v4f32 && VT != MVT::v4i32)
11207 if (VT == MVT::ppcf128)
11216 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11217 VT = VT.getScalarType();
11219 if (!VT.isSimple())
11222 switch (VT.getSimpleVT().SimpleTy) {
11234 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11235 // LR is a callee-save register, but we must treat it as clobbered by any call
11236 // site. Hence we include LR in the scratch registers, which are in turn added
11237 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11238 // to CTR, which is used by any indirect call.
11239 static const MCPhysReg ScratchRegs[] = {
11240 PPC::X12, PPC::LR8, PPC::CTR8, 0
11243 return ScratchRegs;
11247 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11248 EVT VT , unsigned DefinedValues) const {
11249 if (VT == MVT::v2i64)
11252 if (Subtarget.hasQPX()) {
11253 if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11257 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11260 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11261 if (DisableILPPref || Subtarget.enableMachineScheduler())
11262 return TargetLowering::getSchedulingPreference(N);
11267 // Create a fast isel object.
11269 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11270 const TargetLibraryInfo *LibInfo) const {
11271 return PPC::createFastISel(FuncInfo, LibInfo);