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 "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
42 // FIXME: Remove this once soft-float is supported.
43 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
44 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
46 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
47 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
49 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
50 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
52 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
53 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
55 // FIXME: Remove this once the bug has been fixed!
56 extern cl::opt<bool> ANDIGlueBug;
58 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM)
60 Subtarget(*TM.getSubtargetImpl()) {
63 // Use _setjmp/_longjmp instead of setjmp/longjmp.
64 setUseUnderscoreSetJmp(true);
65 setUseUnderscoreLongJmp(true);
67 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68 // arguments are at least 4/8 bytes aligned.
69 bool isPPC64 = Subtarget.isPPC64();
70 setMinStackArgumentAlignment(isPPC64 ? 8:4);
72 // Set up the register classes.
73 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
77 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
79 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
81 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
83 // PowerPC has pre-inc load and store's.
84 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
85 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
86 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
89 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
90 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
91 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
92 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
95 if (Subtarget.useCRBits()) {
96 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
98 if (isPPC64 || Subtarget.hasFPCVT()) {
99 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
100 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
101 isPPC64 ? MVT::i64 : MVT::i32);
102 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
103 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
104 isPPC64 ? MVT::i64 : MVT::i32);
106 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
107 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
110 // PowerPC does not support direct load / store of condition registers
111 setOperationAction(ISD::LOAD, MVT::i1, Custom);
112 setOperationAction(ISD::STORE, MVT::i1, Custom);
114 // FIXME: Remove this once the ANDI glue bug is fixed:
116 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
118 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
119 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
120 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
121 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
122 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
123 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
125 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
128 // This is used in the ppcf128->int sequence. Note it has different semantics
129 // from FP_ROUND: that rounds to nearest, this rounds to zero.
130 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
132 // We do not currently implement these libm ops for PowerPC.
133 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
134 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
135 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
136 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
137 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
138 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
140 // PowerPC has no SREM/UREM instructions
141 setOperationAction(ISD::SREM, MVT::i32, Expand);
142 setOperationAction(ISD::UREM, MVT::i32, Expand);
143 setOperationAction(ISD::SREM, MVT::i64, Expand);
144 setOperationAction(ISD::UREM, MVT::i64, Expand);
146 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
147 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
148 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
149 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
150 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
151 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
152 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
153 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
154 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
156 // We don't support sin/cos/sqrt/fmod/pow
157 setOperationAction(ISD::FSIN , MVT::f64, Expand);
158 setOperationAction(ISD::FCOS , MVT::f64, Expand);
159 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
160 setOperationAction(ISD::FREM , MVT::f64, Expand);
161 setOperationAction(ISD::FPOW , MVT::f64, Expand);
162 setOperationAction(ISD::FMA , MVT::f64, Legal);
163 setOperationAction(ISD::FSIN , MVT::f32, Expand);
164 setOperationAction(ISD::FCOS , MVT::f32, Expand);
165 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
166 setOperationAction(ISD::FREM , MVT::f32, Expand);
167 setOperationAction(ISD::FPOW , MVT::f32, Expand);
168 setOperationAction(ISD::FMA , MVT::f32, Legal);
170 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
172 // If we're enabling GP optimizations, use hardware square root
173 if (!Subtarget.hasFSQRT() &&
174 !(TM.Options.UnsafeFPMath &&
175 Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
176 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
178 if (!Subtarget.hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath &&
180 Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
181 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
183 if (Subtarget.hasFCPSGN()) {
184 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
185 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
187 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
191 if (Subtarget.hasFPRND()) {
192 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
193 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
194 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
195 setOperationAction(ISD::FROUND, MVT::f64, Legal);
197 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
200 setOperationAction(ISD::FROUND, MVT::f32, Legal);
203 // PowerPC does not have BSWAP, CTPOP or CTTZ
204 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
205 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
206 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
207 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
208 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
209 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
210 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
211 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
213 if (Subtarget.hasPOPCNTD()) {
214 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
215 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
217 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
218 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
221 // PowerPC does not have ROTR
222 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
223 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
225 if (!Subtarget.useCRBits()) {
226 // PowerPC does not have Select
227 setOperationAction(ISD::SELECT, MVT::i32, Expand);
228 setOperationAction(ISD::SELECT, MVT::i64, Expand);
229 setOperationAction(ISD::SELECT, MVT::f32, Expand);
230 setOperationAction(ISD::SELECT, MVT::f64, Expand);
233 // PowerPC wants to turn select_cc of FP into fsel when possible.
234 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
235 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
237 // PowerPC wants to optimize integer setcc a bit
238 if (!Subtarget.useCRBits())
239 setOperationAction(ISD::SETCC, MVT::i32, Custom);
241 // PowerPC does not have BRCOND which requires SetCC
242 if (!Subtarget.useCRBits())
243 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
245 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
247 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
248 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
250 // PowerPC does not have [U|S]INT_TO_FP
251 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
252 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
254 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
255 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
256 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
257 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
259 // We cannot sextinreg(i1). Expand to shifts.
260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
262 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
263 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
264 // support continuation, user-level threading, and etc.. As a result, no
265 // other SjLj exception interfaces are implemented and please don't build
266 // your own exception handling based on them.
267 // LLVM/Clang supports zero-cost DWARF exception handling.
268 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
269 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
271 // We want to legalize GlobalAddress and ConstantPool nodes into the
272 // appropriate instructions to materialize the address.
273 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
274 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
275 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
276 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
277 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
278 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
285 setOperationAction(ISD::TRAP, MVT::Other, Legal);
287 // TRAMPOLINE is custom lowered.
288 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
289 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
291 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
292 setOperationAction(ISD::VASTART , MVT::Other, Custom);
294 if (Subtarget.isSVR4ABI()) {
296 // VAARG always uses double-word chunks, so promote anything smaller.
297 setOperationAction(ISD::VAARG, MVT::i1, Promote);
298 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
299 setOperationAction(ISD::VAARG, MVT::i8, Promote);
300 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
301 setOperationAction(ISD::VAARG, MVT::i16, Promote);
302 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
303 setOperationAction(ISD::VAARG, MVT::i32, Promote);
304 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
305 setOperationAction(ISD::VAARG, MVT::Other, Expand);
307 // VAARG is custom lowered with the 32-bit SVR4 ABI.
308 setOperationAction(ISD::VAARG, MVT::Other, Custom);
309 setOperationAction(ISD::VAARG, MVT::i64, Custom);
312 setOperationAction(ISD::VAARG, MVT::Other, Expand);
314 if (Subtarget.isSVR4ABI() && !isPPC64)
315 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
316 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
318 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
320 // Use the default implementation.
321 setOperationAction(ISD::VAEND , MVT::Other, Expand);
322 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
323 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
324 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
325 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
327 // We want to custom lower some of our intrinsics.
328 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
330 // To handle counter-based loop conditions.
331 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
333 // Comparisons that require checking two conditions.
334 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
335 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
336 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
337 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
338 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
339 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
340 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
341 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
342 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
343 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
344 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
345 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
347 if (Subtarget.has64BitSupport()) {
348 // They also have instructions for converting between i64 and fp.
349 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
350 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
351 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
352 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
353 // This is just the low 32 bits of a (signed) fp->i64 conversion.
354 // We cannot do this with Promote because i64 is not a legal type.
355 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
357 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
358 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
360 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
361 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
364 // With the instructions enabled under FPCVT, we can do everything.
365 if (Subtarget.hasFPCVT()) {
366 if (Subtarget.has64BitSupport()) {
367 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
368 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
369 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
370 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
374 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
375 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
376 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
379 if (Subtarget.use64BitRegs()) {
380 // 64-bit PowerPC implementations can support i64 types directly
381 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
382 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
383 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
384 // 64-bit PowerPC wants to expand i128 shifts itself.
385 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
386 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
387 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
389 // 32-bit PowerPC wants to expand i64 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
395 if (Subtarget.hasAltivec()) {
396 // First set operation action for all vector types to expand. Then we
397 // will selectively turn on ones that can be effectively codegen'd.
398 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
399 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
400 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
402 // add/sub are legal for all supported vector VT's.
403 setOperationAction(ISD::ADD , VT, Legal);
404 setOperationAction(ISD::SUB , VT, Legal);
406 // We promote all shuffles to v16i8.
407 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
408 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
410 // We promote all non-typed operations to v4i32.
411 setOperationAction(ISD::AND , VT, Promote);
412 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
413 setOperationAction(ISD::OR , VT, Promote);
414 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
415 setOperationAction(ISD::XOR , VT, Promote);
416 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
417 setOperationAction(ISD::LOAD , VT, Promote);
418 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
419 setOperationAction(ISD::SELECT, VT, Promote);
420 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
421 setOperationAction(ISD::STORE, VT, Promote);
422 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
424 // No other operations are legal.
425 setOperationAction(ISD::MUL , VT, Expand);
426 setOperationAction(ISD::SDIV, VT, Expand);
427 setOperationAction(ISD::SREM, VT, Expand);
428 setOperationAction(ISD::UDIV, VT, Expand);
429 setOperationAction(ISD::UREM, VT, Expand);
430 setOperationAction(ISD::FDIV, VT, Expand);
431 setOperationAction(ISD::FREM, VT, Expand);
432 setOperationAction(ISD::FNEG, VT, Expand);
433 setOperationAction(ISD::FSQRT, VT, Expand);
434 setOperationAction(ISD::FLOG, VT, Expand);
435 setOperationAction(ISD::FLOG10, VT, Expand);
436 setOperationAction(ISD::FLOG2, VT, Expand);
437 setOperationAction(ISD::FEXP, VT, Expand);
438 setOperationAction(ISD::FEXP2, VT, Expand);
439 setOperationAction(ISD::FSIN, VT, Expand);
440 setOperationAction(ISD::FCOS, VT, Expand);
441 setOperationAction(ISD::FABS, VT, Expand);
442 setOperationAction(ISD::FPOWI, VT, Expand);
443 setOperationAction(ISD::FFLOOR, VT, Expand);
444 setOperationAction(ISD::FCEIL, VT, Expand);
445 setOperationAction(ISD::FTRUNC, VT, Expand);
446 setOperationAction(ISD::FRINT, VT, Expand);
447 setOperationAction(ISD::FNEARBYINT, VT, Expand);
448 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
449 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
450 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
451 setOperationAction(ISD::MULHU, VT, Expand);
452 setOperationAction(ISD::MULHS, VT, Expand);
453 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
454 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
455 setOperationAction(ISD::UDIVREM, VT, Expand);
456 setOperationAction(ISD::SDIVREM, VT, Expand);
457 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
458 setOperationAction(ISD::FPOW, VT, Expand);
459 setOperationAction(ISD::BSWAP, VT, Expand);
460 setOperationAction(ISD::CTPOP, VT, Expand);
461 setOperationAction(ISD::CTLZ, VT, Expand);
462 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
463 setOperationAction(ISD::CTTZ, VT, Expand);
464 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
465 setOperationAction(ISD::VSELECT, VT, Expand);
466 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
468 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
469 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
470 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
471 setTruncStoreAction(VT, InnerVT, Expand);
473 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
474 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
475 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
478 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
479 // with merges, splats, etc.
480 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
482 setOperationAction(ISD::AND , MVT::v4i32, Legal);
483 setOperationAction(ISD::OR , MVT::v4i32, Legal);
484 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
485 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
486 setOperationAction(ISD::SELECT, MVT::v4i32,
487 Subtarget.useCRBits() ? Legal : Expand);
488 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
489 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
490 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
491 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
492 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
493 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
494 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
495 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
496 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
498 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
499 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
500 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
501 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
503 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
504 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
506 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
507 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
508 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
511 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
512 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
513 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
515 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
516 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
518 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
519 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
520 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
521 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
523 // Altivec does not contain unordered floating-point compare instructions
524 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
525 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
526 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
527 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
529 if (Subtarget.hasVSX()) {
530 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
531 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
533 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
534 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
535 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
536 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
537 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
539 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
541 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
542 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
544 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
545 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
547 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
548 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
549 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
550 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
551 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
553 // Share the Altivec comparison restrictions.
554 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
555 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
556 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
557 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
559 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
560 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
562 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
564 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
566 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
567 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
569 // VSX v2i64 only supports non-arithmetic operations.
570 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
571 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
573 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
574 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
575 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
577 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
579 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
580 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
581 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
582 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
584 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
586 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
587 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
588 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
589 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
591 // Vector operation legalization checks the result type of
592 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
593 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
594 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
595 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
596 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
598 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
602 if (Subtarget.has64BitSupport()) {
603 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
604 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
606 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
610 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
611 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
614 setBooleanContents(ZeroOrOneBooleanContent);
615 // Altivec instructions set fields to all zeros or all ones.
616 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
619 // These libcalls are not available in 32-bit.
620 setLibcallName(RTLIB::SHL_I128, nullptr);
621 setLibcallName(RTLIB::SRL_I128, nullptr);
622 setLibcallName(RTLIB::SRA_I128, nullptr);
626 setStackPointerRegisterToSaveRestore(PPC::X1);
627 setExceptionPointerRegister(PPC::X3);
628 setExceptionSelectorRegister(PPC::X4);
630 setStackPointerRegisterToSaveRestore(PPC::R1);
631 setExceptionPointerRegister(PPC::R3);
632 setExceptionSelectorRegister(PPC::R4);
635 // We have target-specific dag combine patterns for the following nodes:
636 setTargetDAGCombine(ISD::SINT_TO_FP);
637 setTargetDAGCombine(ISD::LOAD);
638 setTargetDAGCombine(ISD::STORE);
639 setTargetDAGCombine(ISD::BR_CC);
640 if (Subtarget.useCRBits())
641 setTargetDAGCombine(ISD::BRCOND);
642 setTargetDAGCombine(ISD::BSWAP);
643 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
645 setTargetDAGCombine(ISD::SIGN_EXTEND);
646 setTargetDAGCombine(ISD::ZERO_EXTEND);
647 setTargetDAGCombine(ISD::ANY_EXTEND);
649 if (Subtarget.useCRBits()) {
650 setTargetDAGCombine(ISD::TRUNCATE);
651 setTargetDAGCombine(ISD::SETCC);
652 setTargetDAGCombine(ISD::SELECT_CC);
655 // Use reciprocal estimates.
656 if (TM.Options.UnsafeFPMath) {
657 setTargetDAGCombine(ISD::FDIV);
658 setTargetDAGCombine(ISD::FSQRT);
661 // Darwin long double math library functions have $LDBL128 appended.
662 if (Subtarget.isDarwin()) {
663 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
664 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
665 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
666 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
667 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
668 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
669 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
670 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
671 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
672 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
675 // With 32 condition bits, we don't need to sink (and duplicate) compares
676 // aggressively in CodeGenPrep.
677 if (Subtarget.useCRBits())
678 setHasMultipleConditionRegisters();
680 setMinFunctionAlignment(2);
681 if (Subtarget.isDarwin())
682 setPrefFunctionAlignment(4);
684 setInsertFencesForAtomic(true);
686 if (Subtarget.enableMachineScheduler())
687 setSchedulingPreference(Sched::Source);
689 setSchedulingPreference(Sched::Hybrid);
691 computeRegisterProperties();
693 // The Freescale cores does better with aggressive inlining of memcpy and
694 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
695 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
696 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
697 MaxStoresPerMemset = 32;
698 MaxStoresPerMemsetOptSize = 16;
699 MaxStoresPerMemcpy = 32;
700 MaxStoresPerMemcpyOptSize = 8;
701 MaxStoresPerMemmove = 32;
702 MaxStoresPerMemmoveOptSize = 8;
704 setPrefFunctionAlignment(4);
708 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
709 /// the desired ByVal argument alignment.
710 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
711 unsigned MaxMaxAlign) {
712 if (MaxAlign == MaxMaxAlign)
714 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
715 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
717 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
719 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
720 unsigned EltAlign = 0;
721 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
722 if (EltAlign > MaxAlign)
724 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
725 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
726 unsigned EltAlign = 0;
727 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
728 if (EltAlign > MaxAlign)
730 if (MaxAlign == MaxMaxAlign)
736 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
737 /// function arguments in the caller parameter area.
738 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
739 // Darwin passes everything on 4 byte boundary.
740 if (Subtarget.isDarwin())
743 // 16byte and wider vectors are passed on 16byte boundary.
744 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
745 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
746 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
747 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
751 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
753 default: return nullptr;
754 case PPCISD::FSEL: return "PPCISD::FSEL";
755 case PPCISD::FCFID: return "PPCISD::FCFID";
756 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
757 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
758 case PPCISD::FRE: return "PPCISD::FRE";
759 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
760 case PPCISD::STFIWX: return "PPCISD::STFIWX";
761 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
762 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
763 case PPCISD::VPERM: return "PPCISD::VPERM";
764 case PPCISD::Hi: return "PPCISD::Hi";
765 case PPCISD::Lo: return "PPCISD::Lo";
766 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
767 case PPCISD::LOAD: return "PPCISD::LOAD";
768 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
769 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
770 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
771 case PPCISD::SRL: return "PPCISD::SRL";
772 case PPCISD::SRA: return "PPCISD::SRA";
773 case PPCISD::SHL: return "PPCISD::SHL";
774 case PPCISD::CALL: return "PPCISD::CALL";
775 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
776 case PPCISD::CALL_TLS: return "PPCISD::CALL_TLS";
777 case PPCISD::CALL_NOP_TLS: return "PPCISD::CALL_NOP_TLS";
778 case PPCISD::MTCTR: return "PPCISD::MTCTR";
779 case PPCISD::BCTRL: return "PPCISD::BCTRL";
780 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
781 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
782 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
783 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
784 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
785 case PPCISD::VCMP: return "PPCISD::VCMP";
786 case PPCISD::VCMPo: return "PPCISD::VCMPo";
787 case PPCISD::LBRX: return "PPCISD::LBRX";
788 case PPCISD::STBRX: return "PPCISD::STBRX";
789 case PPCISD::LARX: return "PPCISD::LARX";
790 case PPCISD::STCX: return "PPCISD::STCX";
791 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
792 case PPCISD::BDNZ: return "PPCISD::BDNZ";
793 case PPCISD::BDZ: return "PPCISD::BDZ";
794 case PPCISD::MFFS: return "PPCISD::MFFS";
795 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
796 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
797 case PPCISD::CR6SET: return "PPCISD::CR6SET";
798 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
799 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
800 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
801 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
802 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
803 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
804 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
805 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
806 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
807 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
808 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
809 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
810 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
811 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
812 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
813 case PPCISD::SC: return "PPCISD::SC";
817 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
819 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
820 return VT.changeVectorElementTypeToInteger();
823 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
824 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
828 //===----------------------------------------------------------------------===//
829 // Node matching predicates, for use by the tblgen matching code.
830 //===----------------------------------------------------------------------===//
832 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
833 static bool isFloatingPointZero(SDValue Op) {
834 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
835 return CFP->getValueAPF().isZero();
836 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
837 // Maybe this has already been legalized into the constant pool?
838 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
839 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
840 return CFP->getValueAPF().isZero();
845 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
846 /// true if Op is undef or if it matches the specified value.
847 static bool isConstantOrUndef(int Op, int Val) {
848 return Op < 0 || Op == Val;
851 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
852 /// VPKUHUM instruction.
853 /// The ShuffleKind distinguishes between big-endian operations with
854 /// two different inputs (0), either-endian operations with two identical
855 /// inputs (1), and little-endian operantion with two different inputs (2).
856 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
857 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
859 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
860 if (ShuffleKind == 0) {
863 for (unsigned i = 0; i != 16; ++i)
864 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
866 } else if (ShuffleKind == 2) {
869 for (unsigned i = 0; i != 16; ++i)
870 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
872 } else if (ShuffleKind == 1) {
873 unsigned j = IsLE ? 0 : 1;
874 for (unsigned i = 0; i != 8; ++i)
875 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
876 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
882 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
883 /// VPKUWUM instruction.
884 /// The ShuffleKind distinguishes between big-endian operations with
885 /// two different inputs (0), either-endian operations with two identical
886 /// inputs (1), and little-endian operantion with two different inputs (2).
887 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
888 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
890 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
891 if (ShuffleKind == 0) {
894 for (unsigned i = 0; i != 16; i += 2)
895 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
896 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
898 } else if (ShuffleKind == 2) {
901 for (unsigned i = 0; i != 16; i += 2)
902 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
903 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
905 } else if (ShuffleKind == 1) {
906 unsigned j = IsLE ? 0 : 2;
907 for (unsigned i = 0; i != 8; i += 2)
908 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
909 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
910 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
911 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
917 /// isVMerge - Common function, used to match vmrg* shuffles.
919 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
920 unsigned LHSStart, unsigned RHSStart) {
921 if (N->getValueType(0) != MVT::v16i8)
923 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
924 "Unsupported merge size!");
926 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
927 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
928 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
929 LHSStart+j+i*UnitSize) ||
930 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
931 RHSStart+j+i*UnitSize))
937 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
938 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
939 /// The ShuffleKind distinguishes between big-endian merges with two
940 /// different inputs (0), either-endian merges with two identical inputs (1),
941 /// and little-endian merges with two different inputs (2). For the latter,
942 /// the input operands are swapped (see PPCInstrAltivec.td).
943 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
944 unsigned ShuffleKind, SelectionDAG &DAG) {
945 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
946 if (ShuffleKind == 1) // unary
947 return isVMerge(N, UnitSize, 0, 0);
948 else if (ShuffleKind == 2) // swapped
949 return isVMerge(N, UnitSize, 0, 16);
953 if (ShuffleKind == 1) // unary
954 return isVMerge(N, UnitSize, 8, 8);
955 else if (ShuffleKind == 0) // normal
956 return isVMerge(N, UnitSize, 8, 24);
962 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
963 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
964 /// The ShuffleKind distinguishes between big-endian merges with two
965 /// different inputs (0), either-endian merges with two identical inputs (1),
966 /// and little-endian merges with two different inputs (2). For the latter,
967 /// the input operands are swapped (see PPCInstrAltivec.td).
968 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
969 unsigned ShuffleKind, SelectionDAG &DAG) {
970 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
971 if (ShuffleKind == 1) // unary
972 return isVMerge(N, UnitSize, 8, 8);
973 else if (ShuffleKind == 2) // swapped
974 return isVMerge(N, UnitSize, 8, 24);
978 if (ShuffleKind == 1) // unary
979 return isVMerge(N, UnitSize, 0, 0);
980 else if (ShuffleKind == 0) // normal
981 return isVMerge(N, UnitSize, 0, 16);
988 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
989 /// amount, otherwise return -1.
990 /// The ShuffleKind distinguishes between big-endian operations with two
991 /// different inputs (0), either-endian operations with two identical inputs
992 /// (1), and little-endian operations with two different inputs (2). For the
993 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
994 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
996 if (N->getValueType(0) != MVT::v16i8)
999 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1001 // Find the first non-undef value in the shuffle mask.
1003 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1006 if (i == 16) return -1; // all undef.
1008 // Otherwise, check to see if the rest of the elements are consecutively
1009 // numbered from this value.
1010 unsigned ShiftAmt = SVOp->getMaskElt(i);
1011 if (ShiftAmt < i) return -1;
1014 bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1017 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1018 // Check the rest of the elements to see if they are consecutive.
1019 for (++i; i != 16; ++i)
1020 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1022 } else if (ShuffleKind == 1) {
1023 // Check the rest of the elements to see if they are consecutive.
1024 for (++i; i != 16; ++i)
1025 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1030 if (ShuffleKind == 2 && isLE)
1031 ShiftAmt = 16 - ShiftAmt;
1036 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1037 /// specifies a splat of a single element that is suitable for input to
1038 /// VSPLTB/VSPLTH/VSPLTW.
1039 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1040 assert(N->getValueType(0) == MVT::v16i8 &&
1041 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1043 // This is a splat operation if each element of the permute is the same, and
1044 // if the value doesn't reference the second vector.
1045 unsigned ElementBase = N->getMaskElt(0);
1047 // FIXME: Handle UNDEF elements too!
1048 if (ElementBase >= 16)
1051 // Check that the indices are consecutive, in the case of a multi-byte element
1052 // splatted with a v16i8 mask.
1053 for (unsigned i = 1; i != EltSize; ++i)
1054 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1057 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1058 if (N->getMaskElt(i) < 0) continue;
1059 for (unsigned j = 0; j != EltSize; ++j)
1060 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1066 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1068 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1069 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1071 APInt APVal, APUndef;
1075 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1076 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1077 return CFP->getValueAPF().isNegZero();
1082 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1083 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1084 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1085 SelectionDAG &DAG) {
1086 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1087 assert(isSplatShuffleMask(SVOp, EltSize));
1088 if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1089 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1091 return SVOp->getMaskElt(0) / EltSize;
1094 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1095 /// by using a vspltis[bhw] instruction of the specified element size, return
1096 /// the constant being splatted. The ByteSize field indicates the number of
1097 /// bytes of each element [124] -> [bhw].
1098 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1099 SDValue OpVal(nullptr, 0);
1101 // If ByteSize of the splat is bigger than the element size of the
1102 // build_vector, then we have a case where we are checking for a splat where
1103 // multiple elements of the buildvector are folded together into a single
1104 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1105 unsigned EltSize = 16/N->getNumOperands();
1106 if (EltSize < ByteSize) {
1107 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1108 SDValue UniquedVals[4];
1109 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1111 // See if all of the elements in the buildvector agree across.
1112 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1113 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1114 // If the element isn't a constant, bail fully out.
1115 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1118 if (!UniquedVals[i&(Multiple-1)].getNode())
1119 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1120 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1121 return SDValue(); // no match.
1124 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1125 // either constant or undef values that are identical for each chunk. See
1126 // if these chunks can form into a larger vspltis*.
1128 // Check to see if all of the leading entries are either 0 or -1. If
1129 // neither, then this won't fit into the immediate field.
1130 bool LeadingZero = true;
1131 bool LeadingOnes = true;
1132 for (unsigned i = 0; i != Multiple-1; ++i) {
1133 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1135 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1136 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1138 // Finally, check the least significant entry.
1140 if (!UniquedVals[Multiple-1].getNode())
1141 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1142 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1144 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1147 if (!UniquedVals[Multiple-1].getNode())
1148 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1149 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1150 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1151 return DAG.getTargetConstant(Val, MVT::i32);
1157 // Check to see if this buildvec has a single non-undef value in its elements.
1158 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1159 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1160 if (!OpVal.getNode())
1161 OpVal = N->getOperand(i);
1162 else if (OpVal != N->getOperand(i))
1166 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1168 unsigned ValSizeInBytes = EltSize;
1170 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1171 Value = CN->getZExtValue();
1172 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1173 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1174 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1177 // If the splat value is larger than the element value, then we can never do
1178 // this splat. The only case that we could fit the replicated bits into our
1179 // immediate field for would be zero, and we prefer to use vxor for it.
1180 if (ValSizeInBytes < ByteSize) return SDValue();
1182 // If the element value is larger than the splat value, cut it in half and
1183 // check to see if the two halves are equal. Continue doing this until we
1184 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1185 while (ValSizeInBytes > ByteSize) {
1186 ValSizeInBytes >>= 1;
1188 // If the top half equals the bottom half, we're still ok.
1189 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1190 (Value & ((1 << (8*ValSizeInBytes))-1)))
1194 // Properly sign extend the value.
1195 int MaskVal = SignExtend32(Value, ByteSize * 8);
1197 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1198 if (MaskVal == 0) return SDValue();
1200 // Finally, if this value fits in a 5 bit sext field, return it
1201 if (SignExtend32<5>(MaskVal) == MaskVal)
1202 return DAG.getTargetConstant(MaskVal, MVT::i32);
1206 //===----------------------------------------------------------------------===//
1207 // Addressing Mode Selection
1208 //===----------------------------------------------------------------------===//
1210 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1211 /// or 64-bit immediate, and if the value can be accurately represented as a
1212 /// sign extension from a 16-bit value. If so, this returns true and the
1214 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1215 if (!isa<ConstantSDNode>(N))
1218 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1219 if (N->getValueType(0) == MVT::i32)
1220 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1222 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1224 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1225 return isIntS16Immediate(Op.getNode(), Imm);
1229 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1230 /// can be represented as an indexed [r+r] operation. Returns false if it
1231 /// can be more efficiently represented with [r+imm].
1232 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1234 SelectionDAG &DAG) const {
1236 if (N.getOpcode() == ISD::ADD) {
1237 if (isIntS16Immediate(N.getOperand(1), imm))
1238 return false; // r+i
1239 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1240 return false; // r+i
1242 Base = N.getOperand(0);
1243 Index = N.getOperand(1);
1245 } else if (N.getOpcode() == ISD::OR) {
1246 if (isIntS16Immediate(N.getOperand(1), imm))
1247 return false; // r+i can fold it if we can.
1249 // If this is an or of disjoint bitfields, we can codegen this as an add
1250 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1252 APInt LHSKnownZero, LHSKnownOne;
1253 APInt RHSKnownZero, RHSKnownOne;
1254 DAG.computeKnownBits(N.getOperand(0),
1255 LHSKnownZero, LHSKnownOne);
1257 if (LHSKnownZero.getBoolValue()) {
1258 DAG.computeKnownBits(N.getOperand(1),
1259 RHSKnownZero, RHSKnownOne);
1260 // If all of the bits are known zero on the LHS or RHS, the add won't
1262 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1263 Base = N.getOperand(0);
1264 Index = N.getOperand(1);
1273 // If we happen to be doing an i64 load or store into a stack slot that has
1274 // less than a 4-byte alignment, then the frame-index elimination may need to
1275 // use an indexed load or store instruction (because the offset may not be a
1276 // multiple of 4). The extra register needed to hold the offset comes from the
1277 // register scavenger, and it is possible that the scavenger will need to use
1278 // an emergency spill slot. As a result, we need to make sure that a spill slot
1279 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1281 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1282 // FIXME: This does not handle the LWA case.
1286 // NOTE: We'll exclude negative FIs here, which come from argument
1287 // lowering, because there are no known test cases triggering this problem
1288 // using packed structures (or similar). We can remove this exclusion if
1289 // we find such a test case. The reason why this is so test-case driven is
1290 // because this entire 'fixup' is only to prevent crashes (from the
1291 // register scavenger) on not-really-valid inputs. For example, if we have:
1293 // %b = bitcast i1* %a to i64*
1294 // store i64* a, i64 b
1295 // then the store should really be marked as 'align 1', but is not. If it
1296 // were marked as 'align 1' then the indexed form would have been
1297 // instruction-selected initially, and the problem this 'fixup' is preventing
1298 // won't happen regardless.
1302 MachineFunction &MF = DAG.getMachineFunction();
1303 MachineFrameInfo *MFI = MF.getFrameInfo();
1305 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1309 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1310 FuncInfo->setHasNonRISpills();
1313 /// Returns true if the address N can be represented by a base register plus
1314 /// a signed 16-bit displacement [r+imm], and if it is not better
1315 /// represented as reg+reg. If Aligned is true, only accept displacements
1316 /// suitable for STD and friends, i.e. multiples of 4.
1317 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1320 bool Aligned) const {
1321 // FIXME dl should come from parent load or store, not from address
1323 // If this can be more profitably realized as r+r, fail.
1324 if (SelectAddressRegReg(N, Disp, Base, DAG))
1327 if (N.getOpcode() == ISD::ADD) {
1329 if (isIntS16Immediate(N.getOperand(1), imm) &&
1330 (!Aligned || (imm & 3) == 0)) {
1331 Disp = DAG.getTargetConstant(imm, N.getValueType());
1332 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1333 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1334 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1336 Base = N.getOperand(0);
1338 return true; // [r+i]
1339 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1340 // Match LOAD (ADD (X, Lo(G))).
1341 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1342 && "Cannot handle constant offsets yet!");
1343 Disp = N.getOperand(1).getOperand(0); // The global address.
1344 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1345 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1346 Disp.getOpcode() == ISD::TargetConstantPool ||
1347 Disp.getOpcode() == ISD::TargetJumpTable);
1348 Base = N.getOperand(0);
1349 return true; // [&g+r]
1351 } else if (N.getOpcode() == ISD::OR) {
1353 if (isIntS16Immediate(N.getOperand(1), imm) &&
1354 (!Aligned || (imm & 3) == 0)) {
1355 // If this is an or of disjoint bitfields, we can codegen this as an add
1356 // (for better address arithmetic) if the LHS and RHS of the OR are
1357 // provably disjoint.
1358 APInt LHSKnownZero, LHSKnownOne;
1359 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1361 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1362 // If all of the bits are known zero on the LHS or RHS, the add won't
1364 if (FrameIndexSDNode *FI =
1365 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1366 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1367 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1369 Base = N.getOperand(0);
1371 Disp = DAG.getTargetConstant(imm, N.getValueType());
1375 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1376 // Loading from a constant address.
1378 // If this address fits entirely in a 16-bit sext immediate field, codegen
1381 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1382 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1383 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1384 CN->getValueType(0));
1388 // Handle 32-bit sext immediates with LIS + addr mode.
1389 if ((CN->getValueType(0) == MVT::i32 ||
1390 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1391 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1392 int Addr = (int)CN->getZExtValue();
1394 // Otherwise, break this down into an LIS + disp.
1395 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1397 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1398 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1399 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1404 Disp = DAG.getTargetConstant(0, getPointerTy());
1405 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1406 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1407 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1410 return true; // [r+0]
1413 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1414 /// represented as an indexed [r+r] operation.
1415 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1417 SelectionDAG &DAG) const {
1418 // Check to see if we can easily represent this as an [r+r] address. This
1419 // will fail if it thinks that the address is more profitably represented as
1420 // reg+imm, e.g. where imm = 0.
1421 if (SelectAddressRegReg(N, Base, Index, DAG))
1424 // If the operand is an addition, always emit this as [r+r], since this is
1425 // better (for code size, and execution, as the memop does the add for free)
1426 // than emitting an explicit add.
1427 if (N.getOpcode() == ISD::ADD) {
1428 Base = N.getOperand(0);
1429 Index = N.getOperand(1);
1433 // Otherwise, do it the hard way, using R0 as the base register.
1434 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1440 /// getPreIndexedAddressParts - returns true by value, base pointer and
1441 /// offset pointer and addressing mode by reference if the node's address
1442 /// can be legally represented as pre-indexed load / store address.
1443 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1445 ISD::MemIndexedMode &AM,
1446 SelectionDAG &DAG) const {
1447 if (DisablePPCPreinc) return false;
1453 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1454 Ptr = LD->getBasePtr();
1455 VT = LD->getMemoryVT();
1456 Alignment = LD->getAlignment();
1457 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1458 Ptr = ST->getBasePtr();
1459 VT = ST->getMemoryVT();
1460 Alignment = ST->getAlignment();
1465 // PowerPC doesn't have preinc load/store instructions for vectors.
1469 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1471 // Common code will reject creating a pre-inc form if the base pointer
1472 // is a frame index, or if N is a store and the base pointer is either
1473 // the same as or a predecessor of the value being stored. Check for
1474 // those situations here, and try with swapped Base/Offset instead.
1477 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1480 SDValue Val = cast<StoreSDNode>(N)->getValue();
1481 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1486 std::swap(Base, Offset);
1492 // LDU/STU can only handle immediates that are a multiple of 4.
1493 if (VT != MVT::i64) {
1494 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1497 // LDU/STU need an address with at least 4-byte alignment.
1501 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1505 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1506 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1507 // sext i32 to i64 when addr mode is r+i.
1508 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1509 LD->getExtensionType() == ISD::SEXTLOAD &&
1510 isa<ConstantSDNode>(Offset))
1518 //===----------------------------------------------------------------------===//
1519 // LowerOperation implementation
1520 //===----------------------------------------------------------------------===//
1522 /// GetLabelAccessInfo - Return true if we should reference labels using a
1523 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1524 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1525 unsigned &LoOpFlags,
1526 const GlobalValue *GV = nullptr) {
1527 HiOpFlags = PPCII::MO_HA;
1528 LoOpFlags = PPCII::MO_LO;
1530 // Don't use the pic base if not in PIC relocation model.
1531 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1534 HiOpFlags |= PPCII::MO_PIC_FLAG;
1535 LoOpFlags |= PPCII::MO_PIC_FLAG;
1538 // If this is a reference to a global value that requires a non-lazy-ptr, make
1539 // sure that instruction lowering adds it.
1540 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1541 HiOpFlags |= PPCII::MO_NLP_FLAG;
1542 LoOpFlags |= PPCII::MO_NLP_FLAG;
1544 if (GV->hasHiddenVisibility()) {
1545 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1546 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1553 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1554 SelectionDAG &DAG) {
1555 EVT PtrVT = HiPart.getValueType();
1556 SDValue Zero = DAG.getConstant(0, PtrVT);
1559 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1560 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1562 // With PIC, the first instruction is actually "GR+hi(&G)".
1564 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1565 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1567 // Generate non-pic code that has direct accesses to the constant pool.
1568 // The address of the global is just (hi(&g)+lo(&g)).
1569 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1572 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1573 SelectionDAG &DAG) const {
1574 EVT PtrVT = Op.getValueType();
1575 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1576 const Constant *C = CP->getConstVal();
1578 // 64-bit SVR4 ABI code is always position-independent.
1579 // The actual address of the GlobalValue is stored in the TOC.
1580 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1581 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1582 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1583 DAG.getRegister(PPC::X2, MVT::i64));
1586 unsigned MOHiFlag, MOLoFlag;
1587 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1589 if (isPIC && Subtarget.isSVR4ABI()) {
1590 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1591 PPCII::MO_PIC_FLAG);
1593 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1594 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1598 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1600 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1601 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1604 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1605 EVT PtrVT = Op.getValueType();
1606 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1608 // 64-bit SVR4 ABI code is always position-independent.
1609 // The actual address of the GlobalValue is stored in the TOC.
1610 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1611 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1612 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1613 DAG.getRegister(PPC::X2, MVT::i64));
1616 unsigned MOHiFlag, MOLoFlag;
1617 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1619 if (isPIC && Subtarget.isSVR4ABI()) {
1620 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1621 PPCII::MO_PIC_FLAG);
1623 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1624 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1627 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1628 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1629 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1632 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1633 SelectionDAG &DAG) const {
1634 EVT PtrVT = Op.getValueType();
1635 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1636 const BlockAddress *BA = BASDN->getBlockAddress();
1638 // 64-bit SVR4 ABI code is always position-independent.
1639 // The actual BlockAddress is stored in the TOC.
1640 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1641 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1642 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1643 DAG.getRegister(PPC::X2, MVT::i64));
1646 unsigned MOHiFlag, MOLoFlag;
1647 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1648 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1649 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1650 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1653 // Generate a call to __tls_get_addr for the given GOT entry Op.
1654 std::pair<SDValue,SDValue>
1655 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1656 SelectionDAG &DAG) const {
1658 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1659 TargetLowering::ArgListTy Args;
1660 TargetLowering::ArgListEntry Entry;
1662 Entry.Ty = IntPtrTy;
1663 Args.push_back(Entry);
1665 TargetLowering::CallLoweringInfo CLI(DAG);
1666 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1667 .setCallee(CallingConv::C, IntPtrTy,
1668 DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1669 std::move(Args), 0);
1671 return LowerCallTo(CLI);
1674 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1675 SelectionDAG &DAG) const {
1677 // FIXME: TLS addresses currently use medium model code sequences,
1678 // which is the most useful form. Eventually support for small and
1679 // large models could be added if users need it, at the cost of
1680 // additional complexity.
1681 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1683 const GlobalValue *GV = GA->getGlobal();
1684 EVT PtrVT = getPointerTy();
1685 bool is64bit = Subtarget.isPPC64();
1686 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1687 PICLevel::Level picLevel = M->getPICLevel();
1689 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1691 if (Model == TLSModel::LocalExec) {
1692 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1693 PPCII::MO_TPREL_HA);
1694 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1695 PPCII::MO_TPREL_LO);
1696 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1697 is64bit ? MVT::i64 : MVT::i32);
1698 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1699 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1702 if (Model == TLSModel::InitialExec) {
1703 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1704 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1708 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1709 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1710 PtrVT, GOTReg, TGA);
1712 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1713 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1714 PtrVT, TGA, GOTPtr);
1715 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1718 if (Model == TLSModel::GeneralDynamic) {
1719 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1723 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1724 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1727 if (picLevel == PICLevel::Small)
1728 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1730 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1732 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1734 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1735 return CallResult.first;
1738 if (Model == TLSModel::LocalDynamic) {
1739 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1743 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1744 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1747 if (picLevel == PICLevel::Small)
1748 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1750 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1752 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1754 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1755 SDValue TLSAddr = CallResult.first;
1756 SDValue Chain = CallResult.second;
1757 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1758 Chain, TLSAddr, TGA);
1759 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1762 llvm_unreachable("Unknown TLS model!");
1765 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1766 SelectionDAG &DAG) const {
1767 EVT PtrVT = Op.getValueType();
1768 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1770 const GlobalValue *GV = GSDN->getGlobal();
1772 // 64-bit SVR4 ABI code is always position-independent.
1773 // The actual address of the GlobalValue is stored in the TOC.
1774 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1775 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1776 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1777 DAG.getRegister(PPC::X2, MVT::i64));
1780 unsigned MOHiFlag, MOLoFlag;
1781 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1783 if (isPIC && Subtarget.isSVR4ABI()) {
1784 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1786 PPCII::MO_PIC_FLAG);
1787 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1788 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1792 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1794 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1796 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1798 // If the global reference is actually to a non-lazy-pointer, we have to do an
1799 // extra load to get the address of the global.
1800 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1801 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1802 false, false, false, 0);
1806 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1807 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1810 if (Op.getValueType() == MVT::v2i64) {
1811 // When the operands themselves are v2i64 values, we need to do something
1812 // special because VSX has no underlying comparison operations for these.
1813 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1814 // Equality can be handled by casting to the legal type for Altivec
1815 // comparisons, everything else needs to be expanded.
1816 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1817 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1818 DAG.getSetCC(dl, MVT::v4i32,
1819 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1820 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1827 // We handle most of these in the usual way.
1831 // If we're comparing for equality to zero, expose the fact that this is
1832 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1833 // fold the new nodes.
1834 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1835 if (C->isNullValue() && CC == ISD::SETEQ) {
1836 EVT VT = Op.getOperand(0).getValueType();
1837 SDValue Zext = Op.getOperand(0);
1838 if (VT.bitsLT(MVT::i32)) {
1840 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1842 unsigned Log2b = Log2_32(VT.getSizeInBits());
1843 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1844 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1845 DAG.getConstant(Log2b, MVT::i32));
1846 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1848 // Leave comparisons against 0 and -1 alone for now, since they're usually
1849 // optimized. FIXME: revisit this when we can custom lower all setcc
1851 if (C->isAllOnesValue() || C->isNullValue())
1855 // If we have an integer seteq/setne, turn it into a compare against zero
1856 // by xor'ing the rhs with the lhs, which is faster than setting a
1857 // condition register, reading it back out, and masking the correct bit. The
1858 // normal approach here uses sub to do this instead of xor. Using xor exposes
1859 // the result to other bit-twiddling opportunities.
1860 EVT LHSVT = Op.getOperand(0).getValueType();
1861 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1862 EVT VT = Op.getValueType();
1863 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1865 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1870 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1871 const PPCSubtarget &Subtarget) const {
1872 SDNode *Node = Op.getNode();
1873 EVT VT = Node->getValueType(0);
1874 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1875 SDValue InChain = Node->getOperand(0);
1876 SDValue VAListPtr = Node->getOperand(1);
1877 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1880 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1883 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1884 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1885 false, false, false, 0);
1886 InChain = GprIndex.getValue(1);
1888 if (VT == MVT::i64) {
1889 // Check if GprIndex is even
1890 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1891 DAG.getConstant(1, MVT::i32));
1892 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1893 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1894 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1895 DAG.getConstant(1, MVT::i32));
1896 // Align GprIndex to be even if it isn't
1897 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1901 // fpr index is 1 byte after gpr
1902 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1903 DAG.getConstant(1, MVT::i32));
1906 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1907 FprPtr, MachinePointerInfo(SV), MVT::i8,
1908 false, false, false, 0);
1909 InChain = FprIndex.getValue(1);
1911 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1912 DAG.getConstant(8, MVT::i32));
1914 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1915 DAG.getConstant(4, MVT::i32));
1918 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1919 MachinePointerInfo(), false, false,
1921 InChain = OverflowArea.getValue(1);
1923 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1924 MachinePointerInfo(), false, false,
1926 InChain = RegSaveArea.getValue(1);
1928 // select overflow_area if index > 8
1929 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1930 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1932 // adjustment constant gpr_index * 4/8
1933 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1934 VT.isInteger() ? GprIndex : FprIndex,
1935 DAG.getConstant(VT.isInteger() ? 4 : 8,
1938 // OurReg = RegSaveArea + RegConstant
1939 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1942 // Floating types are 32 bytes into RegSaveArea
1943 if (VT.isFloatingPoint())
1944 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1945 DAG.getConstant(32, MVT::i32));
1947 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1948 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1949 VT.isInteger() ? GprIndex : FprIndex,
1950 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1953 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1954 VT.isInteger() ? VAListPtr : FprPtr,
1955 MachinePointerInfo(SV),
1956 MVT::i8, false, false, 0);
1958 // determine if we should load from reg_save_area or overflow_area
1959 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1961 // increase overflow_area by 4/8 if gpr/fpr > 8
1962 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1963 DAG.getConstant(VT.isInteger() ? 4 : 8,
1966 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1969 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1971 MachinePointerInfo(),
1972 MVT::i32, false, false, 0);
1974 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1975 false, false, false, 0);
1978 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1979 const PPCSubtarget &Subtarget) const {
1980 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1982 // We have to copy the entire va_list struct:
1983 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1984 return DAG.getMemcpy(Op.getOperand(0), Op,
1985 Op.getOperand(1), Op.getOperand(2),
1986 DAG.getConstant(12, MVT::i32), 8, false, true,
1987 MachinePointerInfo(), MachinePointerInfo());
1990 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1991 SelectionDAG &DAG) const {
1992 return Op.getOperand(0);
1995 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1996 SelectionDAG &DAG) const {
1997 SDValue Chain = Op.getOperand(0);
1998 SDValue Trmp = Op.getOperand(1); // trampoline
1999 SDValue FPtr = Op.getOperand(2); // nested function
2000 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2003 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2004 bool isPPC64 = (PtrVT == MVT::i64);
2006 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2009 TargetLowering::ArgListTy Args;
2010 TargetLowering::ArgListEntry Entry;
2012 Entry.Ty = IntPtrTy;
2013 Entry.Node = Trmp; Args.push_back(Entry);
2015 // TrampSize == (isPPC64 ? 48 : 40);
2016 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2017 isPPC64 ? MVT::i64 : MVT::i32);
2018 Args.push_back(Entry);
2020 Entry.Node = FPtr; Args.push_back(Entry);
2021 Entry.Node = Nest; Args.push_back(Entry);
2023 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2024 TargetLowering::CallLoweringInfo CLI(DAG);
2025 CLI.setDebugLoc(dl).setChain(Chain)
2026 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2027 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2028 std::move(Args), 0);
2030 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2031 return CallResult.second;
2034 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2035 const PPCSubtarget &Subtarget) const {
2036 MachineFunction &MF = DAG.getMachineFunction();
2037 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2041 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2042 // vastart just stores the address of the VarArgsFrameIndex slot into the
2043 // memory location argument.
2044 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2045 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2046 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2047 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2048 MachinePointerInfo(SV),
2052 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2053 // We suppose the given va_list is already allocated.
2056 // char gpr; /* index into the array of 8 GPRs
2057 // * stored in the register save area
2058 // * gpr=0 corresponds to r3,
2059 // * gpr=1 to r4, etc.
2061 // char fpr; /* index into the array of 8 FPRs
2062 // * stored in the register save area
2063 // * fpr=0 corresponds to f1,
2064 // * fpr=1 to f2, etc.
2066 // char *overflow_arg_area;
2067 // /* location on stack that holds
2068 // * the next overflow argument
2070 // char *reg_save_area;
2071 // /* where r3:r10 and f1:f8 (if saved)
2077 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2078 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2081 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2083 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2085 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2088 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2089 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2091 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2092 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2094 uint64_t FPROffset = 1;
2095 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2097 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2099 // Store first byte : number of int regs
2100 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2102 MachinePointerInfo(SV),
2103 MVT::i8, false, false, 0);
2104 uint64_t nextOffset = FPROffset;
2105 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2108 // Store second byte : number of float regs
2109 SDValue secondStore =
2110 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2111 MachinePointerInfo(SV, nextOffset), MVT::i8,
2113 nextOffset += StackOffset;
2114 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2116 // Store second word : arguments given on stack
2117 SDValue thirdStore =
2118 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2119 MachinePointerInfo(SV, nextOffset),
2121 nextOffset += FrameOffset;
2122 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2124 // Store third word : arguments given in registers
2125 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2126 MachinePointerInfo(SV, nextOffset),
2131 #include "PPCGenCallingConv.inc"
2133 // Function whose sole purpose is to kill compiler warnings
2134 // stemming from unused functions included from PPCGenCallingConv.inc.
2135 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2136 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2139 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2140 CCValAssign::LocInfo &LocInfo,
2141 ISD::ArgFlagsTy &ArgFlags,
2146 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2148 CCValAssign::LocInfo &LocInfo,
2149 ISD::ArgFlagsTy &ArgFlags,
2151 static const MCPhysReg ArgRegs[] = {
2152 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2153 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2155 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2157 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2159 // Skip one register if the first unallocated register has an even register
2160 // number and there are still argument registers available which have not been
2161 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2162 // need to skip a register if RegNum is odd.
2163 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2164 State.AllocateReg(ArgRegs[RegNum]);
2167 // Always return false here, as this function only makes sure that the first
2168 // unallocated register has an odd register number and does not actually
2169 // allocate a register for the current argument.
2173 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2175 CCValAssign::LocInfo &LocInfo,
2176 ISD::ArgFlagsTy &ArgFlags,
2178 static const MCPhysReg ArgRegs[] = {
2179 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2183 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2185 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2187 // If there is only one Floating-point register left we need to put both f64
2188 // values of a split ppc_fp128 value on the stack.
2189 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2190 State.AllocateReg(ArgRegs[RegNum]);
2193 // Always return false here, as this function only makes sure that the two f64
2194 // values a ppc_fp128 value is split into are both passed in registers or both
2195 // passed on the stack and does not actually allocate a register for the
2196 // current argument.
2200 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2202 static const MCPhysReg *GetFPR() {
2203 static const MCPhysReg FPR[] = {
2204 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2205 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2211 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2213 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2214 unsigned PtrByteSize) {
2215 unsigned ArgSize = ArgVT.getStoreSize();
2216 if (Flags.isByVal())
2217 ArgSize = Flags.getByValSize();
2219 // Round up to multiples of the pointer size, except for array members,
2220 // which are always packed.
2221 if (!Flags.isInConsecutiveRegs())
2222 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2227 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2229 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2230 ISD::ArgFlagsTy Flags,
2231 unsigned PtrByteSize) {
2232 unsigned Align = PtrByteSize;
2234 // Altivec parameters are padded to a 16 byte boundary.
2235 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2236 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2237 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2240 // ByVal parameters are aligned as requested.
2241 if (Flags.isByVal()) {
2242 unsigned BVAlign = Flags.getByValAlign();
2243 if (BVAlign > PtrByteSize) {
2244 if (BVAlign % PtrByteSize != 0)
2246 "ByVal alignment is not a multiple of the pointer size");
2252 // Array members are always packed to their original alignment.
2253 if (Flags.isInConsecutiveRegs()) {
2254 // If the array member was split into multiple registers, the first
2255 // needs to be aligned to the size of the full type. (Except for
2256 // ppcf128, which is only aligned as its f64 components.)
2257 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2258 Align = OrigVT.getStoreSize();
2260 Align = ArgVT.getStoreSize();
2266 /// CalculateStackSlotUsed - Return whether this argument will use its
2267 /// stack slot (instead of being passed in registers). ArgOffset,
2268 /// AvailableFPRs, and AvailableVRs must hold the current argument
2269 /// position, and will be updated to account for this argument.
2270 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2271 ISD::ArgFlagsTy Flags,
2272 unsigned PtrByteSize,
2273 unsigned LinkageSize,
2274 unsigned ParamAreaSize,
2275 unsigned &ArgOffset,
2276 unsigned &AvailableFPRs,
2277 unsigned &AvailableVRs) {
2278 bool UseMemory = false;
2280 // Respect alignment of argument on the stack.
2282 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2283 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2284 // If there's no space left in the argument save area, we must
2285 // use memory (this check also catches zero-sized arguments).
2286 if (ArgOffset >= LinkageSize + ParamAreaSize)
2289 // Allocate argument on the stack.
2290 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2291 if (Flags.isInConsecutiveRegsLast())
2292 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2293 // If we overran the argument save area, we must use memory
2294 // (this check catches arguments passed partially in memory)
2295 if (ArgOffset > LinkageSize + ParamAreaSize)
2298 // However, if the argument is actually passed in an FPR or a VR,
2299 // we don't use memory after all.
2300 if (!Flags.isByVal()) {
2301 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2302 if (AvailableFPRs > 0) {
2306 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2307 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2308 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2309 if (AvailableVRs > 0) {
2318 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2319 /// ensure minimum alignment required for target.
2320 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2321 unsigned NumBytes) {
2322 unsigned TargetAlign =
2323 Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2324 unsigned AlignMask = TargetAlign - 1;
2325 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2330 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2331 CallingConv::ID CallConv, bool isVarArg,
2332 const SmallVectorImpl<ISD::InputArg>
2334 SDLoc dl, SelectionDAG &DAG,
2335 SmallVectorImpl<SDValue> &InVals)
2337 if (Subtarget.isSVR4ABI()) {
2338 if (Subtarget.isPPC64())
2339 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2342 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2345 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2351 PPCTargetLowering::LowerFormalArguments_32SVR4(
2353 CallingConv::ID CallConv, bool isVarArg,
2354 const SmallVectorImpl<ISD::InputArg>
2356 SDLoc dl, SelectionDAG &DAG,
2357 SmallVectorImpl<SDValue> &InVals) const {
2359 // 32-bit SVR4 ABI Stack Frame Layout:
2360 // +-----------------------------------+
2361 // +--> | Back chain |
2362 // | +-----------------------------------+
2363 // | | Floating-point register save area |
2364 // | +-----------------------------------+
2365 // | | General register save area |
2366 // | +-----------------------------------+
2367 // | | CR save word |
2368 // | +-----------------------------------+
2369 // | | VRSAVE save word |
2370 // | +-----------------------------------+
2371 // | | Alignment padding |
2372 // | +-----------------------------------+
2373 // | | Vector register save area |
2374 // | +-----------------------------------+
2375 // | | Local variable space |
2376 // | +-----------------------------------+
2377 // | | Parameter list area |
2378 // | +-----------------------------------+
2379 // | | LR save word |
2380 // | +-----------------------------------+
2381 // SP--> +--- | Back chain |
2382 // +-----------------------------------+
2385 // System V Application Binary Interface PowerPC Processor Supplement
2386 // AltiVec Technology Programming Interface Manual
2388 MachineFunction &MF = DAG.getMachineFunction();
2389 MachineFrameInfo *MFI = MF.getFrameInfo();
2390 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2392 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2393 // Potential tail calls could cause overwriting of argument stack slots.
2394 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2395 (CallConv == CallingConv::Fast));
2396 unsigned PtrByteSize = 4;
2398 // Assign locations to all of the incoming arguments.
2399 SmallVector<CCValAssign, 16> ArgLocs;
2400 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2403 // Reserve space for the linkage area on the stack.
2404 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2405 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2407 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2409 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2410 CCValAssign &VA = ArgLocs[i];
2412 // Arguments stored in registers.
2413 if (VA.isRegLoc()) {
2414 const TargetRegisterClass *RC;
2415 EVT ValVT = VA.getValVT();
2417 switch (ValVT.getSimpleVT().SimpleTy) {
2419 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2422 RC = &PPC::GPRCRegClass;
2425 RC = &PPC::F4RCRegClass;
2428 if (Subtarget.hasVSX())
2429 RC = &PPC::VSFRCRegClass;
2431 RC = &PPC::F8RCRegClass;
2437 RC = &PPC::VRRCRegClass;
2441 RC = &PPC::VSHRCRegClass;
2445 // Transform the arguments stored in physical registers into virtual ones.
2446 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2447 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2448 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2450 if (ValVT == MVT::i1)
2451 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2453 InVals.push_back(ArgValue);
2455 // Argument stored in memory.
2456 assert(VA.isMemLoc());
2458 unsigned ArgSize = VA.getLocVT().getStoreSize();
2459 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2462 // Create load nodes to retrieve arguments from the stack.
2463 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2464 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2465 MachinePointerInfo(),
2466 false, false, false, 0));
2470 // Assign locations to all of the incoming aggregate by value arguments.
2471 // Aggregates passed by value are stored in the local variable space of the
2472 // caller's stack frame, right above the parameter list area.
2473 SmallVector<CCValAssign, 16> ByValArgLocs;
2474 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2475 ByValArgLocs, *DAG.getContext());
2477 // Reserve stack space for the allocations in CCInfo.
2478 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2480 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2482 // Area that is at least reserved in the caller of this function.
2483 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2484 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2486 // Set the size that is at least reserved in caller of this function. Tail
2487 // call optimized function's reserved stack space needs to be aligned so that
2488 // taking the difference between two stack areas will result in an aligned
2490 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2491 FuncInfo->setMinReservedArea(MinReservedArea);
2493 SmallVector<SDValue, 8> MemOps;
2495 // If the function takes variable number of arguments, make a frame index for
2496 // the start of the first vararg value... for expansion of llvm.va_start.
2498 static const MCPhysReg GPArgRegs[] = {
2499 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2500 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2502 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2504 static const MCPhysReg FPArgRegs[] = {
2505 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2508 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2509 if (DisablePPCFloatInVariadic)
2512 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2514 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2517 // Make room for NumGPArgRegs and NumFPArgRegs.
2518 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2519 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2521 FuncInfo->setVarArgsStackOffset(
2522 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2523 CCInfo.getNextStackOffset(), true));
2525 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2526 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2528 // The fixed integer arguments of a variadic function are stored to the
2529 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2530 // the result of va_next.
2531 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2532 // Get an existing live-in vreg, or add a new one.
2533 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2535 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2537 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2538 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2539 MachinePointerInfo(), false, false, 0);
2540 MemOps.push_back(Store);
2541 // Increment the address by four for the next argument to store
2542 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2543 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2546 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2548 // The double arguments are stored to the VarArgsFrameIndex
2550 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2551 // Get an existing live-in vreg, or add a new one.
2552 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2554 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2556 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2557 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2558 MachinePointerInfo(), false, false, 0);
2559 MemOps.push_back(Store);
2560 // Increment the address by eight for the next argument to store
2561 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2563 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2567 if (!MemOps.empty())
2568 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2573 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2574 // value to MVT::i64 and then truncate to the correct register size.
2576 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2577 SelectionDAG &DAG, SDValue ArgVal,
2580 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2581 DAG.getValueType(ObjectVT));
2582 else if (Flags.isZExt())
2583 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2584 DAG.getValueType(ObjectVT));
2586 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2590 PPCTargetLowering::LowerFormalArguments_64SVR4(
2592 CallingConv::ID CallConv, bool isVarArg,
2593 const SmallVectorImpl<ISD::InputArg>
2595 SDLoc dl, SelectionDAG &DAG,
2596 SmallVectorImpl<SDValue> &InVals) const {
2597 // TODO: add description of PPC stack frame format, or at least some docs.
2599 bool isELFv2ABI = Subtarget.isELFv2ABI();
2600 bool isLittleEndian = Subtarget.isLittleEndian();
2601 MachineFunction &MF = DAG.getMachineFunction();
2602 MachineFrameInfo *MFI = MF.getFrameInfo();
2603 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2605 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2606 // Potential tail calls could cause overwriting of argument stack slots.
2607 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2608 (CallConv == CallingConv::Fast));
2609 unsigned PtrByteSize = 8;
2611 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2614 static const MCPhysReg GPR[] = {
2615 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2616 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2619 static const MCPhysReg *FPR = GetFPR();
2621 static const MCPhysReg VR[] = {
2622 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2623 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2625 static const MCPhysReg VSRH[] = {
2626 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2627 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2630 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2631 const unsigned Num_FPR_Regs = 13;
2632 const unsigned Num_VR_Regs = array_lengthof(VR);
2634 // Do a first pass over the arguments to determine whether the ABI
2635 // guarantees that our caller has allocated the parameter save area
2636 // on its stack frame. In the ELFv1 ABI, this is always the case;
2637 // in the ELFv2 ABI, it is true if this is a vararg function or if
2638 // any parameter is located in a stack slot.
2640 bool HasParameterArea = !isELFv2ABI || isVarArg;
2641 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2642 unsigned NumBytes = LinkageSize;
2643 unsigned AvailableFPRs = Num_FPR_Regs;
2644 unsigned AvailableVRs = Num_VR_Regs;
2645 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2646 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2647 PtrByteSize, LinkageSize, ParamAreaSize,
2648 NumBytes, AvailableFPRs, AvailableVRs))
2649 HasParameterArea = true;
2651 // Add DAG nodes to load the arguments or copy them out of registers. On
2652 // entry to a function on PPC, the arguments start after the linkage area,
2653 // although the first ones are often in registers.
2655 unsigned ArgOffset = LinkageSize;
2656 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2657 SmallVector<SDValue, 8> MemOps;
2658 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2659 unsigned CurArgIdx = 0;
2660 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2662 bool needsLoad = false;
2663 EVT ObjectVT = Ins[ArgNo].VT;
2664 EVT OrigVT = Ins[ArgNo].ArgVT;
2665 unsigned ObjSize = ObjectVT.getStoreSize();
2666 unsigned ArgSize = ObjSize;
2667 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2668 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2669 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2671 /* Respect alignment of argument on the stack. */
2673 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2674 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2675 unsigned CurArgOffset = ArgOffset;
2677 /* Compute GPR index associated with argument offset. */
2678 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2679 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2681 // FIXME the codegen can be much improved in some cases.
2682 // We do not have to keep everything in memory.
2683 if (Flags.isByVal()) {
2684 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2685 ObjSize = Flags.getByValSize();
2686 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2687 // Empty aggregate parameters do not take up registers. Examples:
2691 // etc. However, we have to provide a place-holder in InVals, so
2692 // pretend we have an 8-byte item at the current address for that
2695 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2696 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2697 InVals.push_back(FIN);
2701 // Create a stack object covering all stack doublewords occupied
2702 // by the argument. If the argument is (fully or partially) on
2703 // the stack, or if the argument is fully in registers but the
2704 // caller has allocated the parameter save anyway, we can refer
2705 // directly to the caller's stack frame. Otherwise, create a
2706 // local copy in our own frame.
2708 if (HasParameterArea ||
2709 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2710 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2712 FI = MFI->CreateStackObject(ArgSize, Align, false);
2713 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2715 // Handle aggregates smaller than 8 bytes.
2716 if (ObjSize < PtrByteSize) {
2717 // The value of the object is its address, which differs from the
2718 // address of the enclosing doubleword on big-endian systems.
2720 if (!isLittleEndian) {
2721 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2722 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2724 InVals.push_back(Arg);
2726 if (GPR_idx != Num_GPR_Regs) {
2727 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2728 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2731 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2732 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2733 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2734 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2735 MachinePointerInfo(FuncArg),
2736 ObjType, false, false, 0);
2738 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2739 // store the whole register as-is to the parameter save area
2741 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2742 MachinePointerInfo(FuncArg),
2746 MemOps.push_back(Store);
2748 // Whether we copied from a register or not, advance the offset
2749 // into the parameter save area by a full doubleword.
2750 ArgOffset += PtrByteSize;
2754 // The value of the object is its address, which is the address of
2755 // its first stack doubleword.
2756 InVals.push_back(FIN);
2758 // Store whatever pieces of the object are in registers to memory.
2759 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2760 if (GPR_idx == Num_GPR_Regs)
2763 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2764 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2767 SDValue Off = DAG.getConstant(j, PtrVT);
2768 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2770 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2771 MachinePointerInfo(FuncArg, j),
2773 MemOps.push_back(Store);
2776 ArgOffset += ArgSize;
2780 switch (ObjectVT.getSimpleVT().SimpleTy) {
2781 default: llvm_unreachable("Unhandled argument type!");
2785 // These can be scalar arguments or elements of an integer array type
2786 // passed directly. Clang may use those instead of "byval" aggregate
2787 // types to avoid forcing arguments to memory unnecessarily.
2788 if (GPR_idx != Num_GPR_Regs) {
2789 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2790 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2792 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2793 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2794 // value to MVT::i64 and then truncate to the correct register size.
2795 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2798 ArgSize = PtrByteSize;
2805 // These can be scalar arguments or elements of a float array type
2806 // passed directly. The latter are used to implement ELFv2 homogenous
2807 // float aggregates.
2808 if (FPR_idx != Num_FPR_Regs) {
2811 if (ObjectVT == MVT::f32)
2812 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2814 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2815 &PPC::VSFRCRegClass :
2816 &PPC::F8RCRegClass);
2818 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2820 } else if (GPR_idx != Num_GPR_Regs) {
2821 // This can only ever happen in the presence of f32 array types,
2822 // since otherwise we never run out of FPRs before running out
2824 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2825 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2827 if (ObjectVT == MVT::f32) {
2828 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2829 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2830 DAG.getConstant(32, MVT::i32));
2831 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2834 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2839 // When passing an array of floats, the array occupies consecutive
2840 // space in the argument area; only round up to the next doubleword
2841 // at the end of the array. Otherwise, each float takes 8 bytes.
2842 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2843 ArgOffset += ArgSize;
2844 if (Flags.isInConsecutiveRegsLast())
2845 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2853 // These can be scalar arguments or elements of a vector array type
2854 // passed directly. The latter are used to implement ELFv2 homogenous
2855 // vector aggregates.
2856 if (VR_idx != Num_VR_Regs) {
2857 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2858 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2859 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2860 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2869 // We need to load the argument to a virtual register if we determined
2870 // above that we ran out of physical registers of the appropriate type.
2872 if (ObjSize < ArgSize && !isLittleEndian)
2873 CurArgOffset += ArgSize - ObjSize;
2874 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2875 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2876 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2877 false, false, false, 0);
2880 InVals.push_back(ArgVal);
2883 // Area that is at least reserved in the caller of this function.
2884 unsigned MinReservedArea;
2885 if (HasParameterArea)
2886 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2888 MinReservedArea = LinkageSize;
2890 // Set the size that is at least reserved in caller of this function. Tail
2891 // call optimized functions' reserved stack space needs to be aligned so that
2892 // taking the difference between two stack areas will result in an aligned
2894 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2895 FuncInfo->setMinReservedArea(MinReservedArea);
2897 // If the function takes variable number of arguments, make a frame index for
2898 // the start of the first vararg value... for expansion of llvm.va_start.
2900 int Depth = ArgOffset;
2902 FuncInfo->setVarArgsFrameIndex(
2903 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2904 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2906 // If this function is vararg, store any remaining integer argument regs
2907 // to their spots on the stack so that they may be loaded by deferencing the
2908 // result of va_next.
2909 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2910 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2911 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2912 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2913 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2914 MachinePointerInfo(), false, false, 0);
2915 MemOps.push_back(Store);
2916 // Increment the address by four for the next argument to store
2917 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2918 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2922 if (!MemOps.empty())
2923 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2929 PPCTargetLowering::LowerFormalArguments_Darwin(
2931 CallingConv::ID CallConv, bool isVarArg,
2932 const SmallVectorImpl<ISD::InputArg>
2934 SDLoc dl, SelectionDAG &DAG,
2935 SmallVectorImpl<SDValue> &InVals) const {
2936 // TODO: add description of PPC stack frame format, or at least some docs.
2938 MachineFunction &MF = DAG.getMachineFunction();
2939 MachineFrameInfo *MFI = MF.getFrameInfo();
2940 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2942 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2943 bool isPPC64 = PtrVT == MVT::i64;
2944 // Potential tail calls could cause overwriting of argument stack slots.
2945 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2946 (CallConv == CallingConv::Fast));
2947 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2949 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2951 unsigned ArgOffset = LinkageSize;
2952 // Area that is at least reserved in caller of this function.
2953 unsigned MinReservedArea = ArgOffset;
2955 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2956 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2957 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2959 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2960 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2961 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2964 static const MCPhysReg *FPR = GetFPR();
2966 static const MCPhysReg VR[] = {
2967 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2968 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2971 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2972 const unsigned Num_FPR_Regs = 13;
2973 const unsigned Num_VR_Regs = array_lengthof( VR);
2975 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2977 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2979 // In 32-bit non-varargs functions, the stack space for vectors is after the
2980 // stack space for non-vectors. We do not use this space unless we have
2981 // too many vectors to fit in registers, something that only occurs in
2982 // constructed examples:), but we have to walk the arglist to figure
2983 // that out...for the pathological case, compute VecArgOffset as the
2984 // start of the vector parameter area. Computing VecArgOffset is the
2985 // entire point of the following loop.
2986 unsigned VecArgOffset = ArgOffset;
2987 if (!isVarArg && !isPPC64) {
2988 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2990 EVT ObjectVT = Ins[ArgNo].VT;
2991 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2993 if (Flags.isByVal()) {
2994 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2995 unsigned ObjSize = Flags.getByValSize();
2997 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2998 VecArgOffset += ArgSize;
3002 switch(ObjectVT.getSimpleVT().SimpleTy) {
3003 default: llvm_unreachable("Unhandled argument type!");
3009 case MVT::i64: // PPC64
3011 // FIXME: We are guaranteed to be !isPPC64 at this point.
3012 // Does MVT::i64 apply?
3019 // Nothing to do, we're only looking at Nonvector args here.
3024 // We've found where the vector parameter area in memory is. Skip the
3025 // first 12 parameters; these don't use that memory.
3026 VecArgOffset = ((VecArgOffset+15)/16)*16;
3027 VecArgOffset += 12*16;
3029 // Add DAG nodes to load the arguments or copy them out of registers. On
3030 // entry to a function on PPC, the arguments start after the linkage area,
3031 // although the first ones are often in registers.
3033 SmallVector<SDValue, 8> MemOps;
3034 unsigned nAltivecParamsAtEnd = 0;
3035 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3036 unsigned CurArgIdx = 0;
3037 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3039 bool needsLoad = false;
3040 EVT ObjectVT = Ins[ArgNo].VT;
3041 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3042 unsigned ArgSize = ObjSize;
3043 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3044 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3045 CurArgIdx = Ins[ArgNo].OrigArgIndex;
3047 unsigned CurArgOffset = ArgOffset;
3049 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3050 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3051 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3052 if (isVarArg || isPPC64) {
3053 MinReservedArea = ((MinReservedArea+15)/16)*16;
3054 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3057 } else nAltivecParamsAtEnd++;
3059 // Calculate min reserved area.
3060 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3064 // FIXME the codegen can be much improved in some cases.
3065 // We do not have to keep everything in memory.
3066 if (Flags.isByVal()) {
3067 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3068 ObjSize = Flags.getByValSize();
3069 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3070 // Objects of size 1 and 2 are right justified, everything else is
3071 // left justified. This means the memory address is adjusted forwards.
3072 if (ObjSize==1 || ObjSize==2) {
3073 CurArgOffset = CurArgOffset + (4 - ObjSize);
3075 // The value of the object is its address.
3076 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3077 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3078 InVals.push_back(FIN);
3079 if (ObjSize==1 || ObjSize==2) {
3080 if (GPR_idx != Num_GPR_Regs) {
3083 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3085 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3086 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3087 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3088 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3089 MachinePointerInfo(FuncArg),
3090 ObjType, false, false, 0);
3091 MemOps.push_back(Store);
3095 ArgOffset += PtrByteSize;
3099 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3100 // Store whatever pieces of the object are in registers
3101 // to memory. ArgOffset will be the address of the beginning
3103 if (GPR_idx != Num_GPR_Regs) {
3106 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3108 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3109 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3110 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3111 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3112 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3113 MachinePointerInfo(FuncArg, j),
3115 MemOps.push_back(Store);
3117 ArgOffset += PtrByteSize;
3119 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3126 switch (ObjectVT.getSimpleVT().SimpleTy) {
3127 default: llvm_unreachable("Unhandled argument type!");
3131 if (GPR_idx != Num_GPR_Regs) {
3132 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3133 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3135 if (ObjectVT == MVT::i1)
3136 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3141 ArgSize = PtrByteSize;
3143 // All int arguments reserve stack space in the Darwin ABI.
3144 ArgOffset += PtrByteSize;
3148 case MVT::i64: // PPC64
3149 if (GPR_idx != Num_GPR_Regs) {
3150 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3151 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3153 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3154 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3155 // value to MVT::i64 and then truncate to the correct register size.
3156 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3161 ArgSize = PtrByteSize;
3163 // All int arguments reserve stack space in the Darwin ABI.
3169 // Every 4 bytes of argument space consumes one of the GPRs available for
3170 // argument passing.
3171 if (GPR_idx != Num_GPR_Regs) {
3173 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3176 if (FPR_idx != Num_FPR_Regs) {
3179 if (ObjectVT == MVT::f32)
3180 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3182 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3184 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3190 // All FP arguments reserve stack space in the Darwin ABI.
3191 ArgOffset += isPPC64 ? 8 : ObjSize;
3197 // Note that vector arguments in registers don't reserve stack space,
3198 // except in varargs functions.
3199 if (VR_idx != Num_VR_Regs) {
3200 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3201 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3203 while ((ArgOffset % 16) != 0) {
3204 ArgOffset += PtrByteSize;
3205 if (GPR_idx != Num_GPR_Regs)
3209 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3213 if (!isVarArg && !isPPC64) {
3214 // Vectors go after all the nonvectors.
3215 CurArgOffset = VecArgOffset;
3218 // Vectors are aligned.
3219 ArgOffset = ((ArgOffset+15)/16)*16;
3220 CurArgOffset = ArgOffset;
3228 // We need to load the argument to a virtual register if we determined above
3229 // that we ran out of physical registers of the appropriate type.
3231 int FI = MFI->CreateFixedObject(ObjSize,
3232 CurArgOffset + (ArgSize - ObjSize),
3234 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3235 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3236 false, false, false, 0);
3239 InVals.push_back(ArgVal);
3242 // Allow for Altivec parameters at the end, if needed.
3243 if (nAltivecParamsAtEnd) {
3244 MinReservedArea = ((MinReservedArea+15)/16)*16;
3245 MinReservedArea += 16*nAltivecParamsAtEnd;
3248 // Area that is at least reserved in the caller of this function.
3249 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3251 // Set the size that is at least reserved in caller of this function. Tail
3252 // call optimized functions' reserved stack space needs to be aligned so that
3253 // taking the difference between two stack areas will result in an aligned
3255 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3256 FuncInfo->setMinReservedArea(MinReservedArea);
3258 // If the function takes variable number of arguments, make a frame index for
3259 // the start of the first vararg value... for expansion of llvm.va_start.
3261 int Depth = ArgOffset;
3263 FuncInfo->setVarArgsFrameIndex(
3264 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3266 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3268 // If this function is vararg, store any remaining integer argument regs
3269 // to their spots on the stack so that they may be loaded by deferencing the
3270 // result of va_next.
3271 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3275 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3277 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3279 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3280 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3281 MachinePointerInfo(), false, false, 0);
3282 MemOps.push_back(Store);
3283 // Increment the address by four for the next argument to store
3284 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3285 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3289 if (!MemOps.empty())
3290 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3295 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3296 /// adjusted to accommodate the arguments for the tailcall.
3297 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3298 unsigned ParamSize) {
3300 if (!isTailCall) return 0;
3302 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3303 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3304 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3305 // Remember only if the new adjustement is bigger.
3306 if (SPDiff < FI->getTailCallSPDelta())
3307 FI->setTailCallSPDelta(SPDiff);
3312 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3313 /// for tail call optimization. Targets which want to do tail call
3314 /// optimization should implement this function.
3316 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3317 CallingConv::ID CalleeCC,
3319 const SmallVectorImpl<ISD::InputArg> &Ins,
3320 SelectionDAG& DAG) const {
3321 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3324 // Variable argument functions are not supported.
3328 MachineFunction &MF = DAG.getMachineFunction();
3329 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3330 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3331 // Functions containing by val parameters are not supported.
3332 for (unsigned i = 0; i != Ins.size(); i++) {
3333 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3334 if (Flags.isByVal()) return false;
3337 // Non-PIC/GOT tail calls are supported.
3338 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3341 // At the moment we can only do local tail calls (in same module, hidden
3342 // or protected) if we are generating PIC.
3343 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3344 return G->getGlobal()->hasHiddenVisibility()
3345 || G->getGlobal()->hasProtectedVisibility();
3351 /// isCallCompatibleAddress - Return the immediate to use if the specified
3352 /// 32-bit value is representable in the immediate field of a BxA instruction.
3353 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3354 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3355 if (!C) return nullptr;
3357 int Addr = C->getZExtValue();
3358 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3359 SignExtend32<26>(Addr) != Addr)
3360 return nullptr; // Top 6 bits have to be sext of immediate.
3362 return DAG.getConstant((int)C->getZExtValue() >> 2,
3363 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3368 struct TailCallArgumentInfo {
3373 TailCallArgumentInfo() : FrameIdx(0) {}
3378 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3380 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3382 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3383 SmallVectorImpl<SDValue> &MemOpChains,
3385 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3386 SDValue Arg = TailCallArgs[i].Arg;
3387 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3388 int FI = TailCallArgs[i].FrameIdx;
3389 // Store relative to framepointer.
3390 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3391 MachinePointerInfo::getFixedStack(FI),
3396 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3397 /// the appropriate stack slot for the tail call optimized function call.
3398 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3399 MachineFunction &MF,
3408 // Calculate the new stack slot for the return address.
3409 int SlotSize = isPPC64 ? 8 : 4;
3410 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3412 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3413 NewRetAddrLoc, true);
3414 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3415 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3416 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3417 MachinePointerInfo::getFixedStack(NewRetAddr),
3420 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3421 // slot as the FP is never overwritten.
3424 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3425 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3427 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3428 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3429 MachinePointerInfo::getFixedStack(NewFPIdx),
3436 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3437 /// the position of the argument.
3439 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3440 SDValue Arg, int SPDiff, unsigned ArgOffset,
3441 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3442 int Offset = ArgOffset + SPDiff;
3443 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3444 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3445 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3446 SDValue FIN = DAG.getFrameIndex(FI, VT);
3447 TailCallArgumentInfo Info;
3449 Info.FrameIdxOp = FIN;
3451 TailCallArguments.push_back(Info);
3454 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3455 /// stack slot. Returns the chain as result and the loaded frame pointers in
3456 /// LROpOut/FPOpout. Used when tail calling.
3457 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3465 // Load the LR and FP stack slot for later adjusting.
3466 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3467 LROpOut = getReturnAddrFrameIndex(DAG);
3468 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3469 false, false, false, 0);
3470 Chain = SDValue(LROpOut.getNode(), 1);
3472 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3473 // slot as the FP is never overwritten.
3475 FPOpOut = getFramePointerFrameIndex(DAG);
3476 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3477 false, false, false, 0);
3478 Chain = SDValue(FPOpOut.getNode(), 1);
3484 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3485 /// by "Src" to address "Dst" of size "Size". Alignment information is
3486 /// specified by the specific parameter attribute. The copy will be passed as
3487 /// a byval function parameter.
3488 /// Sometimes what we are copying is the end of a larger object, the part that
3489 /// does not fit in registers.
3491 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3492 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3494 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3495 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3496 false, false, MachinePointerInfo(),
3497 MachinePointerInfo());
3500 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3503 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3504 SDValue Arg, SDValue PtrOff, int SPDiff,
3505 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3506 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3507 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3509 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3514 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3516 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3517 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3518 DAG.getConstant(ArgOffset, PtrVT));
3520 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3521 MachinePointerInfo(), false, false, 0));
3522 // Calculate and remember argument location.
3523 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3528 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3529 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3530 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3531 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3532 MachineFunction &MF = DAG.getMachineFunction();
3534 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3535 // might overwrite each other in case of tail call optimization.
3536 SmallVector<SDValue, 8> MemOpChains2;
3537 // Do not flag preceding copytoreg stuff together with the following stuff.
3539 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3541 if (!MemOpChains2.empty())
3542 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3544 // Store the return address to the appropriate stack slot.
3545 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3546 isPPC64, isDarwinABI, dl);
3548 // Emit callseq_end just before tailcall node.
3549 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3550 DAG.getIntPtrConstant(0, true), InFlag, dl);
3551 InFlag = Chain.getValue(1);
3555 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3556 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3557 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3558 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3559 const PPCSubtarget &Subtarget) {
3561 bool isPPC64 = Subtarget.isPPC64();
3562 bool isSVR4ABI = Subtarget.isSVR4ABI();
3563 bool isELFv2ABI = Subtarget.isELFv2ABI();
3565 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3566 NodeTys.push_back(MVT::Other); // Returns a chain
3567 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3569 unsigned CallOpc = PPCISD::CALL;
3571 bool needIndirectCall = true;
3572 if (!isSVR4ABI || !isPPC64)
3573 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3574 // If this is an absolute destination address, use the munged value.
3575 Callee = SDValue(Dest, 0);
3576 needIndirectCall = false;
3579 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3580 unsigned OpFlags = 0;
3581 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3582 (Subtarget.getTargetTriple().isMacOSX() &&
3583 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3584 (G->getGlobal()->isDeclaration() ||
3585 G->getGlobal()->isWeakForLinker())) ||
3586 (Subtarget.isTargetELF() && !isPPC64 &&
3587 !G->getGlobal()->hasLocalLinkage() &&
3588 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3589 // PC-relative references to external symbols should go through $stub,
3590 // unless we're building with the leopard linker or later, which
3591 // automatically synthesizes these stubs.
3592 OpFlags = PPCII::MO_PLT_OR_STUB;
3595 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3596 // every direct call is) turn it into a TargetGlobalAddress /
3597 // TargetExternalSymbol node so that legalize doesn't hack it.
3598 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3599 Callee.getValueType(), 0, OpFlags);
3600 needIndirectCall = false;
3603 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3604 unsigned char OpFlags = 0;
3606 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3607 (Subtarget.getTargetTriple().isMacOSX() &&
3608 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3609 (Subtarget.isTargetELF() && !isPPC64 &&
3610 DAG.getTarget().getRelocationModel() == Reloc::PIC_) ) {
3611 // PC-relative references to external symbols should go through $stub,
3612 // unless we're building with the leopard linker or later, which
3613 // automatically synthesizes these stubs.
3614 OpFlags = PPCII::MO_PLT_OR_STUB;
3617 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3619 needIndirectCall = false;
3622 if (needIndirectCall) {
3623 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3624 // to do the call, we can't use PPCISD::CALL.
3625 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3627 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3628 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3629 // entry point, but to the function descriptor (the function entry point
3630 // address is part of the function descriptor though).
3631 // The function descriptor is a three doubleword structure with the
3632 // following fields: function entry point, TOC base address and
3633 // environment pointer.
3634 // Thus for a call through a function pointer, the following actions need
3636 // 1. Save the TOC of the caller in the TOC save area of its stack
3637 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3638 // 2. Load the address of the function entry point from the function
3640 // 3. Load the TOC of the callee from the function descriptor into r2.
3641 // 4. Load the environment pointer from the function descriptor into
3643 // 5. Branch to the function entry point address.
3644 // 6. On return of the callee, the TOC of the caller needs to be
3645 // restored (this is done in FinishCall()).
3647 // All those operations are flagged together to ensure that no other
3648 // operations can be scheduled in between. E.g. without flagging the
3649 // operations together, a TOC access in the caller could be scheduled
3650 // between the load of the callee TOC and the branch to the callee, which
3651 // results in the TOC access going through the TOC of the callee instead
3652 // of going through the TOC of the caller, which leads to incorrect code.
3654 // Load the address of the function entry point from the function
3656 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3657 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3658 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3659 Chain = LoadFuncPtr.getValue(1);
3660 InFlag = LoadFuncPtr.getValue(2);
3662 // Load environment pointer into r11.
3663 // Offset of the environment pointer within the function descriptor.
3664 SDValue PtrOff = DAG.getIntPtrConstant(16);
3666 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3667 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3669 Chain = LoadEnvPtr.getValue(1);
3670 InFlag = LoadEnvPtr.getValue(2);
3672 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3674 Chain = EnvVal.getValue(0);
3675 InFlag = EnvVal.getValue(1);
3677 // Load TOC of the callee into r2. We are using a target-specific load
3678 // with r2 hard coded, because the result of a target-independent load
3679 // would never go directly into r2, since r2 is a reserved register (which
3680 // prevents the register allocator from allocating it), resulting in an
3681 // additional register being allocated and an unnecessary move instruction
3683 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3684 SDValue TOCOff = DAG.getIntPtrConstant(8);
3685 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3686 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3688 Chain = LoadTOCPtr.getValue(0);
3689 InFlag = LoadTOCPtr.getValue(1);
3691 MTCTROps[0] = Chain;
3692 MTCTROps[1] = LoadFuncPtr;
3693 MTCTROps[2] = InFlag;
3696 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3697 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3698 InFlag = Chain.getValue(1);
3701 NodeTys.push_back(MVT::Other);
3702 NodeTys.push_back(MVT::Glue);
3703 Ops.push_back(Chain);
3704 CallOpc = PPCISD::BCTRL;
3705 Callee.setNode(nullptr);
3706 // Add use of X11 (holding environment pointer)
3707 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3708 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3709 // Add CTR register as callee so a bctr can be emitted later.
3711 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3714 // If this is a direct call, pass the chain and the callee.
3715 if (Callee.getNode()) {
3716 Ops.push_back(Chain);
3717 Ops.push_back(Callee);
3719 // If this is a call to __tls_get_addr, find the symbol whose address
3720 // is to be taken and add it to the list. This will be used to
3721 // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld).
3722 // We find the symbol by walking the chain to the CopyFromReg, walking
3723 // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and
3724 // pulling the symbol from that node.
3725 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
3726 if (!strcmp(S->getSymbol(), "__tls_get_addr")) {
3727 assert(!needIndirectCall && "Indirect call to __tls_get_addr???");
3728 SDNode *AddI = Chain.getNode()->getOperand(2).getNode();
3729 SDValue TGTAddr = AddI->getOperand(1);
3730 assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress &&
3731 "Didn't find target global TLS address where we expected one");
3732 Ops.push_back(TGTAddr);
3733 CallOpc = PPCISD::CALL_TLS;
3736 // If this is a tail call add stack pointer delta.
3738 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3740 // Add argument registers to the end of the list so that they are known live
3742 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3743 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3744 RegsToPass[i].second.getValueType()));
3746 // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3747 if (Callee.getNode() && isELFv2ABI)
3748 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3754 bool isLocalCall(const SDValue &Callee)
3756 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3757 return !G->getGlobal()->isDeclaration() &&
3758 !G->getGlobal()->isWeakForLinker();
3763 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3764 CallingConv::ID CallConv, bool isVarArg,
3765 const SmallVectorImpl<ISD::InputArg> &Ins,
3766 SDLoc dl, SelectionDAG &DAG,
3767 SmallVectorImpl<SDValue> &InVals) const {
3769 SmallVector<CCValAssign, 16> RVLocs;
3770 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3772 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3774 // Copy all of the result registers out of their specified physreg.
3775 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3776 CCValAssign &VA = RVLocs[i];
3777 assert(VA.isRegLoc() && "Can only return in registers!");
3779 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3780 VA.getLocReg(), VA.getLocVT(), InFlag);
3781 Chain = Val.getValue(1);
3782 InFlag = Val.getValue(2);
3784 switch (VA.getLocInfo()) {
3785 default: llvm_unreachable("Unknown loc info!");
3786 case CCValAssign::Full: break;
3787 case CCValAssign::AExt:
3788 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3790 case CCValAssign::ZExt:
3791 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3792 DAG.getValueType(VA.getValVT()));
3793 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3795 case CCValAssign::SExt:
3796 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3797 DAG.getValueType(VA.getValVT()));
3798 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3802 InVals.push_back(Val);
3809 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3810 bool isTailCall, bool isVarArg,
3812 SmallVector<std::pair<unsigned, SDValue>, 8>
3814 SDValue InFlag, SDValue Chain,
3816 int SPDiff, unsigned NumBytes,
3817 const SmallVectorImpl<ISD::InputArg> &Ins,
3818 SmallVectorImpl<SDValue> &InVals) const {
3820 bool isELFv2ABI = Subtarget.isELFv2ABI();
3821 std::vector<EVT> NodeTys;
3822 SmallVector<SDValue, 8> Ops;
3823 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3824 isTailCall, RegsToPass, Ops, NodeTys,
3827 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3828 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3829 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3831 // When performing tail call optimization the callee pops its arguments off
3832 // the stack. Account for this here so these bytes can be pushed back on in
3833 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3834 int BytesCalleePops =
3835 (CallConv == CallingConv::Fast &&
3836 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3838 // Add a register mask operand representing the call-preserved registers.
3839 const TargetRegisterInfo *TRI =
3840 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3841 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3842 assert(Mask && "Missing call preserved mask for calling convention");
3843 Ops.push_back(DAG.getRegisterMask(Mask));
3845 if (InFlag.getNode())
3846 Ops.push_back(InFlag);
3850 assert(((Callee.getOpcode() == ISD::Register &&
3851 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3852 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3853 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3854 isa<ConstantSDNode>(Callee)) &&
3855 "Expecting an global address, external symbol, absolute value or register");
3857 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3860 // Add a NOP immediately after the branch instruction when using the 64-bit
3861 // SVR4 ABI. At link time, if caller and callee are in a different module and
3862 // thus have a different TOC, the call will be replaced with a call to a stub
3863 // function which saves the current TOC, loads the TOC of the callee and
3864 // branches to the callee. The NOP will be replaced with a load instruction
3865 // which restores the TOC of the caller from the TOC save slot of the current
3866 // stack frame. If caller and callee belong to the same module (and have the
3867 // same TOC), the NOP will remain unchanged.
3869 bool needsTOCRestore = false;
3870 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3871 if (CallOpc == PPCISD::BCTRL) {
3872 // This is a call through a function pointer.
3873 // Restore the caller TOC from the save area into R2.
3874 // See PrepareCall() for more information about calls through function
3875 // pointers in the 64-bit SVR4 ABI.
3876 // We are using a target-specific load with r2 hard coded, because the
3877 // result of a target-independent load would never go directly into r2,
3878 // since r2 is a reserved register (which prevents the register allocator
3879 // from allocating it), resulting in an additional register being
3880 // allocated and an unnecessary move instruction being generated.
3881 needsTOCRestore = true;
3882 } else if ((CallOpc == PPCISD::CALL) &&
3883 (!isLocalCall(Callee) ||
3884 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3885 // Otherwise insert NOP for non-local calls.
3886 CallOpc = PPCISD::CALL_NOP;
3887 } else if (CallOpc == PPCISD::CALL_TLS)
3888 // For 64-bit SVR4, TLS calls are always non-local.
3889 CallOpc = PPCISD::CALL_NOP_TLS;
3892 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3893 InFlag = Chain.getValue(1);
3895 if (needsTOCRestore) {
3896 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3897 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3898 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3899 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3900 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3901 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3902 Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
3903 InFlag = Chain.getValue(1);
3906 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3907 DAG.getIntPtrConstant(BytesCalleePops, true),
3910 InFlag = Chain.getValue(1);
3912 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3913 Ins, dl, DAG, InVals);
3917 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3918 SmallVectorImpl<SDValue> &InVals) const {
3919 SelectionDAG &DAG = CLI.DAG;
3921 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3922 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3923 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3924 SDValue Chain = CLI.Chain;
3925 SDValue Callee = CLI.Callee;
3926 bool &isTailCall = CLI.IsTailCall;
3927 CallingConv::ID CallConv = CLI.CallConv;
3928 bool isVarArg = CLI.IsVarArg;
3931 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3934 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3935 report_fatal_error("failed to perform tail call elimination on a call "
3936 "site marked musttail");
3938 if (Subtarget.isSVR4ABI()) {
3939 if (Subtarget.isPPC64())
3940 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3941 isTailCall, Outs, OutVals, Ins,
3944 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3945 isTailCall, Outs, OutVals, Ins,
3949 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3950 isTailCall, Outs, OutVals, Ins,
3955 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3956 CallingConv::ID CallConv, bool isVarArg,
3958 const SmallVectorImpl<ISD::OutputArg> &Outs,
3959 const SmallVectorImpl<SDValue> &OutVals,
3960 const SmallVectorImpl<ISD::InputArg> &Ins,
3961 SDLoc dl, SelectionDAG &DAG,
3962 SmallVectorImpl<SDValue> &InVals) const {
3963 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3964 // of the 32-bit SVR4 ABI stack frame layout.
3966 assert((CallConv == CallingConv::C ||
3967 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3969 unsigned PtrByteSize = 4;
3971 MachineFunction &MF = DAG.getMachineFunction();
3973 // Mark this function as potentially containing a function that contains a
3974 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3975 // and restoring the callers stack pointer in this functions epilog. This is
3976 // done because by tail calling the called function might overwrite the value
3977 // in this function's (MF) stack pointer stack slot 0(SP).
3978 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3979 CallConv == CallingConv::Fast)
3980 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3982 // Count how many bytes are to be pushed on the stack, including the linkage
3983 // area, parameter list area and the part of the local variable space which
3984 // contains copies of aggregates which are passed by value.
3986 // Assign locations to all of the outgoing arguments.
3987 SmallVector<CCValAssign, 16> ArgLocs;
3988 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3991 // Reserve space for the linkage area on the stack.
3992 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
3996 // Handle fixed and variable vector arguments differently.
3997 // Fixed vector arguments go into registers as long as registers are
3998 // available. Variable vector arguments always go into memory.
3999 unsigned NumArgs = Outs.size();
4001 for (unsigned i = 0; i != NumArgs; ++i) {
4002 MVT ArgVT = Outs[i].VT;
4003 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4006 if (Outs[i].IsFixed) {
4007 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4010 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4016 errs() << "Call operand #" << i << " has unhandled type "
4017 << EVT(ArgVT).getEVTString() << "\n";
4019 llvm_unreachable(nullptr);
4023 // All arguments are treated the same.
4024 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4027 // Assign locations to all of the outgoing aggregate by value arguments.
4028 SmallVector<CCValAssign, 16> ByValArgLocs;
4029 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4030 ByValArgLocs, *DAG.getContext());
4032 // Reserve stack space for the allocations in CCInfo.
4033 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4035 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4037 // Size of the linkage area, parameter list area and the part of the local
4038 // space variable where copies of aggregates which are passed by value are
4040 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4042 // Calculate by how many bytes the stack has to be adjusted in case of tail
4043 // call optimization.
4044 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4046 // Adjust the stack pointer for the new arguments...
4047 // These operations are automatically eliminated by the prolog/epilog pass
4048 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4050 SDValue CallSeqStart = Chain;
4052 // Load the return address and frame pointer so it can be moved somewhere else
4055 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4058 // Set up a copy of the stack pointer for use loading and storing any
4059 // arguments that may not fit in the registers available for argument
4061 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4063 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4064 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4065 SmallVector<SDValue, 8> MemOpChains;
4067 bool seenFloatArg = false;
4068 // Walk the register/memloc assignments, inserting copies/loads.
4069 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4072 CCValAssign &VA = ArgLocs[i];
4073 SDValue Arg = OutVals[i];
4074 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4076 if (Flags.isByVal()) {
4077 // Argument is an aggregate which is passed by value, thus we need to
4078 // create a copy of it in the local variable space of the current stack
4079 // frame (which is the stack frame of the caller) and pass the address of
4080 // this copy to the callee.
4081 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4082 CCValAssign &ByValVA = ByValArgLocs[j++];
4083 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4085 // Memory reserved in the local variable space of the callers stack frame.
4086 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4088 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4089 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4091 // Create a copy of the argument in the local area of the current
4093 SDValue MemcpyCall =
4094 CreateCopyOfByValArgument(Arg, PtrOff,
4095 CallSeqStart.getNode()->getOperand(0),
4098 // This must go outside the CALLSEQ_START..END.
4099 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4100 CallSeqStart.getNode()->getOperand(1),
4102 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4103 NewCallSeqStart.getNode());
4104 Chain = CallSeqStart = NewCallSeqStart;
4106 // Pass the address of the aggregate copy on the stack either in a
4107 // physical register or in the parameter list area of the current stack
4108 // frame to the callee.
4112 if (VA.isRegLoc()) {
4113 if (Arg.getValueType() == MVT::i1)
4114 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4116 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4117 // Put argument in a physical register.
4118 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4120 // Put argument in the parameter list area of the current stack frame.
4121 assert(VA.isMemLoc());
4122 unsigned LocMemOffset = VA.getLocMemOffset();
4125 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4126 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4128 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4129 MachinePointerInfo(),
4132 // Calculate and remember argument location.
4133 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4139 if (!MemOpChains.empty())
4140 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4142 // Build a sequence of copy-to-reg nodes chained together with token chain
4143 // and flag operands which copy the outgoing args into the appropriate regs.
4145 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4146 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4147 RegsToPass[i].second, InFlag);
4148 InFlag = Chain.getValue(1);
4151 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4154 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4155 SDValue Ops[] = { Chain, InFlag };
4157 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4158 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4160 InFlag = Chain.getValue(1);
4164 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4165 false, TailCallArguments);
4167 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4168 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4172 // Copy an argument into memory, being careful to do this outside the
4173 // call sequence for the call to which the argument belongs.
4175 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4176 SDValue CallSeqStart,
4177 ISD::ArgFlagsTy Flags,
4180 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4181 CallSeqStart.getNode()->getOperand(0),
4183 // The MEMCPY must go outside the CALLSEQ_START..END.
4184 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4185 CallSeqStart.getNode()->getOperand(1),
4187 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4188 NewCallSeqStart.getNode());
4189 return NewCallSeqStart;
4193 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4194 CallingConv::ID CallConv, bool isVarArg,
4196 const SmallVectorImpl<ISD::OutputArg> &Outs,
4197 const SmallVectorImpl<SDValue> &OutVals,
4198 const SmallVectorImpl<ISD::InputArg> &Ins,
4199 SDLoc dl, SelectionDAG &DAG,
4200 SmallVectorImpl<SDValue> &InVals) const {
4202 bool isELFv2ABI = Subtarget.isELFv2ABI();
4203 bool isLittleEndian = Subtarget.isLittleEndian();
4204 unsigned NumOps = Outs.size();
4206 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4207 unsigned PtrByteSize = 8;
4209 MachineFunction &MF = DAG.getMachineFunction();
4211 // Mark this function as potentially containing a function that contains a
4212 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4213 // and restoring the callers stack pointer in this functions epilog. This is
4214 // done because by tail calling the called function might overwrite the value
4215 // in this function's (MF) stack pointer stack slot 0(SP).
4216 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4217 CallConv == CallingConv::Fast)
4218 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4220 // Count how many bytes are to be pushed on the stack, including the linkage
4221 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4222 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4223 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4224 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4226 unsigned NumBytes = LinkageSize;
4228 // Add up all the space actually used.
4229 for (unsigned i = 0; i != NumOps; ++i) {
4230 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4231 EVT ArgVT = Outs[i].VT;
4232 EVT OrigVT = Outs[i].ArgVT;
4234 /* Respect alignment of argument on the stack. */
4236 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4237 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4239 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4240 if (Flags.isInConsecutiveRegsLast())
4241 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4244 unsigned NumBytesActuallyUsed = NumBytes;
4246 // The prolog code of the callee may store up to 8 GPR argument registers to
4247 // the stack, allowing va_start to index over them in memory if its varargs.
4248 // Because we cannot tell if this is needed on the caller side, we have to
4249 // conservatively assume that it is needed. As such, make sure we have at
4250 // least enough stack space for the caller to store the 8 GPRs.
4251 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4252 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4254 // Tail call needs the stack to be aligned.
4255 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4256 CallConv == CallingConv::Fast)
4257 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4259 // Calculate by how many bytes the stack has to be adjusted in case of tail
4260 // call optimization.
4261 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4263 // To protect arguments on the stack from being clobbered in a tail call,
4264 // force all the loads to happen before doing any other lowering.
4266 Chain = DAG.getStackArgumentTokenFactor(Chain);
4268 // Adjust the stack pointer for the new arguments...
4269 // These operations are automatically eliminated by the prolog/epilog pass
4270 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4272 SDValue CallSeqStart = Chain;
4274 // Load the return address and frame pointer so it can be move somewhere else
4277 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4280 // Set up a copy of the stack pointer for use loading and storing any
4281 // arguments that may not fit in the registers available for argument
4283 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4285 // Figure out which arguments are going to go in registers, and which in
4286 // memory. Also, if this is a vararg function, floating point operations
4287 // must be stored to our stack, and loaded into integer regs as well, if
4288 // any integer regs are available for argument passing.
4289 unsigned ArgOffset = LinkageSize;
4290 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4292 static const MCPhysReg GPR[] = {
4293 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4294 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4296 static const MCPhysReg *FPR = GetFPR();
4298 static const MCPhysReg VR[] = {
4299 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4300 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4302 static const MCPhysReg VSRH[] = {
4303 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4304 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4307 const unsigned NumGPRs = array_lengthof(GPR);
4308 const unsigned NumFPRs = 13;
4309 const unsigned NumVRs = array_lengthof(VR);
4311 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4312 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4314 SmallVector<SDValue, 8> MemOpChains;
4315 for (unsigned i = 0; i != NumOps; ++i) {
4316 SDValue Arg = OutVals[i];
4317 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4318 EVT ArgVT = Outs[i].VT;
4319 EVT OrigVT = Outs[i].ArgVT;
4321 /* Respect alignment of argument on the stack. */
4323 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4324 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4326 /* Compute GPR index associated with argument offset. */
4327 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4328 GPR_idx = std::min(GPR_idx, NumGPRs);
4330 // PtrOff will be used to store the current argument to the stack if a
4331 // register cannot be found for it.
4334 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4336 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4338 // Promote integers to 64-bit values.
4339 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4340 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4341 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4342 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4345 // FIXME memcpy is used way more than necessary. Correctness first.
4346 // Note: "by value" is code for passing a structure by value, not
4348 if (Flags.isByVal()) {
4349 // Note: Size includes alignment padding, so
4350 // struct x { short a; char b; }
4351 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4352 // These are the proper values we need for right-justifying the
4353 // aggregate in a parameter register.
4354 unsigned Size = Flags.getByValSize();
4356 // An empty aggregate parameter takes up no storage and no
4361 // All aggregates smaller than 8 bytes must be passed right-justified.
4362 if (Size==1 || Size==2 || Size==4) {
4363 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4364 if (GPR_idx != NumGPRs) {
4365 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4366 MachinePointerInfo(), VT,
4367 false, false, false, 0);
4368 MemOpChains.push_back(Load.getValue(1));
4369 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4371 ArgOffset += PtrByteSize;
4376 if (GPR_idx == NumGPRs && Size < 8) {
4377 SDValue AddPtr = PtrOff;
4378 if (!isLittleEndian) {
4379 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4380 PtrOff.getValueType());
4381 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4383 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4386 ArgOffset += PtrByteSize;
4389 // Copy entire object into memory. There are cases where gcc-generated
4390 // code assumes it is there, even if it could be put entirely into
4391 // registers. (This is not what the doc says.)
4393 // FIXME: The above statement is likely due to a misunderstanding of the
4394 // documents. All arguments must be copied into the parameter area BY
4395 // THE CALLEE in the event that the callee takes the address of any
4396 // formal argument. That has not yet been implemented. However, it is
4397 // reasonable to use the stack area as a staging area for the register
4400 // Skip this for small aggregates, as we will use the same slot for a
4401 // right-justified copy, below.
4403 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4407 // When a register is available, pass a small aggregate right-justified.
4408 if (Size < 8 && GPR_idx != NumGPRs) {
4409 // The easiest way to get this right-justified in a register
4410 // is to copy the structure into the rightmost portion of a
4411 // local variable slot, then load the whole slot into the
4413 // FIXME: The memcpy seems to produce pretty awful code for
4414 // small aggregates, particularly for packed ones.
4415 // FIXME: It would be preferable to use the slot in the
4416 // parameter save area instead of a new local variable.
4417 SDValue AddPtr = PtrOff;
4418 if (!isLittleEndian) {
4419 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4420 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4422 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4426 // Load the slot into the register.
4427 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4428 MachinePointerInfo(),
4429 false, false, false, 0);
4430 MemOpChains.push_back(Load.getValue(1));
4431 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4433 // Done with this argument.
4434 ArgOffset += PtrByteSize;
4438 // For aggregates larger than PtrByteSize, copy the pieces of the
4439 // object that fit into registers from the parameter save area.
4440 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4441 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4442 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4443 if (GPR_idx != NumGPRs) {
4444 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4445 MachinePointerInfo(),
4446 false, false, false, 0);
4447 MemOpChains.push_back(Load.getValue(1));
4448 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4449 ArgOffset += PtrByteSize;
4451 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4458 switch (Arg.getSimpleValueType().SimpleTy) {
4459 default: llvm_unreachable("Unexpected ValueType for argument!");
4463 // These can be scalar arguments or elements of an integer array type
4464 // passed directly. Clang may use those instead of "byval" aggregate
4465 // types to avoid forcing arguments to memory unnecessarily.
4466 if (GPR_idx != NumGPRs) {
4467 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4469 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4470 true, isTailCall, false, MemOpChains,
4471 TailCallArguments, dl);
4473 ArgOffset += PtrByteSize;
4477 // These can be scalar arguments or elements of a float array type
4478 // passed directly. The latter are used to implement ELFv2 homogenous
4479 // float aggregates.
4481 // Named arguments go into FPRs first, and once they overflow, the
4482 // remaining arguments go into GPRs and then the parameter save area.
4483 // Unnamed arguments for vararg functions always go to GPRs and
4484 // then the parameter save area. For now, put all arguments to vararg
4485 // routines always in both locations (FPR *and* GPR or stack slot).
4486 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4488 // First load the argument into the next available FPR.
4489 if (FPR_idx != NumFPRs)
4490 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4492 // Next, load the argument into GPR or stack slot if needed.
4493 if (!NeedGPROrStack)
4495 else if (GPR_idx != NumGPRs) {
4496 // In the non-vararg case, this can only ever happen in the
4497 // presence of f32 array types, since otherwise we never run
4498 // out of FPRs before running out of GPRs.
4501 // Double values are always passed in a single GPR.
4502 if (Arg.getValueType() != MVT::f32) {
4503 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4505 // Non-array float values are extended and passed in a GPR.
4506 } else if (!Flags.isInConsecutiveRegs()) {
4507 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4508 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4510 // If we have an array of floats, we collect every odd element
4511 // together with its predecessor into one GPR.
4512 } else if (ArgOffset % PtrByteSize != 0) {
4514 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4515 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4516 if (!isLittleEndian)
4518 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4520 // The final element, if even, goes into the first half of a GPR.
4521 } else if (Flags.isInConsecutiveRegsLast()) {
4522 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4523 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4524 if (!isLittleEndian)
4525 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4526 DAG.getConstant(32, MVT::i32));
4528 // Non-final even elements are skipped; they will be handled
4529 // together the with subsequent argument on the next go-around.
4533 if (ArgVal.getNode())
4534 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4536 // Single-precision floating-point values are mapped to the
4537 // second (rightmost) word of the stack doubleword.
4538 if (Arg.getValueType() == MVT::f32 &&
4539 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4540 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4541 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4544 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4545 true, isTailCall, false, MemOpChains,
4546 TailCallArguments, dl);
4548 // When passing an array of floats, the array occupies consecutive
4549 // space in the argument area; only round up to the next doubleword
4550 // at the end of the array. Otherwise, each float takes 8 bytes.
4551 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4552 Flags.isInConsecutiveRegs()) ? 4 : 8;
4553 if (Flags.isInConsecutiveRegsLast())
4554 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4563 // These can be scalar arguments or elements of a vector array type
4564 // passed directly. The latter are used to implement ELFv2 homogenous
4565 // vector aggregates.
4567 // For a varargs call, named arguments go into VRs or on the stack as
4568 // usual; unnamed arguments always go to the stack or the corresponding
4569 // GPRs when within range. For now, we always put the value in both
4570 // locations (or even all three).
4572 // We could elide this store in the case where the object fits
4573 // entirely in R registers. Maybe later.
4574 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4575 MachinePointerInfo(), false, false, 0);
4576 MemOpChains.push_back(Store);
4577 if (VR_idx != NumVRs) {
4578 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4579 MachinePointerInfo(),
4580 false, false, false, 0);
4581 MemOpChains.push_back(Load.getValue(1));
4583 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4584 Arg.getSimpleValueType() == MVT::v2i64) ?
4585 VSRH[VR_idx] : VR[VR_idx];
4588 RegsToPass.push_back(std::make_pair(VReg, Load));
4591 for (unsigned i=0; i<16; i+=PtrByteSize) {
4592 if (GPR_idx == NumGPRs)
4594 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4595 DAG.getConstant(i, PtrVT));
4596 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4597 false, false, false, 0);
4598 MemOpChains.push_back(Load.getValue(1));
4599 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4604 // Non-varargs Altivec params go into VRs or on the stack.
4605 if (VR_idx != NumVRs) {
4606 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4607 Arg.getSimpleValueType() == MVT::v2i64) ?
4608 VSRH[VR_idx] : VR[VR_idx];
4611 RegsToPass.push_back(std::make_pair(VReg, Arg));
4613 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4614 true, isTailCall, true, MemOpChains,
4615 TailCallArguments, dl);
4622 assert(NumBytesActuallyUsed == ArgOffset);
4623 (void)NumBytesActuallyUsed;
4625 if (!MemOpChains.empty())
4626 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4628 // Check if this is an indirect call (MTCTR/BCTRL).
4629 // See PrepareCall() for more information about calls through function
4630 // pointers in the 64-bit SVR4 ABI.
4632 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4633 !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4634 // Load r2 into a virtual register and store it to the TOC save area.
4635 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4636 // TOC save area offset.
4637 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4638 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4639 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4640 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4642 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4643 // This does not mean the MTCTR instruction must use R12; it's easier
4644 // to model this as an extra parameter, so do that.
4646 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4649 // Build a sequence of copy-to-reg nodes chained together with token chain
4650 // and flag operands which copy the outgoing args into the appropriate regs.
4652 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4653 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4654 RegsToPass[i].second, InFlag);
4655 InFlag = Chain.getValue(1);
4659 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4660 FPOp, true, TailCallArguments);
4662 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4663 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4668 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4669 CallingConv::ID CallConv, bool isVarArg,
4671 const SmallVectorImpl<ISD::OutputArg> &Outs,
4672 const SmallVectorImpl<SDValue> &OutVals,
4673 const SmallVectorImpl<ISD::InputArg> &Ins,
4674 SDLoc dl, SelectionDAG &DAG,
4675 SmallVectorImpl<SDValue> &InVals) const {
4677 unsigned NumOps = Outs.size();
4679 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4680 bool isPPC64 = PtrVT == MVT::i64;
4681 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4683 MachineFunction &MF = DAG.getMachineFunction();
4685 // Mark this function as potentially containing a function that contains a
4686 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4687 // and restoring the callers stack pointer in this functions epilog. This is
4688 // done because by tail calling the called function might overwrite the value
4689 // in this function's (MF) stack pointer stack slot 0(SP).
4690 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4691 CallConv == CallingConv::Fast)
4692 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4694 // Count how many bytes are to be pushed on the stack, including the linkage
4695 // area, and parameter passing area. We start with 24/48 bytes, which is
4696 // prereserved space for [SP][CR][LR][3 x unused].
4697 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4699 unsigned NumBytes = LinkageSize;
4701 // Add up all the space actually used.
4702 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4703 // they all go in registers, but we must reserve stack space for them for
4704 // possible use by the caller. In varargs or 64-bit calls, parameters are
4705 // assigned stack space in order, with padding so Altivec parameters are
4707 unsigned nAltivecParamsAtEnd = 0;
4708 for (unsigned i = 0; i != NumOps; ++i) {
4709 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4710 EVT ArgVT = Outs[i].VT;
4711 // Varargs Altivec parameters are padded to a 16 byte boundary.
4712 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4713 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4714 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4715 if (!isVarArg && !isPPC64) {
4716 // Non-varargs Altivec parameters go after all the non-Altivec
4717 // parameters; handle those later so we know how much padding we need.
4718 nAltivecParamsAtEnd++;
4721 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4722 NumBytes = ((NumBytes+15)/16)*16;
4724 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4727 // Allow for Altivec parameters at the end, if needed.
4728 if (nAltivecParamsAtEnd) {
4729 NumBytes = ((NumBytes+15)/16)*16;
4730 NumBytes += 16*nAltivecParamsAtEnd;
4733 // The prolog code of the callee may store up to 8 GPR argument registers to
4734 // the stack, allowing va_start to index over them in memory if its varargs.
4735 // Because we cannot tell if this is needed on the caller side, we have to
4736 // conservatively assume that it is needed. As such, make sure we have at
4737 // least enough stack space for the caller to store the 8 GPRs.
4738 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4740 // Tail call needs the stack to be aligned.
4741 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4742 CallConv == CallingConv::Fast)
4743 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4745 // Calculate by how many bytes the stack has to be adjusted in case of tail
4746 // call optimization.
4747 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4749 // To protect arguments on the stack from being clobbered in a tail call,
4750 // force all the loads to happen before doing any other lowering.
4752 Chain = DAG.getStackArgumentTokenFactor(Chain);
4754 // Adjust the stack pointer for the new arguments...
4755 // These operations are automatically eliminated by the prolog/epilog pass
4756 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4758 SDValue CallSeqStart = Chain;
4760 // Load the return address and frame pointer so it can be move somewhere else
4763 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4766 // Set up a copy of the stack pointer for use loading and storing any
4767 // arguments that may not fit in the registers available for argument
4771 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4773 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4775 // Figure out which arguments are going to go in registers, and which in
4776 // memory. Also, if this is a vararg function, floating point operations
4777 // must be stored to our stack, and loaded into integer regs as well, if
4778 // any integer regs are available for argument passing.
4779 unsigned ArgOffset = LinkageSize;
4780 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4782 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4783 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4784 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4786 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4787 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4788 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4790 static const MCPhysReg *FPR = GetFPR();
4792 static const MCPhysReg VR[] = {
4793 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4794 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4796 const unsigned NumGPRs = array_lengthof(GPR_32);
4797 const unsigned NumFPRs = 13;
4798 const unsigned NumVRs = array_lengthof(VR);
4800 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4802 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4803 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4805 SmallVector<SDValue, 8> MemOpChains;
4806 for (unsigned i = 0; i != NumOps; ++i) {
4807 SDValue Arg = OutVals[i];
4808 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4810 // PtrOff will be used to store the current argument to the stack if a
4811 // register cannot be found for it.
4814 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4816 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4818 // On PPC64, promote integers to 64-bit values.
4819 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4820 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4821 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4822 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4825 // FIXME memcpy is used way more than necessary. Correctness first.
4826 // Note: "by value" is code for passing a structure by value, not
4828 if (Flags.isByVal()) {
4829 unsigned Size = Flags.getByValSize();
4830 // Very small objects are passed right-justified. Everything else is
4831 // passed left-justified.
4832 if (Size==1 || Size==2) {
4833 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4834 if (GPR_idx != NumGPRs) {
4835 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4836 MachinePointerInfo(), VT,
4837 false, false, false, 0);
4838 MemOpChains.push_back(Load.getValue(1));
4839 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4841 ArgOffset += PtrByteSize;
4843 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4844 PtrOff.getValueType());
4845 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4846 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4849 ArgOffset += PtrByteSize;
4853 // Copy entire object into memory. There are cases where gcc-generated
4854 // code assumes it is there, even if it could be put entirely into
4855 // registers. (This is not what the doc says.)
4856 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4860 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4861 // copy the pieces of the object that fit into registers from the
4862 // parameter save area.
4863 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4864 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4865 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4866 if (GPR_idx != NumGPRs) {
4867 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4868 MachinePointerInfo(),
4869 false, false, false, 0);
4870 MemOpChains.push_back(Load.getValue(1));
4871 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4872 ArgOffset += PtrByteSize;
4874 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4881 switch (Arg.getSimpleValueType().SimpleTy) {
4882 default: llvm_unreachable("Unexpected ValueType for argument!");
4886 if (GPR_idx != NumGPRs) {
4887 if (Arg.getValueType() == MVT::i1)
4888 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4890 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4892 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4893 isPPC64, isTailCall, false, MemOpChains,
4894 TailCallArguments, dl);
4896 ArgOffset += PtrByteSize;
4900 if (FPR_idx != NumFPRs) {
4901 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4904 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4905 MachinePointerInfo(), false, false, 0);
4906 MemOpChains.push_back(Store);
4908 // Float varargs are always shadowed in available integer registers
4909 if (GPR_idx != NumGPRs) {
4910 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4911 MachinePointerInfo(), false, false,
4913 MemOpChains.push_back(Load.getValue(1));
4914 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4916 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4917 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4918 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4919 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4920 MachinePointerInfo(),
4921 false, false, false, 0);
4922 MemOpChains.push_back(Load.getValue(1));
4923 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4926 // If we have any FPRs remaining, we may also have GPRs remaining.
4927 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4929 if (GPR_idx != NumGPRs)
4931 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4932 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4936 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4937 isPPC64, isTailCall, false, MemOpChains,
4938 TailCallArguments, dl);
4942 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4949 // These go aligned on the stack, or in the corresponding R registers
4950 // when within range. The Darwin PPC ABI doc claims they also go in
4951 // V registers; in fact gcc does this only for arguments that are
4952 // prototyped, not for those that match the ... We do it for all
4953 // arguments, seems to work.
4954 while (ArgOffset % 16 !=0) {
4955 ArgOffset += PtrByteSize;
4956 if (GPR_idx != NumGPRs)
4959 // We could elide this store in the case where the object fits
4960 // entirely in R registers. Maybe later.
4961 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4962 DAG.getConstant(ArgOffset, PtrVT));
4963 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4964 MachinePointerInfo(), false, false, 0);
4965 MemOpChains.push_back(Store);
4966 if (VR_idx != NumVRs) {
4967 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4968 MachinePointerInfo(),
4969 false, false, false, 0);
4970 MemOpChains.push_back(Load.getValue(1));
4971 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4974 for (unsigned i=0; i<16; i+=PtrByteSize) {
4975 if (GPR_idx == NumGPRs)
4977 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4978 DAG.getConstant(i, PtrVT));
4979 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4980 false, false, false, 0);
4981 MemOpChains.push_back(Load.getValue(1));
4982 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4987 // Non-varargs Altivec params generally go in registers, but have
4988 // stack space allocated at the end.
4989 if (VR_idx != NumVRs) {
4990 // Doesn't have GPR space allocated.
4991 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4992 } else if (nAltivecParamsAtEnd==0) {
4993 // We are emitting Altivec params in order.
4994 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4995 isPPC64, isTailCall, true, MemOpChains,
4996 TailCallArguments, dl);
5002 // If all Altivec parameters fit in registers, as they usually do,
5003 // they get stack space following the non-Altivec parameters. We
5004 // don't track this here because nobody below needs it.
5005 // If there are more Altivec parameters than fit in registers emit
5007 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5009 // Offset is aligned; skip 1st 12 params which go in V registers.
5010 ArgOffset = ((ArgOffset+15)/16)*16;
5012 for (unsigned i = 0; i != NumOps; ++i) {
5013 SDValue Arg = OutVals[i];
5014 EVT ArgType = Outs[i].VT;
5015 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5016 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5019 // We are emitting Altivec params in order.
5020 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5021 isPPC64, isTailCall, true, MemOpChains,
5022 TailCallArguments, dl);
5029 if (!MemOpChains.empty())
5030 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5032 // On Darwin, R12 must contain the address of an indirect callee. This does
5033 // not mean the MTCTR instruction must use R12; it's easier to model this as
5034 // an extra parameter, so do that.
5036 !dyn_cast<GlobalAddressSDNode>(Callee) &&
5037 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
5038 !isBLACompatibleAddress(Callee, DAG))
5039 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5040 PPC::R12), Callee));
5042 // Build a sequence of copy-to-reg nodes chained together with token chain
5043 // and flag operands which copy the outgoing args into the appropriate regs.
5045 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5046 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5047 RegsToPass[i].second, InFlag);
5048 InFlag = Chain.getValue(1);
5052 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5053 FPOp, true, TailCallArguments);
5055 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5056 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5061 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5062 MachineFunction &MF, bool isVarArg,
5063 const SmallVectorImpl<ISD::OutputArg> &Outs,
5064 LLVMContext &Context) const {
5065 SmallVector<CCValAssign, 16> RVLocs;
5066 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5067 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5071 PPCTargetLowering::LowerReturn(SDValue Chain,
5072 CallingConv::ID CallConv, bool isVarArg,
5073 const SmallVectorImpl<ISD::OutputArg> &Outs,
5074 const SmallVectorImpl<SDValue> &OutVals,
5075 SDLoc dl, SelectionDAG &DAG) const {
5077 SmallVector<CCValAssign, 16> RVLocs;
5078 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5080 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5083 SmallVector<SDValue, 4> RetOps(1, Chain);
5085 // Copy the result values into the output registers.
5086 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5087 CCValAssign &VA = RVLocs[i];
5088 assert(VA.isRegLoc() && "Can only return in registers!");
5090 SDValue Arg = OutVals[i];
5092 switch (VA.getLocInfo()) {
5093 default: llvm_unreachable("Unknown loc info!");
5094 case CCValAssign::Full: break;
5095 case CCValAssign::AExt:
5096 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5098 case CCValAssign::ZExt:
5099 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5101 case CCValAssign::SExt:
5102 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5106 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5107 Flag = Chain.getValue(1);
5108 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5111 RetOps[0] = Chain; // Update chain.
5113 // Add the flag if we have it.
5115 RetOps.push_back(Flag);
5117 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5120 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5121 const PPCSubtarget &Subtarget) const {
5122 // When we pop the dynamic allocation we need to restore the SP link.
5125 // Get the corect type for pointers.
5126 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5128 // Construct the stack pointer operand.
5129 bool isPPC64 = Subtarget.isPPC64();
5130 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5131 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5133 // Get the operands for the STACKRESTORE.
5134 SDValue Chain = Op.getOperand(0);
5135 SDValue SaveSP = Op.getOperand(1);
5137 // Load the old link SP.
5138 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5139 MachinePointerInfo(),
5140 false, false, false, 0);
5142 // Restore the stack pointer.
5143 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5145 // Store the old link SP.
5146 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5153 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5154 MachineFunction &MF = DAG.getMachineFunction();
5155 bool isPPC64 = Subtarget.isPPC64();
5156 bool isDarwinABI = Subtarget.isDarwinABI();
5157 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5159 // Get current frame pointer save index. The users of this index will be
5160 // primarily DYNALLOC instructions.
5161 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5162 int RASI = FI->getReturnAddrSaveIndex();
5164 // If the frame pointer save index hasn't been defined yet.
5166 // Find out what the fix offset of the frame pointer save area.
5167 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5168 // Allocate the frame index for frame pointer save area.
5169 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
5171 FI->setReturnAddrSaveIndex(RASI);
5173 return DAG.getFrameIndex(RASI, PtrVT);
5177 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5178 MachineFunction &MF = DAG.getMachineFunction();
5179 bool isPPC64 = Subtarget.isPPC64();
5180 bool isDarwinABI = Subtarget.isDarwinABI();
5181 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5183 // Get current frame pointer save index. The users of this index will be
5184 // primarily DYNALLOC instructions.
5185 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5186 int FPSI = FI->getFramePointerSaveIndex();
5188 // If the frame pointer save index hasn't been defined yet.
5190 // Find out what the fix offset of the frame pointer save area.
5191 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5194 // Allocate the frame index for frame pointer save area.
5195 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5197 FI->setFramePointerSaveIndex(FPSI);
5199 return DAG.getFrameIndex(FPSI, PtrVT);
5202 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5204 const PPCSubtarget &Subtarget) const {
5206 SDValue Chain = Op.getOperand(0);
5207 SDValue Size = Op.getOperand(1);
5210 // Get the corect type for pointers.
5211 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5213 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5214 DAG.getConstant(0, PtrVT), Size);
5215 // Construct a node for the frame pointer save index.
5216 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5217 // Build a DYNALLOC node.
5218 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5219 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5220 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5223 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5224 SelectionDAG &DAG) const {
5226 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5227 DAG.getVTList(MVT::i32, MVT::Other),
5228 Op.getOperand(0), Op.getOperand(1));
5231 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5232 SelectionDAG &DAG) const {
5234 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5235 Op.getOperand(0), Op.getOperand(1));
5238 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5239 assert(Op.getValueType() == MVT::i1 &&
5240 "Custom lowering only for i1 loads");
5242 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5245 LoadSDNode *LD = cast<LoadSDNode>(Op);
5247 SDValue Chain = LD->getChain();
5248 SDValue BasePtr = LD->getBasePtr();
5249 MachineMemOperand *MMO = LD->getMemOperand();
5251 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5252 BasePtr, MVT::i8, MMO);
5253 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5255 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5256 return DAG.getMergeValues(Ops, dl);
5259 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5260 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5261 "Custom lowering only for i1 stores");
5263 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5266 StoreSDNode *ST = cast<StoreSDNode>(Op);
5268 SDValue Chain = ST->getChain();
5269 SDValue BasePtr = ST->getBasePtr();
5270 SDValue Value = ST->getValue();
5271 MachineMemOperand *MMO = ST->getMemOperand();
5273 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5274 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5277 // FIXME: Remove this once the ANDI glue bug is fixed:
5278 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5279 assert(Op.getValueType() == MVT::i1 &&
5280 "Custom lowering only for i1 results");
5283 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5287 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5289 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5290 // Not FP? Not a fsel.
5291 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5292 !Op.getOperand(2).getValueType().isFloatingPoint())
5295 // We might be able to do better than this under some circumstances, but in
5296 // general, fsel-based lowering of select is a finite-math-only optimization.
5297 // For more information, see section F.3 of the 2.06 ISA specification.
5298 if (!DAG.getTarget().Options.NoInfsFPMath ||
5299 !DAG.getTarget().Options.NoNaNsFPMath)
5302 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5304 EVT ResVT = Op.getValueType();
5305 EVT CmpVT = Op.getOperand(0).getValueType();
5306 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5307 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5310 // If the RHS of the comparison is a 0.0, we don't need to do the
5311 // subtraction at all.
5313 if (isFloatingPointZero(RHS))
5315 default: break; // SETUO etc aren't handled by fsel.
5319 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5320 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5321 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5322 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5323 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5324 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5325 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5328 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5331 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5332 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5333 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5336 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5339 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5340 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5341 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5342 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5347 default: break; // SETUO etc aren't handled by fsel.
5351 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5352 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5353 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5354 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5355 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5356 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5357 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5358 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5361 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5362 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5363 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5364 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5367 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5368 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5369 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5370 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5373 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5374 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5375 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5376 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5379 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5380 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5381 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5382 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5387 // FIXME: Split this code up when LegalizeDAGTypes lands.
5388 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5390 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5391 SDValue Src = Op.getOperand(0);
5392 if (Src.getValueType() == MVT::f32)
5393 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5396 switch (Op.getSimpleValueType().SimpleTy) {
5397 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5399 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5400 (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5405 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5406 "i64 FP_TO_UINT is supported only with FPCVT");
5407 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5413 // Convert the FP value to an int value through memory.
5414 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5415 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5416 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5417 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5418 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5420 // Emit a store to the stack slot.
5423 MachineFunction &MF = DAG.getMachineFunction();
5424 MachineMemOperand *MMO =
5425 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5426 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5427 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5428 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5430 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5431 MPI, false, false, 0);
5433 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5435 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5436 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5437 DAG.getConstant(4, FIPtr.getValueType()));
5438 MPI = MachinePointerInfo();
5441 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5442 false, false, false, 0);
5445 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5446 SelectionDAG &DAG) const {
5448 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5449 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5452 if (Op.getOperand(0).getValueType() == MVT::i1)
5453 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5454 DAG.getConstantFP(1.0, Op.getValueType()),
5455 DAG.getConstantFP(0.0, Op.getValueType()));
5457 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5458 "UINT_TO_FP is supported only with FPCVT");
5460 // If we have FCFIDS, then use it when converting to single-precision.
5461 // Otherwise, convert to double-precision and then round.
5462 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5463 (Op.getOpcode() == ISD::UINT_TO_FP ?
5464 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5465 (Op.getOpcode() == ISD::UINT_TO_FP ?
5466 PPCISD::FCFIDU : PPCISD::FCFID);
5467 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5468 MVT::f32 : MVT::f64;
5470 if (Op.getOperand(0).getValueType() == MVT::i64) {
5471 SDValue SINT = Op.getOperand(0);
5472 // When converting to single-precision, we actually need to convert
5473 // to double-precision first and then round to single-precision.
5474 // To avoid double-rounding effects during that operation, we have
5475 // to prepare the input operand. Bits that might be truncated when
5476 // converting to double-precision are replaced by a bit that won't
5477 // be lost at this stage, but is below the single-precision rounding
5480 // However, if -enable-unsafe-fp-math is in effect, accept double
5481 // rounding to avoid the extra overhead.
5482 if (Op.getValueType() == MVT::f32 &&
5483 !Subtarget.hasFPCVT() &&
5484 !DAG.getTarget().Options.UnsafeFPMath) {
5486 // Twiddle input to make sure the low 11 bits are zero. (If this
5487 // is the case, we are guaranteed the value will fit into the 53 bit
5488 // mantissa of an IEEE double-precision value without rounding.)
5489 // If any of those low 11 bits were not zero originally, make sure
5490 // bit 12 (value 2048) is set instead, so that the final rounding
5491 // to single-precision gets the correct result.
5492 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5493 SINT, DAG.getConstant(2047, MVT::i64));
5494 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5495 Round, DAG.getConstant(2047, MVT::i64));
5496 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5497 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5498 Round, DAG.getConstant(-2048, MVT::i64));
5500 // However, we cannot use that value unconditionally: if the magnitude
5501 // of the input value is small, the bit-twiddling we did above might
5502 // end up visibly changing the output. Fortunately, in that case, we
5503 // don't need to twiddle bits since the original input will convert
5504 // exactly to double-precision floating-point already. Therefore,
5505 // construct a conditional to use the original value if the top 11
5506 // bits are all sign-bit copies, and use the rounded value computed
5508 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5509 SINT, DAG.getConstant(53, MVT::i32));
5510 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5511 Cond, DAG.getConstant(1, MVT::i64));
5512 Cond = DAG.getSetCC(dl, MVT::i32,
5513 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5515 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5518 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5519 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5521 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5522 FP = DAG.getNode(ISD::FP_ROUND, dl,
5523 MVT::f32, FP, DAG.getIntPtrConstant(0));
5527 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5528 "Unhandled INT_TO_FP type in custom expander!");
5529 // Since we only generate this in 64-bit mode, we can take advantage of
5530 // 64-bit registers. In particular, sign extend the input value into the
5531 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5532 // then lfd it and fcfid it.
5533 MachineFunction &MF = DAG.getMachineFunction();
5534 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5535 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5538 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5539 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5540 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5542 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5543 MachinePointerInfo::getFixedStack(FrameIdx),
5546 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5547 "Expected an i32 store");
5548 MachineMemOperand *MMO =
5549 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5550 MachineMemOperand::MOLoad, 4, 4);
5551 SDValue Ops[] = { Store, FIdx };
5552 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5553 PPCISD::LFIWZX : PPCISD::LFIWAX,
5554 dl, DAG.getVTList(MVT::f64, MVT::Other),
5555 Ops, MVT::i32, MMO);
5557 assert(Subtarget.isPPC64() &&
5558 "i32->FP without LFIWAX supported only on PPC64");
5560 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5561 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5563 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5566 // STD the extended value into the stack slot.
5567 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5568 MachinePointerInfo::getFixedStack(FrameIdx),
5571 // Load the value as a double.
5572 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5573 MachinePointerInfo::getFixedStack(FrameIdx),
5574 false, false, false, 0);
5577 // FCFID it and return it.
5578 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5579 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5580 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5584 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5585 SelectionDAG &DAG) const {
5588 The rounding mode is in bits 30:31 of FPSR, and has the following
5595 FLT_ROUNDS, on the other hand, expects the following:
5602 To perform the conversion, we do:
5603 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5606 MachineFunction &MF = DAG.getMachineFunction();
5607 EVT VT = Op.getValueType();
5608 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5610 // Save FP Control Word to register
5612 MVT::f64, // return register
5613 MVT::Glue // unused in this context
5615 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5617 // Save FP register to stack slot
5618 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5619 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5620 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5621 StackSlot, MachinePointerInfo(), false, false,0);
5623 // Load FP Control Word from low 32 bits of stack slot.
5624 SDValue Four = DAG.getConstant(4, PtrVT);
5625 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5626 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5627 false, false, false, 0);
5629 // Transform as necessary
5631 DAG.getNode(ISD::AND, dl, MVT::i32,
5632 CWD, DAG.getConstant(3, MVT::i32));
5634 DAG.getNode(ISD::SRL, dl, MVT::i32,
5635 DAG.getNode(ISD::AND, dl, MVT::i32,
5636 DAG.getNode(ISD::XOR, dl, MVT::i32,
5637 CWD, DAG.getConstant(3, MVT::i32)),
5638 DAG.getConstant(3, MVT::i32)),
5639 DAG.getConstant(1, MVT::i32));
5642 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5644 return DAG.getNode((VT.getSizeInBits() < 16 ?
5645 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5648 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5649 EVT VT = Op.getValueType();
5650 unsigned BitWidth = VT.getSizeInBits();
5652 assert(Op.getNumOperands() == 3 &&
5653 VT == Op.getOperand(1).getValueType() &&
5656 // Expand into a bunch of logical ops. Note that these ops
5657 // depend on the PPC behavior for oversized shift amounts.
5658 SDValue Lo = Op.getOperand(0);
5659 SDValue Hi = Op.getOperand(1);
5660 SDValue Amt = Op.getOperand(2);
5661 EVT AmtVT = Amt.getValueType();
5663 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5664 DAG.getConstant(BitWidth, AmtVT), Amt);
5665 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5666 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5667 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5668 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5669 DAG.getConstant(-BitWidth, AmtVT));
5670 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5671 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5672 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5673 SDValue OutOps[] = { OutLo, OutHi };
5674 return DAG.getMergeValues(OutOps, dl);
5677 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5678 EVT VT = Op.getValueType();
5680 unsigned BitWidth = VT.getSizeInBits();
5681 assert(Op.getNumOperands() == 3 &&
5682 VT == Op.getOperand(1).getValueType() &&
5685 // Expand into a bunch of logical ops. Note that these ops
5686 // depend on the PPC behavior for oversized shift amounts.
5687 SDValue Lo = Op.getOperand(0);
5688 SDValue Hi = Op.getOperand(1);
5689 SDValue Amt = Op.getOperand(2);
5690 EVT AmtVT = Amt.getValueType();
5692 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5693 DAG.getConstant(BitWidth, AmtVT), Amt);
5694 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5695 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5696 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5697 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5698 DAG.getConstant(-BitWidth, AmtVT));
5699 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5700 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5701 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5702 SDValue OutOps[] = { OutLo, OutHi };
5703 return DAG.getMergeValues(OutOps, dl);
5706 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5708 EVT VT = Op.getValueType();
5709 unsigned BitWidth = VT.getSizeInBits();
5710 assert(Op.getNumOperands() == 3 &&
5711 VT == Op.getOperand(1).getValueType() &&
5714 // Expand into a bunch of logical ops, followed by a select_cc.
5715 SDValue Lo = Op.getOperand(0);
5716 SDValue Hi = Op.getOperand(1);
5717 SDValue Amt = Op.getOperand(2);
5718 EVT AmtVT = Amt.getValueType();
5720 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5721 DAG.getConstant(BitWidth, AmtVT), Amt);
5722 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5723 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5724 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5725 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5726 DAG.getConstant(-BitWidth, AmtVT));
5727 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5728 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5729 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5730 Tmp4, Tmp6, ISD::SETLE);
5731 SDValue OutOps[] = { OutLo, OutHi };
5732 return DAG.getMergeValues(OutOps, dl);
5735 //===----------------------------------------------------------------------===//
5736 // Vector related lowering.
5739 /// BuildSplatI - Build a canonical splati of Val with an element size of
5740 /// SplatSize. Cast the result to VT.
5741 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5742 SelectionDAG &DAG, SDLoc dl) {
5743 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5745 static const EVT VTys[] = { // canonical VT to use for each size.
5746 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5749 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5751 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5755 EVT CanonicalVT = VTys[SplatSize-1];
5757 // Build a canonical splat for this value.
5758 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5759 SmallVector<SDValue, 8> Ops;
5760 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5761 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5762 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5765 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5766 /// specified intrinsic ID.
5767 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5768 SelectionDAG &DAG, SDLoc dl,
5769 EVT DestVT = MVT::Other) {
5770 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5771 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5772 DAG.getConstant(IID, MVT::i32), Op);
5775 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5776 /// specified intrinsic ID.
5777 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5778 SelectionDAG &DAG, SDLoc dl,
5779 EVT DestVT = MVT::Other) {
5780 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5781 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5782 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5785 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5786 /// specified intrinsic ID.
5787 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5788 SDValue Op2, SelectionDAG &DAG,
5789 SDLoc dl, EVT DestVT = MVT::Other) {
5790 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5791 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5792 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5796 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5797 /// amount. The result has the specified value type.
5798 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5799 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5800 // Force LHS/RHS to be the right type.
5801 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5802 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5805 for (unsigned i = 0; i != 16; ++i)
5807 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5808 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5811 // If this is a case we can't handle, return null and let the default
5812 // expansion code take care of it. If we CAN select this case, and if it
5813 // selects to a single instruction, return Op. Otherwise, if we can codegen
5814 // this case more efficiently than a constant pool load, lower it to the
5815 // sequence of ops that should be used.
5816 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5817 SelectionDAG &DAG) const {
5819 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5820 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5822 // Check if this is a splat of a constant value.
5823 APInt APSplatBits, APSplatUndef;
5824 unsigned SplatBitSize;
5826 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5827 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5830 unsigned SplatBits = APSplatBits.getZExtValue();
5831 unsigned SplatUndef = APSplatUndef.getZExtValue();
5832 unsigned SplatSize = SplatBitSize / 8;
5834 // First, handle single instruction cases.
5837 if (SplatBits == 0) {
5838 // Canonicalize all zero vectors to be v4i32.
5839 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5840 SDValue Z = DAG.getConstant(0, MVT::i32);
5841 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5842 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5847 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5848 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5850 if (SextVal >= -16 && SextVal <= 15)
5851 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5854 // Two instruction sequences.
5856 // If this value is in the range [-32,30] and is even, use:
5857 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5858 // If this value is in the range [17,31] and is odd, use:
5859 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5860 // If this value is in the range [-31,-17] and is odd, use:
5861 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5862 // Note the last two are three-instruction sequences.
5863 if (SextVal >= -32 && SextVal <= 31) {
5864 // To avoid having these optimizations undone by constant folding,
5865 // we convert to a pseudo that will be expanded later into one of
5867 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5868 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5869 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5870 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5871 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5872 if (VT == Op.getValueType())
5875 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5878 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5879 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5881 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5882 // Make -1 and vspltisw -1:
5883 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5885 // Make the VSLW intrinsic, computing 0x8000_0000.
5886 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5889 // xor by OnesV to invert it.
5890 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5891 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5894 // The remaining cases assume either big endian element order or
5895 // a splat-size that equates to the element size of the vector
5896 // to be built. An example that doesn't work for little endian is
5897 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5898 // and a vector element size of 16 bits. The code below will
5899 // produce the vector in big endian element order, which for little
5900 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5902 // For now, just avoid these optimizations in that case.
5903 // FIXME: Develop correct optimizations for LE with mismatched
5904 // splat and element sizes.
5906 if (Subtarget.isLittleEndian() &&
5907 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5910 // Check to see if this is a wide variety of vsplti*, binop self cases.
5911 static const signed char SplatCsts[] = {
5912 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5913 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5916 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5917 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5918 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5919 int i = SplatCsts[idx];
5921 // Figure out what shift amount will be used by altivec if shifted by i in
5923 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5925 // vsplti + shl self.
5926 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5927 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5928 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5929 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5930 Intrinsic::ppc_altivec_vslw
5932 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5933 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5936 // vsplti + srl self.
5937 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5938 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5939 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5940 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5941 Intrinsic::ppc_altivec_vsrw
5943 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5944 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5947 // vsplti + sra self.
5948 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5949 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5950 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5951 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5952 Intrinsic::ppc_altivec_vsraw
5954 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5955 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5958 // vsplti + rol self.
5959 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5960 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5961 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5962 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5963 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5964 Intrinsic::ppc_altivec_vrlw
5966 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5967 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5970 // t = vsplti c, result = vsldoi t, t, 1
5971 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5972 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5973 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5975 // t = vsplti c, result = vsldoi t, t, 2
5976 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5977 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5978 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5980 // t = vsplti c, result = vsldoi t, t, 3
5981 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5982 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5983 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5990 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5991 /// the specified operations to build the shuffle.
5992 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5993 SDValue RHS, SelectionDAG &DAG,
5995 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5996 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5997 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6000 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6012 if (OpNum == OP_COPY) {
6013 if (LHSID == (1*9+2)*9+3) return LHS;
6014 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6018 SDValue OpLHS, OpRHS;
6019 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6020 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6024 default: llvm_unreachable("Unknown i32 permute!");
6026 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6027 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6028 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6029 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6032 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6033 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6034 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6035 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6038 for (unsigned i = 0; i != 16; ++i)
6039 ShufIdxs[i] = (i&3)+0;
6042 for (unsigned i = 0; i != 16; ++i)
6043 ShufIdxs[i] = (i&3)+4;
6046 for (unsigned i = 0; i != 16; ++i)
6047 ShufIdxs[i] = (i&3)+8;
6050 for (unsigned i = 0; i != 16; ++i)
6051 ShufIdxs[i] = (i&3)+12;
6054 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6056 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6058 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6060 EVT VT = OpLHS.getValueType();
6061 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6062 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6063 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6064 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6067 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6068 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6069 /// return the code it can be lowered into. Worst case, it can always be
6070 /// lowered into a vperm.
6071 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6072 SelectionDAG &DAG) const {
6074 SDValue V1 = Op.getOperand(0);
6075 SDValue V2 = Op.getOperand(1);
6076 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6077 EVT VT = Op.getValueType();
6078 bool isLittleEndian = Subtarget.isLittleEndian();
6080 // Cases that are handled by instructions that take permute immediates
6081 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6082 // selected by the instruction selector.
6083 if (V2.getOpcode() == ISD::UNDEF) {
6084 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6085 PPC::isSplatShuffleMask(SVOp, 2) ||
6086 PPC::isSplatShuffleMask(SVOp, 4) ||
6087 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6088 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6089 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6090 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6091 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6092 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6093 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6094 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6095 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6100 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6101 // and produce a fixed permutation. If any of these match, do not lower to
6103 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6104 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6105 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6106 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6107 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6108 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6109 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6110 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6111 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6112 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6115 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6116 // perfect shuffle table to emit an optimal matching sequence.
6117 ArrayRef<int> PermMask = SVOp->getMask();
6119 unsigned PFIndexes[4];
6120 bool isFourElementShuffle = true;
6121 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6122 unsigned EltNo = 8; // Start out undef.
6123 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6124 if (PermMask[i*4+j] < 0)
6125 continue; // Undef, ignore it.
6127 unsigned ByteSource = PermMask[i*4+j];
6128 if ((ByteSource & 3) != j) {
6129 isFourElementShuffle = false;
6134 EltNo = ByteSource/4;
6135 } else if (EltNo != ByteSource/4) {
6136 isFourElementShuffle = false;
6140 PFIndexes[i] = EltNo;
6143 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6144 // perfect shuffle vector to determine if it is cost effective to do this as
6145 // discrete instructions, or whether we should use a vperm.
6146 // For now, we skip this for little endian until such time as we have a
6147 // little-endian perfect shuffle table.
6148 if (isFourElementShuffle && !isLittleEndian) {
6149 // Compute the index in the perfect shuffle table.
6150 unsigned PFTableIndex =
6151 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6153 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6154 unsigned Cost = (PFEntry >> 30);
6156 // Determining when to avoid vperm is tricky. Many things affect the cost
6157 // of vperm, particularly how many times the perm mask needs to be computed.
6158 // For example, if the perm mask can be hoisted out of a loop or is already
6159 // used (perhaps because there are multiple permutes with the same shuffle
6160 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6161 // the loop requires an extra register.
6163 // As a compromise, we only emit discrete instructions if the shuffle can be
6164 // generated in 3 or fewer operations. When we have loop information
6165 // available, if this block is within a loop, we should avoid using vperm
6166 // for 3-operation perms and use a constant pool load instead.
6168 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6171 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6172 // vector that will get spilled to the constant pool.
6173 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6175 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6176 // that it is in input element units, not in bytes. Convert now.
6178 // For little endian, the order of the input vectors is reversed, and
6179 // the permutation mask is complemented with respect to 31. This is
6180 // necessary to produce proper semantics with the big-endian-biased vperm
6182 EVT EltVT = V1.getValueType().getVectorElementType();
6183 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6185 SmallVector<SDValue, 16> ResultMask;
6186 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6187 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6189 for (unsigned j = 0; j != BytesPerElement; ++j)
6191 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6194 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6198 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6201 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6204 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6208 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6209 /// altivec comparison. If it is, return true and fill in Opc/isDot with
6210 /// information about the intrinsic.
6211 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6213 unsigned IntrinsicID =
6214 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6217 switch (IntrinsicID) {
6218 default: return false;
6219 // Comparison predicates.
6220 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
6221 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6222 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
6223 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
6224 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6225 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6226 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6227 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6228 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6229 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6230 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6231 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6232 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6234 // Normal Comparisons.
6235 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
6236 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
6237 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
6238 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
6239 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
6240 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
6241 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
6242 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
6243 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
6244 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
6245 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
6246 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
6247 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
6252 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6253 /// lower, do it, otherwise return null.
6254 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6255 SelectionDAG &DAG) const {
6256 // If this is a lowered altivec predicate compare, CompareOpc is set to the
6257 // opcode number of the comparison.
6261 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6262 return SDValue(); // Don't custom lower most intrinsics.
6264 // If this is a non-dot comparison, make the VCMP node and we are done.
6266 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6267 Op.getOperand(1), Op.getOperand(2),
6268 DAG.getConstant(CompareOpc, MVT::i32));
6269 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6272 // Create the PPCISD altivec 'dot' comparison node.
6274 Op.getOperand(2), // LHS
6275 Op.getOperand(3), // RHS
6276 DAG.getConstant(CompareOpc, MVT::i32)
6278 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6279 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6281 // Now that we have the comparison, emit a copy from the CR to a GPR.
6282 // This is flagged to the above dot comparison.
6283 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6284 DAG.getRegister(PPC::CR6, MVT::i32),
6285 CompNode.getValue(1));
6287 // Unpack the result based on how the target uses it.
6288 unsigned BitNo; // Bit # of CR6.
6289 bool InvertBit; // Invert result?
6290 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6291 default: // Can't happen, don't crash on invalid number though.
6292 case 0: // Return the value of the EQ bit of CR6.
6293 BitNo = 0; InvertBit = false;
6295 case 1: // Return the inverted value of the EQ bit of CR6.
6296 BitNo = 0; InvertBit = true;
6298 case 2: // Return the value of the LT bit of CR6.
6299 BitNo = 2; InvertBit = false;
6301 case 3: // Return the inverted value of the LT bit of CR6.
6302 BitNo = 2; InvertBit = true;
6306 // Shift the bit into the low position.
6307 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6308 DAG.getConstant(8-(3-BitNo), MVT::i32));
6310 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6311 DAG.getConstant(1, MVT::i32));
6313 // If we are supposed to, toggle the bit.
6315 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6316 DAG.getConstant(1, MVT::i32));
6320 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6321 SelectionDAG &DAG) const {
6323 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6324 // instructions), but for smaller types, we need to first extend up to v2i32
6325 // before doing going farther.
6326 if (Op.getValueType() == MVT::v2i64) {
6327 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6328 if (ExtVT != MVT::v2i32) {
6329 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6330 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6331 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6332 ExtVT.getVectorElementType(), 4)));
6333 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6334 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6335 DAG.getValueType(MVT::v2i32));
6344 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6345 SelectionDAG &DAG) const {
6347 // Create a stack slot that is 16-byte aligned.
6348 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6349 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6350 EVT PtrVT = getPointerTy();
6351 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6353 // Store the input value into Value#0 of the stack slot.
6354 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6355 Op.getOperand(0), FIdx, MachinePointerInfo(),
6358 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6359 false, false, false, 0);
6362 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6364 if (Op.getValueType() == MVT::v4i32) {
6365 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6367 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6368 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6370 SDValue RHSSwap = // = vrlw RHS, 16
6371 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6373 // Shrinkify inputs to v8i16.
6374 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6375 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6376 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6378 // Low parts multiplied together, generating 32-bit results (we ignore the
6380 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6381 LHS, RHS, DAG, dl, MVT::v4i32);
6383 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6384 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6385 // Shift the high parts up 16 bits.
6386 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6388 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6389 } else if (Op.getValueType() == MVT::v8i16) {
6390 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6392 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6394 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6395 LHS, RHS, Zero, DAG, dl);
6396 } else if (Op.getValueType() == MVT::v16i8) {
6397 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6398 bool isLittleEndian = Subtarget.isLittleEndian();
6400 // Multiply the even 8-bit parts, producing 16-bit sums.
6401 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6402 LHS, RHS, DAG, dl, MVT::v8i16);
6403 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6405 // Multiply the odd 8-bit parts, producing 16-bit sums.
6406 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6407 LHS, RHS, DAG, dl, MVT::v8i16);
6408 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6410 // Merge the results together. Because vmuleub and vmuloub are
6411 // instructions with a big-endian bias, we must reverse the
6412 // element numbering and reverse the meaning of "odd" and "even"
6413 // when generating little endian code.
6415 for (unsigned i = 0; i != 8; ++i) {
6416 if (isLittleEndian) {
6418 Ops[i*2+1] = 2*i+16;
6421 Ops[i*2+1] = 2*i+1+16;
6425 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6427 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6429 llvm_unreachable("Unknown mul to lower!");
6433 /// LowerOperation - Provide custom lowering hooks for some operations.
6435 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6436 switch (Op.getOpcode()) {
6437 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6438 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6439 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6440 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6441 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6442 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6443 case ISD::SETCC: return LowerSETCC(Op, DAG);
6444 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6445 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6447 return LowerVASTART(Op, DAG, Subtarget);
6450 return LowerVAARG(Op, DAG, Subtarget);
6453 return LowerVACOPY(Op, DAG, Subtarget);
6455 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
6456 case ISD::DYNAMIC_STACKALLOC:
6457 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6459 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6460 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6462 case ISD::LOAD: return LowerLOAD(Op, DAG);
6463 case ISD::STORE: return LowerSTORE(Op, DAG);
6464 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6465 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6466 case ISD::FP_TO_UINT:
6467 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6469 case ISD::UINT_TO_FP:
6470 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6471 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6473 // Lower 64-bit shifts.
6474 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6475 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6476 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6478 // Vector-related lowering.
6479 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6480 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6481 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6482 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6483 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6484 case ISD::MUL: return LowerMUL(Op, DAG);
6486 // For counter-based loop handling.
6487 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6489 // Frame & Return address.
6490 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6491 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6495 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6496 SmallVectorImpl<SDValue>&Results,
6497 SelectionDAG &DAG) const {
6498 const TargetMachine &TM = getTargetMachine();
6500 switch (N->getOpcode()) {
6502 llvm_unreachable("Do not know how to custom type legalize this operation!");
6503 case ISD::READCYCLECOUNTER: {
6504 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6505 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6507 Results.push_back(RTB);
6508 Results.push_back(RTB.getValue(1));
6509 Results.push_back(RTB.getValue(2));
6512 case ISD::INTRINSIC_W_CHAIN: {
6513 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6514 Intrinsic::ppc_is_decremented_ctr_nonzero)
6517 assert(N->getValueType(0) == MVT::i1 &&
6518 "Unexpected result type for CTR decrement intrinsic");
6519 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6520 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6521 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6524 Results.push_back(NewInt);
6525 Results.push_back(NewInt.getValue(1));
6529 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6530 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6533 EVT VT = N->getValueType(0);
6535 if (VT == MVT::i64) {
6536 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6538 Results.push_back(NewNode);
6539 Results.push_back(NewNode.getValue(1));
6543 case ISD::FP_ROUND_INREG: {
6544 assert(N->getValueType(0) == MVT::ppcf128);
6545 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6546 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6547 MVT::f64, N->getOperand(0),
6548 DAG.getIntPtrConstant(0));
6549 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6550 MVT::f64, N->getOperand(0),
6551 DAG.getIntPtrConstant(1));
6553 // Add the two halves of the long double in round-to-zero mode.
6554 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6556 // We know the low half is about to be thrown away, so just use something
6558 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6562 case ISD::FP_TO_SINT:
6563 // LowerFP_TO_INT() can only handle f32 and f64.
6564 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6566 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6572 //===----------------------------------------------------------------------===//
6573 // Other Lowering Code
6574 //===----------------------------------------------------------------------===//
6576 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6577 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6578 Function *Func = Intrinsic::getDeclaration(M, Id);
6579 return Builder.CreateCall(Func);
6582 // The mappings for emitLeading/TrailingFence is taken from
6583 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6584 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6585 AtomicOrdering Ord, bool IsStore,
6586 bool IsLoad) const {
6587 if (Ord == SequentiallyConsistent)
6588 return callIntrinsic(Builder, Intrinsic::ppc_sync);
6589 else if (isAtLeastRelease(Ord))
6590 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6595 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6596 AtomicOrdering Ord, bool IsStore,
6597 bool IsLoad) const {
6598 if (IsLoad && isAtLeastAcquire(Ord))
6599 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6600 // FIXME: this is too conservative, a dependent branch + isync is enough.
6601 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6602 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6603 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6609 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6610 bool is64bit, unsigned BinOpcode) const {
6611 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6612 const TargetInstrInfo *TII =
6613 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6615 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6616 MachineFunction *F = BB->getParent();
6617 MachineFunction::iterator It = BB;
6620 unsigned dest = MI->getOperand(0).getReg();
6621 unsigned ptrA = MI->getOperand(1).getReg();
6622 unsigned ptrB = MI->getOperand(2).getReg();
6623 unsigned incr = MI->getOperand(3).getReg();
6624 DebugLoc dl = MI->getDebugLoc();
6626 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6627 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6628 F->insert(It, loopMBB);
6629 F->insert(It, exitMBB);
6630 exitMBB->splice(exitMBB->begin(), BB,
6631 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6632 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6634 MachineRegisterInfo &RegInfo = F->getRegInfo();
6635 unsigned TmpReg = (!BinOpcode) ? incr :
6636 RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6637 : &PPC::GPRCRegClass);
6641 // fallthrough --> loopMBB
6642 BB->addSuccessor(loopMBB);
6645 // l[wd]arx dest, ptr
6646 // add r0, dest, incr
6647 // st[wd]cx. r0, ptr
6649 // fallthrough --> exitMBB
6651 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6652 .addReg(ptrA).addReg(ptrB);
6654 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6655 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6656 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6657 BuildMI(BB, dl, TII->get(PPC::BCC))
6658 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6659 BB->addSuccessor(loopMBB);
6660 BB->addSuccessor(exitMBB);
6669 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6670 MachineBasicBlock *BB,
6671 bool is8bit, // operation
6672 unsigned BinOpcode) const {
6673 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6674 const TargetInstrInfo *TII =
6675 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6676 // In 64 bit mode we have to use 64 bits for addresses, even though the
6677 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6678 // registers without caring whether they're 32 or 64, but here we're
6679 // doing actual arithmetic on the addresses.
6680 bool is64bit = Subtarget.isPPC64();
6681 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6683 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6684 MachineFunction *F = BB->getParent();
6685 MachineFunction::iterator It = BB;
6688 unsigned dest = MI->getOperand(0).getReg();
6689 unsigned ptrA = MI->getOperand(1).getReg();
6690 unsigned ptrB = MI->getOperand(2).getReg();
6691 unsigned incr = MI->getOperand(3).getReg();
6692 DebugLoc dl = MI->getDebugLoc();
6694 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6695 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6696 F->insert(It, loopMBB);
6697 F->insert(It, exitMBB);
6698 exitMBB->splice(exitMBB->begin(), BB,
6699 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6700 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6702 MachineRegisterInfo &RegInfo = F->getRegInfo();
6703 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
6704 : &PPC::GPRCRegClass;
6705 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6706 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6707 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6708 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6709 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6710 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6711 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6712 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6713 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6714 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6715 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6717 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6721 // fallthrough --> loopMBB
6722 BB->addSuccessor(loopMBB);
6724 // The 4-byte load must be aligned, while a char or short may be
6725 // anywhere in the word. Hence all this nasty bookkeeping code.
6726 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6727 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6728 // xori shift, shift1, 24 [16]
6729 // rlwinm ptr, ptr1, 0, 0, 29
6730 // slw incr2, incr, shift
6731 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6732 // slw mask, mask2, shift
6734 // lwarx tmpDest, ptr
6735 // add tmp, tmpDest, incr2
6736 // andc tmp2, tmpDest, mask
6737 // and tmp3, tmp, mask
6738 // or tmp4, tmp3, tmp2
6741 // fallthrough --> exitMBB
6742 // srw dest, tmpDest, shift
6743 if (ptrA != ZeroReg) {
6744 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6745 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6746 .addReg(ptrA).addReg(ptrB);
6750 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6751 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6752 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6753 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6755 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6756 .addReg(Ptr1Reg).addImm(0).addImm(61);
6758 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6759 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6760 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6761 .addReg(incr).addReg(ShiftReg);
6763 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6765 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6766 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6768 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6769 .addReg(Mask2Reg).addReg(ShiftReg);
6772 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6773 .addReg(ZeroReg).addReg(PtrReg);
6775 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6776 .addReg(Incr2Reg).addReg(TmpDestReg);
6777 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6778 .addReg(TmpDestReg).addReg(MaskReg);
6779 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6780 .addReg(TmpReg).addReg(MaskReg);
6781 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6782 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6783 BuildMI(BB, dl, TII->get(PPC::STWCX))
6784 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6785 BuildMI(BB, dl, TII->get(PPC::BCC))
6786 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6787 BB->addSuccessor(loopMBB);
6788 BB->addSuccessor(exitMBB);
6793 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6798 llvm::MachineBasicBlock*
6799 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6800 MachineBasicBlock *MBB) const {
6801 DebugLoc DL = MI->getDebugLoc();
6802 const TargetInstrInfo *TII =
6803 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6805 MachineFunction *MF = MBB->getParent();
6806 MachineRegisterInfo &MRI = MF->getRegInfo();
6808 const BasicBlock *BB = MBB->getBasicBlock();
6809 MachineFunction::iterator I = MBB;
6813 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6814 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6816 unsigned DstReg = MI->getOperand(0).getReg();
6817 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6818 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6819 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6820 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6822 MVT PVT = getPointerTy();
6823 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6824 "Invalid Pointer Size!");
6825 // For v = setjmp(buf), we generate
6828 // SjLjSetup mainMBB
6834 // buf[LabelOffset] = LR
6838 // v = phi(main, restore)
6841 MachineBasicBlock *thisMBB = MBB;
6842 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6843 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6844 MF->insert(I, mainMBB);
6845 MF->insert(I, sinkMBB);
6847 MachineInstrBuilder MIB;
6849 // Transfer the remainder of BB and its successor edges to sinkMBB.
6850 sinkMBB->splice(sinkMBB->begin(), MBB,
6851 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6852 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6854 // Note that the structure of the jmp_buf used here is not compatible
6855 // with that used by libc, and is not designed to be. Specifically, it
6856 // stores only those 'reserved' registers that LLVM does not otherwise
6857 // understand how to spill. Also, by convention, by the time this
6858 // intrinsic is called, Clang has already stored the frame address in the
6859 // first slot of the buffer and stack address in the third. Following the
6860 // X86 target code, we'll store the jump address in the second slot. We also
6861 // need to save the TOC pointer (R2) to handle jumps between shared
6862 // libraries, and that will be stored in the fourth slot. The thread
6863 // identifier (R13) is not affected.
6866 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6867 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6868 const int64_t BPOffset = 4 * PVT.getStoreSize();
6870 // Prepare IP either in reg.
6871 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6872 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6873 unsigned BufReg = MI->getOperand(1).getReg();
6875 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6876 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6880 MIB.setMemRefs(MMOBegin, MMOEnd);
6883 // Naked functions never have a base pointer, and so we use r1. For all
6884 // other functions, this decision must be delayed until during PEI.
6886 if (MF->getFunction()->getAttributes().hasAttribute(
6887 AttributeSet::FunctionIndex, Attribute::Naked))
6888 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6890 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6892 MIB = BuildMI(*thisMBB, MI, DL,
6893 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6897 MIB.setMemRefs(MMOBegin, MMOEnd);
6900 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6901 const PPCRegisterInfo *TRI =
6902 getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
6903 MIB.addRegMask(TRI->getNoPreservedMask());
6905 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6907 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6909 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6911 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6912 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6916 MIB = BuildMI(mainMBB, DL,
6917 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6920 if (Subtarget.isPPC64()) {
6921 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6923 .addImm(LabelOffset)
6926 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6928 .addImm(LabelOffset)
6932 MIB.setMemRefs(MMOBegin, MMOEnd);
6934 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6935 mainMBB->addSuccessor(sinkMBB);
6938 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6939 TII->get(PPC::PHI), DstReg)
6940 .addReg(mainDstReg).addMBB(mainMBB)
6941 .addReg(restoreDstReg).addMBB(thisMBB);
6943 MI->eraseFromParent();
6948 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6949 MachineBasicBlock *MBB) const {
6950 DebugLoc DL = MI->getDebugLoc();
6951 const TargetInstrInfo *TII =
6952 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6954 MachineFunction *MF = MBB->getParent();
6955 MachineRegisterInfo &MRI = MF->getRegInfo();
6958 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6959 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6961 MVT PVT = getPointerTy();
6962 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6963 "Invalid Pointer Size!");
6965 const TargetRegisterClass *RC =
6966 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6967 unsigned Tmp = MRI.createVirtualRegister(RC);
6968 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6969 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6970 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6971 unsigned BP = (PVT == MVT::i64) ? PPC::X30 :
6972 (Subtarget.isSVR4ABI() &&
6973 MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6974 PPC::R29 : PPC::R30);
6976 MachineInstrBuilder MIB;
6978 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6979 const int64_t SPOffset = 2 * PVT.getStoreSize();
6980 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6981 const int64_t BPOffset = 4 * PVT.getStoreSize();
6983 unsigned BufReg = MI->getOperand(0).getReg();
6985 // Reload FP (the jumped-to function may not have had a
6986 // frame pointer, and if so, then its r31 will be restored
6988 if (PVT == MVT::i64) {
6989 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6993 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6997 MIB.setMemRefs(MMOBegin, MMOEnd);
7000 if (PVT == MVT::i64) {
7001 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7002 .addImm(LabelOffset)
7005 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7006 .addImm(LabelOffset)
7009 MIB.setMemRefs(MMOBegin, MMOEnd);
7012 if (PVT == MVT::i64) {
7013 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7017 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7021 MIB.setMemRefs(MMOBegin, MMOEnd);
7024 if (PVT == MVT::i64) {
7025 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7029 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7033 MIB.setMemRefs(MMOBegin, MMOEnd);
7036 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7037 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7041 MIB.setMemRefs(MMOBegin, MMOEnd);
7045 BuildMI(*MBB, MI, DL,
7046 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7047 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7049 MI->eraseFromParent();
7054 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7055 MachineBasicBlock *BB) const {
7056 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7057 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7058 return emitEHSjLjSetJmp(MI, BB);
7059 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7060 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7061 return emitEHSjLjLongJmp(MI, BB);
7064 const TargetInstrInfo *TII =
7065 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7067 // To "insert" these instructions we actually have to insert their
7068 // control-flow patterns.
7069 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7070 MachineFunction::iterator It = BB;
7073 MachineFunction *F = BB->getParent();
7075 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7076 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7077 MI->getOpcode() == PPC::SELECT_I4 ||
7078 MI->getOpcode() == PPC::SELECT_I8)) {
7079 SmallVector<MachineOperand, 2> Cond;
7080 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7081 MI->getOpcode() == PPC::SELECT_CC_I8)
7082 Cond.push_back(MI->getOperand(4));
7084 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7085 Cond.push_back(MI->getOperand(1));
7087 DebugLoc dl = MI->getDebugLoc();
7088 const TargetInstrInfo *TII =
7089 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7090 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7091 Cond, MI->getOperand(2).getReg(),
7092 MI->getOperand(3).getReg());
7093 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7094 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7095 MI->getOpcode() == PPC::SELECT_CC_F4 ||
7096 MI->getOpcode() == PPC::SELECT_CC_F8 ||
7097 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7098 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7099 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7100 MI->getOpcode() == PPC::SELECT_I4 ||
7101 MI->getOpcode() == PPC::SELECT_I8 ||
7102 MI->getOpcode() == PPC::SELECT_F4 ||
7103 MI->getOpcode() == PPC::SELECT_F8 ||
7104 MI->getOpcode() == PPC::SELECT_VRRC ||
7105 MI->getOpcode() == PPC::SELECT_VSFRC ||
7106 MI->getOpcode() == PPC::SELECT_VSRC) {
7107 // The incoming instruction knows the destination vreg to set, the
7108 // condition code register to branch on, the true/false values to
7109 // select between, and a branch opcode to use.
7114 // cmpTY ccX, r1, r2
7116 // fallthrough --> copy0MBB
7117 MachineBasicBlock *thisMBB = BB;
7118 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7119 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7120 DebugLoc dl = MI->getDebugLoc();
7121 F->insert(It, copy0MBB);
7122 F->insert(It, sinkMBB);
7124 // Transfer the remainder of BB and its successor edges to sinkMBB.
7125 sinkMBB->splice(sinkMBB->begin(), BB,
7126 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7127 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7129 // Next, add the true and fallthrough blocks as its successors.
7130 BB->addSuccessor(copy0MBB);
7131 BB->addSuccessor(sinkMBB);
7133 if (MI->getOpcode() == PPC::SELECT_I4 ||
7134 MI->getOpcode() == PPC::SELECT_I8 ||
7135 MI->getOpcode() == PPC::SELECT_F4 ||
7136 MI->getOpcode() == PPC::SELECT_F8 ||
7137 MI->getOpcode() == PPC::SELECT_VRRC ||
7138 MI->getOpcode() == PPC::SELECT_VSFRC ||
7139 MI->getOpcode() == PPC::SELECT_VSRC) {
7140 BuildMI(BB, dl, TII->get(PPC::BC))
7141 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7143 unsigned SelectPred = MI->getOperand(4).getImm();
7144 BuildMI(BB, dl, TII->get(PPC::BCC))
7145 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7149 // %FalseValue = ...
7150 // # fallthrough to sinkMBB
7153 // Update machine-CFG edges
7154 BB->addSuccessor(sinkMBB);
7157 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7160 BuildMI(*BB, BB->begin(), dl,
7161 TII->get(PPC::PHI), MI->getOperand(0).getReg())
7162 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7163 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7164 } else if (MI->getOpcode() == PPC::ReadTB) {
7165 // To read the 64-bit time-base register on a 32-bit target, we read the
7166 // two halves. Should the counter have wrapped while it was being read, we
7167 // need to try again.
7170 // mfspr Rx,TBU # load from TBU
7171 // mfspr Ry,TB # load from TB
7172 // mfspr Rz,TBU # load from TBU
7173 // cmpw crX,Rx,Rz # check if ‘old’=’new’
7174 // bne readLoop # branch if they're not equal
7177 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7178 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7179 DebugLoc dl = MI->getDebugLoc();
7180 F->insert(It, readMBB);
7181 F->insert(It, sinkMBB);
7183 // Transfer the remainder of BB and its successor edges to sinkMBB.
7184 sinkMBB->splice(sinkMBB->begin(), BB,
7185 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7186 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7188 BB->addSuccessor(readMBB);
7191 MachineRegisterInfo &RegInfo = F->getRegInfo();
7192 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7193 unsigned LoReg = MI->getOperand(0).getReg();
7194 unsigned HiReg = MI->getOperand(1).getReg();
7196 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7197 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7198 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7200 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7202 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7203 .addReg(HiReg).addReg(ReadAgainReg);
7204 BuildMI(BB, dl, TII->get(PPC::BCC))
7205 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7207 BB->addSuccessor(readMBB);
7208 BB->addSuccessor(sinkMBB);
7210 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7211 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7212 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7213 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7214 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7215 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7216 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7217 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7219 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7220 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7221 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7222 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7223 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7224 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7225 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7226 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7228 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7229 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7230 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7231 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7232 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7233 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7234 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7235 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7237 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7238 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7239 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7240 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7241 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7242 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7243 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7244 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7246 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7247 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7248 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7249 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7250 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7251 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7252 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7253 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7255 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7256 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7257 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7258 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7259 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7260 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7261 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7262 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7264 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7265 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7266 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7267 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7268 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7269 BB = EmitAtomicBinary(MI, BB, false, 0);
7270 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7271 BB = EmitAtomicBinary(MI, BB, true, 0);
7273 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7274 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7275 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7277 unsigned dest = MI->getOperand(0).getReg();
7278 unsigned ptrA = MI->getOperand(1).getReg();
7279 unsigned ptrB = MI->getOperand(2).getReg();
7280 unsigned oldval = MI->getOperand(3).getReg();
7281 unsigned newval = MI->getOperand(4).getReg();
7282 DebugLoc dl = MI->getDebugLoc();
7284 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7285 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7286 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7287 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7288 F->insert(It, loop1MBB);
7289 F->insert(It, loop2MBB);
7290 F->insert(It, midMBB);
7291 F->insert(It, exitMBB);
7292 exitMBB->splice(exitMBB->begin(), BB,
7293 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7294 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7298 // fallthrough --> loopMBB
7299 BB->addSuccessor(loop1MBB);
7302 // l[wd]arx dest, ptr
7303 // cmp[wd] dest, oldval
7306 // st[wd]cx. newval, ptr
7310 // st[wd]cx. dest, ptr
7313 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7314 .addReg(ptrA).addReg(ptrB);
7315 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7316 .addReg(oldval).addReg(dest);
7317 BuildMI(BB, dl, TII->get(PPC::BCC))
7318 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7319 BB->addSuccessor(loop2MBB);
7320 BB->addSuccessor(midMBB);
7323 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7324 .addReg(newval).addReg(ptrA).addReg(ptrB);
7325 BuildMI(BB, dl, TII->get(PPC::BCC))
7326 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7327 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7328 BB->addSuccessor(loop1MBB);
7329 BB->addSuccessor(exitMBB);
7332 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7333 .addReg(dest).addReg(ptrA).addReg(ptrB);
7334 BB->addSuccessor(exitMBB);
7339 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7340 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7341 // We must use 64-bit registers for addresses when targeting 64-bit,
7342 // since we're actually doing arithmetic on them. Other registers
7344 bool is64bit = Subtarget.isPPC64();
7345 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7347 unsigned dest = MI->getOperand(0).getReg();
7348 unsigned ptrA = MI->getOperand(1).getReg();
7349 unsigned ptrB = MI->getOperand(2).getReg();
7350 unsigned oldval = MI->getOperand(3).getReg();
7351 unsigned newval = MI->getOperand(4).getReg();
7352 DebugLoc dl = MI->getDebugLoc();
7354 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7355 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7356 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7357 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7358 F->insert(It, loop1MBB);
7359 F->insert(It, loop2MBB);
7360 F->insert(It, midMBB);
7361 F->insert(It, exitMBB);
7362 exitMBB->splice(exitMBB->begin(), BB,
7363 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7364 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7366 MachineRegisterInfo &RegInfo = F->getRegInfo();
7367 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7368 : &PPC::GPRCRegClass;
7369 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7370 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7371 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7372 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7373 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7374 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7375 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7376 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7377 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7378 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7379 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7380 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7381 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7383 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7384 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7387 // fallthrough --> loopMBB
7388 BB->addSuccessor(loop1MBB);
7390 // The 4-byte load must be aligned, while a char or short may be
7391 // anywhere in the word. Hence all this nasty bookkeeping code.
7392 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7393 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7394 // xori shift, shift1, 24 [16]
7395 // rlwinm ptr, ptr1, 0, 0, 29
7396 // slw newval2, newval, shift
7397 // slw oldval2, oldval,shift
7398 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7399 // slw mask, mask2, shift
7400 // and newval3, newval2, mask
7401 // and oldval3, oldval2, mask
7403 // lwarx tmpDest, ptr
7404 // and tmp, tmpDest, mask
7405 // cmpw tmp, oldval3
7408 // andc tmp2, tmpDest, mask
7409 // or tmp4, tmp2, newval3
7414 // stwcx. tmpDest, ptr
7416 // srw dest, tmpDest, shift
7417 if (ptrA != ZeroReg) {
7418 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7419 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7420 .addReg(ptrA).addReg(ptrB);
7424 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7425 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7426 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7427 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7429 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7430 .addReg(Ptr1Reg).addImm(0).addImm(61);
7432 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7433 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7434 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7435 .addReg(newval).addReg(ShiftReg);
7436 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7437 .addReg(oldval).addReg(ShiftReg);
7439 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7441 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7442 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7443 .addReg(Mask3Reg).addImm(65535);
7445 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7446 .addReg(Mask2Reg).addReg(ShiftReg);
7447 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7448 .addReg(NewVal2Reg).addReg(MaskReg);
7449 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7450 .addReg(OldVal2Reg).addReg(MaskReg);
7453 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7454 .addReg(ZeroReg).addReg(PtrReg);
7455 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7456 .addReg(TmpDestReg).addReg(MaskReg);
7457 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7458 .addReg(TmpReg).addReg(OldVal3Reg);
7459 BuildMI(BB, dl, TII->get(PPC::BCC))
7460 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7461 BB->addSuccessor(loop2MBB);
7462 BB->addSuccessor(midMBB);
7465 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7466 .addReg(TmpDestReg).addReg(MaskReg);
7467 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7468 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7469 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7470 .addReg(ZeroReg).addReg(PtrReg);
7471 BuildMI(BB, dl, TII->get(PPC::BCC))
7472 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7473 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7474 BB->addSuccessor(loop1MBB);
7475 BB->addSuccessor(exitMBB);
7478 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7479 .addReg(ZeroReg).addReg(PtrReg);
7480 BB->addSuccessor(exitMBB);
7485 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7487 } else if (MI->getOpcode() == PPC::FADDrtz) {
7488 // This pseudo performs an FADD with rounding mode temporarily forced
7489 // to round-to-zero. We emit this via custom inserter since the FPSCR
7490 // is not modeled at the SelectionDAG level.
7491 unsigned Dest = MI->getOperand(0).getReg();
7492 unsigned Src1 = MI->getOperand(1).getReg();
7493 unsigned Src2 = MI->getOperand(2).getReg();
7494 DebugLoc dl = MI->getDebugLoc();
7496 MachineRegisterInfo &RegInfo = F->getRegInfo();
7497 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7499 // Save FPSCR value.
7500 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7502 // Set rounding mode to round-to-zero.
7503 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7504 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7506 // Perform addition.
7507 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7509 // Restore FPSCR value.
7510 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7511 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7512 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7513 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7514 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7515 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7516 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7517 PPC::ANDIo8 : PPC::ANDIo;
7518 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7519 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7521 MachineRegisterInfo &RegInfo = F->getRegInfo();
7522 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7523 &PPC::GPRCRegClass :
7524 &PPC::G8RCRegClass);
7526 DebugLoc dl = MI->getDebugLoc();
7527 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7528 .addReg(MI->getOperand(1).getReg()).addImm(1);
7529 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7530 MI->getOperand(0).getReg())
7531 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7533 llvm_unreachable("Unexpected instr type to insert");
7536 MI->eraseFromParent(); // The pseudo instruction is gone now.
7540 //===----------------------------------------------------------------------===//
7541 // Target Optimization Hooks
7542 //===----------------------------------------------------------------------===//
7544 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7545 DAGCombinerInfo &DCI,
7546 unsigned &RefinementSteps,
7547 bool &UseOneConstNR) const {
7548 EVT VT = Operand.getValueType();
7549 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7550 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7551 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7552 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7553 // Convergence is quadratic, so we essentially double the number of digits
7554 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7555 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7556 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7557 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7558 if (VT.getScalarType() == MVT::f64)
7560 UseOneConstNR = true;
7561 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7566 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7567 DAGCombinerInfo &DCI,
7568 unsigned &RefinementSteps) const {
7569 EVT VT = Operand.getValueType();
7570 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7571 (VT == MVT::f64 && Subtarget.hasFRE()) ||
7572 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7573 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7574 // Convergence is quadratic, so we essentially double the number of digits
7575 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7576 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7577 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7578 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7579 if (VT.getScalarType() == MVT::f64)
7581 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7586 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7587 // Note: This functionality is used only when unsafe-fp-math is enabled, and
7588 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7589 // enabled for division), this functionality is redundant with the default
7590 // combiner logic (once the division -> reciprocal/multiply transformation
7591 // has taken place). As a result, this matters more for older cores than for
7594 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7595 // reciprocal if there are two or more FDIVs (for embedded cores with only
7596 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7597 switch (Subtarget.getDarwinDirective()) {
7599 return NumUsers > 2;
7602 case PPC::DIR_E500mc:
7603 case PPC::DIR_E5500:
7604 return NumUsers > 1;
7608 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7609 unsigned Bytes, int Dist,
7610 SelectionDAG &DAG) {
7611 if (VT.getSizeInBits() / 8 != Bytes)
7614 SDValue BaseLoc = Base->getBasePtr();
7615 if (Loc.getOpcode() == ISD::FrameIndex) {
7616 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7618 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7619 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7620 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7621 int FS = MFI->getObjectSize(FI);
7622 int BFS = MFI->getObjectSize(BFI);
7623 if (FS != BFS || FS != (int)Bytes) return false;
7624 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7628 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7629 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7632 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7633 const GlobalValue *GV1 = nullptr;
7634 const GlobalValue *GV2 = nullptr;
7635 int64_t Offset1 = 0;
7636 int64_t Offset2 = 0;
7637 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7638 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7639 if (isGA1 && isGA2 && GV1 == GV2)
7640 return Offset1 == (Offset2 + Dist*Bytes);
7644 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7645 // not enforce equality of the chain operands.
7646 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7647 unsigned Bytes, int Dist,
7648 SelectionDAG &DAG) {
7649 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7650 EVT VT = LS->getMemoryVT();
7651 SDValue Loc = LS->getBasePtr();
7652 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7655 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7657 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7658 default: return false;
7659 case Intrinsic::ppc_altivec_lvx:
7660 case Intrinsic::ppc_altivec_lvxl:
7661 case Intrinsic::ppc_vsx_lxvw4x:
7664 case Intrinsic::ppc_vsx_lxvd2x:
7667 case Intrinsic::ppc_altivec_lvebx:
7670 case Intrinsic::ppc_altivec_lvehx:
7673 case Intrinsic::ppc_altivec_lvewx:
7678 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7681 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7683 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7684 default: return false;
7685 case Intrinsic::ppc_altivec_stvx:
7686 case Intrinsic::ppc_altivec_stvxl:
7687 case Intrinsic::ppc_vsx_stxvw4x:
7690 case Intrinsic::ppc_vsx_stxvd2x:
7693 case Intrinsic::ppc_altivec_stvebx:
7696 case Intrinsic::ppc_altivec_stvehx:
7699 case Intrinsic::ppc_altivec_stvewx:
7704 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7710 // Return true is there is a nearyby consecutive load to the one provided
7711 // (regardless of alignment). We search up and down the chain, looking though
7712 // token factors and other loads (but nothing else). As a result, a true result
7713 // indicates that it is safe to create a new consecutive load adjacent to the
7715 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7716 SDValue Chain = LD->getChain();
7717 EVT VT = LD->getMemoryVT();
7719 SmallSet<SDNode *, 16> LoadRoots;
7720 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7721 SmallSet<SDNode *, 16> Visited;
7723 // First, search up the chain, branching to follow all token-factor operands.
7724 // If we find a consecutive load, then we're done, otherwise, record all
7725 // nodes just above the top-level loads and token factors.
7726 while (!Queue.empty()) {
7727 SDNode *ChainNext = Queue.pop_back_val();
7728 if (!Visited.insert(ChainNext).second)
7731 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7732 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7735 if (!Visited.count(ChainLD->getChain().getNode()))
7736 Queue.push_back(ChainLD->getChain().getNode());
7737 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7738 for (const SDUse &O : ChainNext->ops())
7739 if (!Visited.count(O.getNode()))
7740 Queue.push_back(O.getNode());
7742 LoadRoots.insert(ChainNext);
7745 // Second, search down the chain, starting from the top-level nodes recorded
7746 // in the first phase. These top-level nodes are the nodes just above all
7747 // loads and token factors. Starting with their uses, recursively look though
7748 // all loads (just the chain uses) and token factors to find a consecutive
7753 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7754 IE = LoadRoots.end(); I != IE; ++I) {
7755 Queue.push_back(*I);
7757 while (!Queue.empty()) {
7758 SDNode *LoadRoot = Queue.pop_back_val();
7759 if (!Visited.insert(LoadRoot).second)
7762 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7763 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7766 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7767 UE = LoadRoot->use_end(); UI != UE; ++UI)
7768 if (((isa<MemSDNode>(*UI) &&
7769 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7770 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7771 Queue.push_back(*UI);
7778 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7779 DAGCombinerInfo &DCI) const {
7780 SelectionDAG &DAG = DCI.DAG;
7783 assert(Subtarget.useCRBits() &&
7784 "Expecting to be tracking CR bits");
7785 // If we're tracking CR bits, we need to be careful that we don't have:
7786 // trunc(binary-ops(zext(x), zext(y)))
7788 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7789 // such that we're unnecessarily moving things into GPRs when it would be
7790 // better to keep them in CR bits.
7792 // Note that trunc here can be an actual i1 trunc, or can be the effective
7793 // truncation that comes from a setcc or select_cc.
7794 if (N->getOpcode() == ISD::TRUNCATE &&
7795 N->getValueType(0) != MVT::i1)
7798 if (N->getOperand(0).getValueType() != MVT::i32 &&
7799 N->getOperand(0).getValueType() != MVT::i64)
7802 if (N->getOpcode() == ISD::SETCC ||
7803 N->getOpcode() == ISD::SELECT_CC) {
7804 // If we're looking at a comparison, then we need to make sure that the
7805 // high bits (all except for the first) don't matter the result.
7807 cast<CondCodeSDNode>(N->getOperand(
7808 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7809 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7811 if (ISD::isSignedIntSetCC(CC)) {
7812 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7813 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7815 } else if (ISD::isUnsignedIntSetCC(CC)) {
7816 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7817 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7818 !DAG.MaskedValueIsZero(N->getOperand(1),
7819 APInt::getHighBitsSet(OpBits, OpBits-1)))
7822 // This is neither a signed nor an unsigned comparison, just make sure
7823 // that the high bits are equal.
7824 APInt Op1Zero, Op1One;
7825 APInt Op2Zero, Op2One;
7826 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7827 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7829 // We don't really care about what is known about the first bit (if
7830 // anything), so clear it in all masks prior to comparing them.
7831 Op1Zero.clearBit(0); Op1One.clearBit(0);
7832 Op2Zero.clearBit(0); Op2One.clearBit(0);
7834 if (Op1Zero != Op2Zero || Op1One != Op2One)
7839 // We now know that the higher-order bits are irrelevant, we just need to
7840 // make sure that all of the intermediate operations are bit operations, and
7841 // all inputs are extensions.
7842 if (N->getOperand(0).getOpcode() != ISD::AND &&
7843 N->getOperand(0).getOpcode() != ISD::OR &&
7844 N->getOperand(0).getOpcode() != ISD::XOR &&
7845 N->getOperand(0).getOpcode() != ISD::SELECT &&
7846 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7847 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7848 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7849 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7850 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7853 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7854 N->getOperand(1).getOpcode() != ISD::AND &&
7855 N->getOperand(1).getOpcode() != ISD::OR &&
7856 N->getOperand(1).getOpcode() != ISD::XOR &&
7857 N->getOperand(1).getOpcode() != ISD::SELECT &&
7858 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7859 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7860 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7861 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7862 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7865 SmallVector<SDValue, 4> Inputs;
7866 SmallVector<SDValue, 8> BinOps, PromOps;
7867 SmallPtrSet<SDNode *, 16> Visited;
7869 for (unsigned i = 0; i < 2; ++i) {
7870 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7871 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7872 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7873 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7874 isa<ConstantSDNode>(N->getOperand(i)))
7875 Inputs.push_back(N->getOperand(i));
7877 BinOps.push_back(N->getOperand(i));
7879 if (N->getOpcode() == ISD::TRUNCATE)
7883 // Visit all inputs, collect all binary operations (and, or, xor and
7884 // select) that are all fed by extensions.
7885 while (!BinOps.empty()) {
7886 SDValue BinOp = BinOps.back();
7889 if (!Visited.insert(BinOp.getNode()).second)
7892 PromOps.push_back(BinOp);
7894 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7895 // The condition of the select is not promoted.
7896 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7898 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7901 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7902 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7903 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7904 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7905 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7906 Inputs.push_back(BinOp.getOperand(i));
7907 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7908 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7909 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7910 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7911 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7912 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7913 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7914 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7915 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7916 BinOps.push_back(BinOp.getOperand(i));
7918 // We have an input that is not an extension or another binary
7919 // operation; we'll abort this transformation.
7925 // Make sure that this is a self-contained cluster of operations (which
7926 // is not quite the same thing as saying that everything has only one
7928 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7929 if (isa<ConstantSDNode>(Inputs[i]))
7932 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7933 UE = Inputs[i].getNode()->use_end();
7936 if (User != N && !Visited.count(User))
7939 // Make sure that we're not going to promote the non-output-value
7940 // operand(s) or SELECT or SELECT_CC.
7941 // FIXME: Although we could sometimes handle this, and it does occur in
7942 // practice that one of the condition inputs to the select is also one of
7943 // the outputs, we currently can't deal with this.
7944 if (User->getOpcode() == ISD::SELECT) {
7945 if (User->getOperand(0) == Inputs[i])
7947 } else if (User->getOpcode() == ISD::SELECT_CC) {
7948 if (User->getOperand(0) == Inputs[i] ||
7949 User->getOperand(1) == Inputs[i])
7955 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7956 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7957 UE = PromOps[i].getNode()->use_end();
7960 if (User != N && !Visited.count(User))
7963 // Make sure that we're not going to promote the non-output-value
7964 // operand(s) or SELECT or SELECT_CC.
7965 // FIXME: Although we could sometimes handle this, and it does occur in
7966 // practice that one of the condition inputs to the select is also one of
7967 // the outputs, we currently can't deal with this.
7968 if (User->getOpcode() == ISD::SELECT) {
7969 if (User->getOperand(0) == PromOps[i])
7971 } else if (User->getOpcode() == ISD::SELECT_CC) {
7972 if (User->getOperand(0) == PromOps[i] ||
7973 User->getOperand(1) == PromOps[i])
7979 // Replace all inputs with the extension operand.
7980 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7981 // Constants may have users outside the cluster of to-be-promoted nodes,
7982 // and so we need to replace those as we do the promotions.
7983 if (isa<ConstantSDNode>(Inputs[i]))
7986 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7989 // Replace all operations (these are all the same, but have a different
7990 // (i1) return type). DAG.getNode will validate that the types of
7991 // a binary operator match, so go through the list in reverse so that
7992 // we've likely promoted both operands first. Any intermediate truncations or
7993 // extensions disappear.
7994 while (!PromOps.empty()) {
7995 SDValue PromOp = PromOps.back();
7998 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7999 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8000 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8001 PromOp.getOpcode() == ISD::ANY_EXTEND) {
8002 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8003 PromOp.getOperand(0).getValueType() != MVT::i1) {
8004 // The operand is not yet ready (see comment below).
8005 PromOps.insert(PromOps.begin(), PromOp);
8009 SDValue RepValue = PromOp.getOperand(0);
8010 if (isa<ConstantSDNode>(RepValue))
8011 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8013 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8018 switch (PromOp.getOpcode()) {
8019 default: C = 0; break;
8020 case ISD::SELECT: C = 1; break;
8021 case ISD::SELECT_CC: C = 2; break;
8024 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8025 PromOp.getOperand(C).getValueType() != MVT::i1) ||
8026 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8027 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8028 // The to-be-promoted operands of this node have not yet been
8029 // promoted (this should be rare because we're going through the
8030 // list backward, but if one of the operands has several users in
8031 // this cluster of to-be-promoted nodes, it is possible).
8032 PromOps.insert(PromOps.begin(), PromOp);
8036 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8037 PromOp.getNode()->op_end());
8039 // If there are any constant inputs, make sure they're replaced now.
8040 for (unsigned i = 0; i < 2; ++i)
8041 if (isa<ConstantSDNode>(Ops[C+i]))
8042 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8044 DAG.ReplaceAllUsesOfValueWith(PromOp,
8045 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8048 // Now we're left with the initial truncation itself.
8049 if (N->getOpcode() == ISD::TRUNCATE)
8050 return N->getOperand(0);
8052 // Otherwise, this is a comparison. The operands to be compared have just
8053 // changed type (to i1), but everything else is the same.
8054 return SDValue(N, 0);
8057 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8058 DAGCombinerInfo &DCI) const {
8059 SelectionDAG &DAG = DCI.DAG;
8062 // If we're tracking CR bits, we need to be careful that we don't have:
8063 // zext(binary-ops(trunc(x), trunc(y)))
8065 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8066 // such that we're unnecessarily moving things into CR bits that can more
8067 // efficiently stay in GPRs. Note that if we're not certain that the high
8068 // bits are set as required by the final extension, we still may need to do
8069 // some masking to get the proper behavior.
8071 // This same functionality is important on PPC64 when dealing with
8072 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8073 // the return values of functions. Because it is so similar, it is handled
8076 if (N->getValueType(0) != MVT::i32 &&
8077 N->getValueType(0) != MVT::i64)
8080 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8081 Subtarget.useCRBits()) ||
8082 (N->getOperand(0).getValueType() == MVT::i32 &&
8083 Subtarget.isPPC64())))
8086 if (N->getOperand(0).getOpcode() != ISD::AND &&
8087 N->getOperand(0).getOpcode() != ISD::OR &&
8088 N->getOperand(0).getOpcode() != ISD::XOR &&
8089 N->getOperand(0).getOpcode() != ISD::SELECT &&
8090 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8093 SmallVector<SDValue, 4> Inputs;
8094 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8095 SmallPtrSet<SDNode *, 16> Visited;
8097 // Visit all inputs, collect all binary operations (and, or, xor and
8098 // select) that are all fed by truncations.
8099 while (!BinOps.empty()) {
8100 SDValue BinOp = BinOps.back();
8103 if (!Visited.insert(BinOp.getNode()).second)
8106 PromOps.push_back(BinOp);
8108 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8109 // The condition of the select is not promoted.
8110 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8112 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8115 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8116 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8117 Inputs.push_back(BinOp.getOperand(i));
8118 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8119 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8120 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8121 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8122 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8123 BinOps.push_back(BinOp.getOperand(i));
8125 // We have an input that is not a truncation or another binary
8126 // operation; we'll abort this transformation.
8132 // Make sure that this is a self-contained cluster of operations (which
8133 // is not quite the same thing as saying that everything has only one
8135 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8136 if (isa<ConstantSDNode>(Inputs[i]))
8139 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8140 UE = Inputs[i].getNode()->use_end();
8143 if (User != N && !Visited.count(User))
8146 // Make sure that we're not going to promote the non-output-value
8147 // operand(s) or SELECT or SELECT_CC.
8148 // FIXME: Although we could sometimes handle this, and it does occur in
8149 // practice that one of the condition inputs to the select is also one of
8150 // the outputs, we currently can't deal with this.
8151 if (User->getOpcode() == ISD::SELECT) {
8152 if (User->getOperand(0) == Inputs[i])
8154 } else if (User->getOpcode() == ISD::SELECT_CC) {
8155 if (User->getOperand(0) == Inputs[i] ||
8156 User->getOperand(1) == Inputs[i])
8162 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8163 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8164 UE = PromOps[i].getNode()->use_end();
8167 if (User != N && !Visited.count(User))
8170 // Make sure that we're not going to promote the non-output-value
8171 // operand(s) or SELECT or SELECT_CC.
8172 // FIXME: Although we could sometimes handle this, and it does occur in
8173 // practice that one of the condition inputs to the select is also one of
8174 // the outputs, we currently can't deal with this.
8175 if (User->getOpcode() == ISD::SELECT) {
8176 if (User->getOperand(0) == PromOps[i])
8178 } else if (User->getOpcode() == ISD::SELECT_CC) {
8179 if (User->getOperand(0) == PromOps[i] ||
8180 User->getOperand(1) == PromOps[i])
8186 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8187 bool ReallyNeedsExt = false;
8188 if (N->getOpcode() != ISD::ANY_EXTEND) {
8189 // If all of the inputs are not already sign/zero extended, then
8190 // we'll still need to do that at the end.
8191 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8192 if (isa<ConstantSDNode>(Inputs[i]))
8196 Inputs[i].getOperand(0).getValueSizeInBits();
8197 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8199 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8200 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8201 APInt::getHighBitsSet(OpBits,
8202 OpBits-PromBits))) ||
8203 (N->getOpcode() == ISD::SIGN_EXTEND &&
8204 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8205 (OpBits-(PromBits-1)))) {
8206 ReallyNeedsExt = true;
8212 // Replace all inputs, either with the truncation operand, or a
8213 // truncation or extension to the final output type.
8214 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8215 // Constant inputs need to be replaced with the to-be-promoted nodes that
8216 // use them because they might have users outside of the cluster of
8218 if (isa<ConstantSDNode>(Inputs[i]))
8221 SDValue InSrc = Inputs[i].getOperand(0);
8222 if (Inputs[i].getValueType() == N->getValueType(0))
8223 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8224 else if (N->getOpcode() == ISD::SIGN_EXTEND)
8225 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8226 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8227 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8228 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8229 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8231 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8232 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8235 // Replace all operations (these are all the same, but have a different
8236 // (promoted) return type). DAG.getNode will validate that the types of
8237 // a binary operator match, so go through the list in reverse so that
8238 // we've likely promoted both operands first.
8239 while (!PromOps.empty()) {
8240 SDValue PromOp = PromOps.back();
8244 switch (PromOp.getOpcode()) {
8245 default: C = 0; break;
8246 case ISD::SELECT: C = 1; break;
8247 case ISD::SELECT_CC: C = 2; break;
8250 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8251 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8252 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8253 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8254 // The to-be-promoted operands of this node have not yet been
8255 // promoted (this should be rare because we're going through the
8256 // list backward, but if one of the operands has several users in
8257 // this cluster of to-be-promoted nodes, it is possible).
8258 PromOps.insert(PromOps.begin(), PromOp);
8262 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8263 PromOp.getNode()->op_end());
8265 // If this node has constant inputs, then they'll need to be promoted here.
8266 for (unsigned i = 0; i < 2; ++i) {
8267 if (!isa<ConstantSDNode>(Ops[C+i]))
8269 if (Ops[C+i].getValueType() == N->getValueType(0))
8272 if (N->getOpcode() == ISD::SIGN_EXTEND)
8273 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8274 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8275 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8277 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8280 DAG.ReplaceAllUsesOfValueWith(PromOp,
8281 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8284 // Now we're left with the initial extension itself.
8285 if (!ReallyNeedsExt)
8286 return N->getOperand(0);
8288 // To zero extend, just mask off everything except for the first bit (in the
8290 if (N->getOpcode() == ISD::ZERO_EXTEND)
8291 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8292 DAG.getConstant(APInt::getLowBitsSet(
8293 N->getValueSizeInBits(0), PromBits),
8294 N->getValueType(0)));
8296 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8297 "Invalid extension type");
8298 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8300 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8301 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
8302 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8303 N->getOperand(0), ShiftCst), ShiftCst);
8306 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8307 DAGCombinerInfo &DCI) const {
8308 const TargetMachine &TM = getTargetMachine();
8309 SelectionDAG &DAG = DCI.DAG;
8311 switch (N->getOpcode()) {
8314 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8315 if (C->isNullValue()) // 0 << V -> 0.
8316 return N->getOperand(0);
8320 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8321 if (C->isNullValue()) // 0 >>u V -> 0.
8322 return N->getOperand(0);
8326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8327 if (C->isNullValue() || // 0 >>s V -> 0.
8328 C->isAllOnesValue()) // -1 >>s V -> -1.
8329 return N->getOperand(0);
8332 case ISD::SIGN_EXTEND:
8333 case ISD::ZERO_EXTEND:
8334 case ISD::ANY_EXTEND:
8335 return DAGCombineExtBoolTrunc(N, DCI);
8338 case ISD::SELECT_CC:
8339 return DAGCombineTruncBoolExt(N, DCI);
8340 case ISD::SINT_TO_FP:
8341 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8342 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8343 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8344 // We allow the src/dst to be either f32/f64, but the intermediate
8345 // type must be i64.
8346 if (N->getOperand(0).getValueType() == MVT::i64 &&
8347 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8348 SDValue Val = N->getOperand(0).getOperand(0);
8349 if (Val.getValueType() == MVT::f32) {
8350 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8351 DCI.AddToWorklist(Val.getNode());
8354 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8355 DCI.AddToWorklist(Val.getNode());
8356 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8357 DCI.AddToWorklist(Val.getNode());
8358 if (N->getValueType(0) == MVT::f32) {
8359 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8360 DAG.getIntPtrConstant(0));
8361 DCI.AddToWorklist(Val.getNode());
8364 } else if (N->getOperand(0).getValueType() == MVT::i32) {
8365 // If the intermediate type is i32, we can avoid the load/store here
8372 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8373 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8374 !cast<StoreSDNode>(N)->isTruncatingStore() &&
8375 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8376 N->getOperand(1).getValueType() == MVT::i32 &&
8377 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8378 SDValue Val = N->getOperand(1).getOperand(0);
8379 if (Val.getValueType() == MVT::f32) {
8380 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8381 DCI.AddToWorklist(Val.getNode());
8383 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8384 DCI.AddToWorklist(Val.getNode());
8387 N->getOperand(0), Val, N->getOperand(2),
8388 DAG.getValueType(N->getOperand(1).getValueType())
8391 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8392 DAG.getVTList(MVT::Other), Ops,
8393 cast<StoreSDNode>(N)->getMemoryVT(),
8394 cast<StoreSDNode>(N)->getMemOperand());
8395 DCI.AddToWorklist(Val.getNode());
8399 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8400 if (cast<StoreSDNode>(N)->isUnindexed() &&
8401 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8402 N->getOperand(1).getNode()->hasOneUse() &&
8403 (N->getOperand(1).getValueType() == MVT::i32 ||
8404 N->getOperand(1).getValueType() == MVT::i16 ||
8405 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8406 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8407 N->getOperand(1).getValueType() == MVT::i64))) {
8408 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8409 // Do an any-extend to 32-bits if this is a half-word input.
8410 if (BSwapOp.getValueType() == MVT::i16)
8411 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8414 N->getOperand(0), BSwapOp, N->getOperand(2),
8415 DAG.getValueType(N->getOperand(1).getValueType())
8418 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8419 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8420 cast<StoreSDNode>(N)->getMemOperand());
8424 LoadSDNode *LD = cast<LoadSDNode>(N);
8425 EVT VT = LD->getValueType(0);
8426 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8427 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8428 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8429 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8430 // P8 and later hardware should just use LOAD.
8431 !TM.getSubtarget<PPCSubtarget>().hasP8Vector() &&
8432 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8433 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8434 LD->getAlignment() < ABIAlignment) {
8435 // This is a type-legal unaligned Altivec load.
8436 SDValue Chain = LD->getChain();
8437 SDValue Ptr = LD->getBasePtr();
8438 bool isLittleEndian = Subtarget.isLittleEndian();
8440 // This implements the loading of unaligned vectors as described in
8441 // the venerable Apple Velocity Engine overview. Specifically:
8442 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8443 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8445 // The general idea is to expand a sequence of one or more unaligned
8446 // loads into an alignment-based permutation-control instruction (lvsl
8447 // or lvsr), a series of regular vector loads (which always truncate
8448 // their input address to an aligned address), and a series of
8449 // permutations. The results of these permutations are the requested
8450 // loaded values. The trick is that the last "extra" load is not taken
8451 // from the address you might suspect (sizeof(vector) bytes after the
8452 // last requested load), but rather sizeof(vector) - 1 bytes after the
8453 // last requested vector. The point of this is to avoid a page fault if
8454 // the base address happened to be aligned. This works because if the
8455 // base address is aligned, then adding less than a full vector length
8456 // will cause the last vector in the sequence to be (re)loaded.
8457 // Otherwise, the next vector will be fetched as you might suspect was
8460 // We might be able to reuse the permutation generation from
8461 // a different base address offset from this one by an aligned amount.
8462 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8463 // optimization later.
8464 Intrinsic::ID Intr = (isLittleEndian ?
8465 Intrinsic::ppc_altivec_lvsr :
8466 Intrinsic::ppc_altivec_lvsl);
8467 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8469 // Create the new MMO for the new base load. It is like the original MMO,
8470 // but represents an area in memory almost twice the vector size centered
8471 // on the original address. If the address is unaligned, we might start
8472 // reading up to (sizeof(vector)-1) bytes below the address of the
8473 // original unaligned load.
8474 MachineFunction &MF = DAG.getMachineFunction();
8475 MachineMemOperand *BaseMMO =
8476 MF.getMachineMemOperand(LD->getMemOperand(),
8477 -LD->getMemoryVT().getStoreSize()+1,
8478 2*LD->getMemoryVT().getStoreSize()-1);
8480 // Create the new base load.
8481 SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8483 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8485 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8486 DAG.getVTList(MVT::v4i32, MVT::Other),
8487 BaseLoadOps, MVT::v4i32, BaseMMO);
8489 // Note that the value of IncOffset (which is provided to the next
8490 // load's pointer info offset value, and thus used to calculate the
8491 // alignment), and the value of IncValue (which is actually used to
8492 // increment the pointer value) are different! This is because we
8493 // require the next load to appear to be aligned, even though it
8494 // is actually offset from the base pointer by a lesser amount.
8495 int IncOffset = VT.getSizeInBits() / 8;
8496 int IncValue = IncOffset;
8498 // Walk (both up and down) the chain looking for another load at the real
8499 // (aligned) offset (the alignment of the other load does not matter in
8500 // this case). If found, then do not use the offset reduction trick, as
8501 // that will prevent the loads from being later combined (as they would
8502 // otherwise be duplicates).
8503 if (!findConsecutiveLoad(LD, DAG))
8506 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8507 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8509 MachineMemOperand *ExtraMMO =
8510 MF.getMachineMemOperand(LD->getMemOperand(),
8511 1, 2*LD->getMemoryVT().getStoreSize()-1);
8512 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8514 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8515 DAG.getVTList(MVT::v4i32, MVT::Other),
8516 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8518 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8519 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8521 // Because vperm has a big-endian bias, we must reverse the order
8522 // of the input vectors and complement the permute control vector
8523 // when generating little endian code. We have already handled the
8524 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8525 // and ExtraLoad here.
8528 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8529 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8531 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8532 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8534 if (VT != MVT::v4i32)
8535 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8537 // The output of the permutation is our loaded result, the TokenFactor is
8539 DCI.CombineTo(N, Perm, TF);
8540 return SDValue(N, 0);
8544 case ISD::INTRINSIC_WO_CHAIN: {
8545 bool isLittleEndian = Subtarget.isLittleEndian();
8546 Intrinsic::ID Intr = (isLittleEndian ?
8547 Intrinsic::ppc_altivec_lvsr :
8548 Intrinsic::ppc_altivec_lvsl);
8549 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8550 N->getOperand(1)->getOpcode() == ISD::ADD) {
8551 SDValue Add = N->getOperand(1);
8553 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8554 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8555 Add.getValueType().getScalarType().getSizeInBits()))) {
8556 SDNode *BasePtr = Add->getOperand(0).getNode();
8557 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8558 UE = BasePtr->use_end(); UI != UE; ++UI) {
8559 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8560 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8562 // We've found another LVSL/LVSR, and this address is an aligned
8563 // multiple of that one. The results will be the same, so use the
8564 // one we've just found instead.
8566 return SDValue(*UI, 0);
8575 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8576 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8577 N->getOperand(0).hasOneUse() &&
8578 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8579 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8580 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8581 N->getValueType(0) == MVT::i64))) {
8582 SDValue Load = N->getOperand(0);
8583 LoadSDNode *LD = cast<LoadSDNode>(Load);
8584 // Create the byte-swapping load.
8586 LD->getChain(), // Chain
8587 LD->getBasePtr(), // Ptr
8588 DAG.getValueType(N->getValueType(0)) // VT
8591 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8592 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8593 MVT::i64 : MVT::i32, MVT::Other),
8594 Ops, LD->getMemoryVT(), LD->getMemOperand());
8596 // If this is an i16 load, insert the truncate.
8597 SDValue ResVal = BSLoad;
8598 if (N->getValueType(0) == MVT::i16)
8599 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8601 // First, combine the bswap away. This makes the value produced by the
8603 DCI.CombineTo(N, ResVal);
8605 // Next, combine the load away, we give it a bogus result value but a real
8606 // chain result. The result value is dead because the bswap is dead.
8607 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8609 // Return N so it doesn't get rechecked!
8610 return SDValue(N, 0);
8614 case PPCISD::VCMP: {
8615 // If a VCMPo node already exists with exactly the same operands as this
8616 // node, use its result instead of this node (VCMPo computes both a CR6 and
8617 // a normal output).
8619 if (!N->getOperand(0).hasOneUse() &&
8620 !N->getOperand(1).hasOneUse() &&
8621 !N->getOperand(2).hasOneUse()) {
8623 // Scan all of the users of the LHS, looking for VCMPo's that match.
8624 SDNode *VCMPoNode = nullptr;
8626 SDNode *LHSN = N->getOperand(0).getNode();
8627 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8629 if (UI->getOpcode() == PPCISD::VCMPo &&
8630 UI->getOperand(1) == N->getOperand(1) &&
8631 UI->getOperand(2) == N->getOperand(2) &&
8632 UI->getOperand(0) == N->getOperand(0)) {
8637 // If there is no VCMPo node, or if the flag value has a single use, don't
8639 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8642 // Look at the (necessarily single) use of the flag value. If it has a
8643 // chain, this transformation is more complex. Note that multiple things
8644 // could use the value result, which we should ignore.
8645 SDNode *FlagUser = nullptr;
8646 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8647 FlagUser == nullptr; ++UI) {
8648 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8650 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8651 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8658 // If the user is a MFOCRF instruction, we know this is safe.
8659 // Otherwise we give up for right now.
8660 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8661 return SDValue(VCMPoNode, 0);
8666 SDValue Cond = N->getOperand(1);
8667 SDValue Target = N->getOperand(2);
8669 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8670 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8671 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8673 // We now need to make the intrinsic dead (it cannot be instruction
8675 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8676 assert(Cond.getNode()->hasOneUse() &&
8677 "Counter decrement has more than one use");
8679 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8680 N->getOperand(0), Target);
8685 // If this is a branch on an altivec predicate comparison, lower this so
8686 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8687 // lowering is done pre-legalize, because the legalizer lowers the predicate
8688 // compare down to code that is difficult to reassemble.
8689 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8690 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8692 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8693 // value. If so, pass-through the AND to get to the intrinsic.
8694 if (LHS.getOpcode() == ISD::AND &&
8695 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8696 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8697 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8698 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8699 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8701 LHS = LHS.getOperand(0);
8703 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8704 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8705 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8706 isa<ConstantSDNode>(RHS)) {
8707 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8708 "Counter decrement comparison is not EQ or NE");
8710 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8711 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8712 (CC == ISD::SETNE && !Val);
8714 // We now need to make the intrinsic dead (it cannot be instruction
8716 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8717 assert(LHS.getNode()->hasOneUse() &&
8718 "Counter decrement has more than one use");
8720 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8721 N->getOperand(0), N->getOperand(4));
8727 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8728 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8729 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8730 assert(isDot && "Can't compare against a vector result!");
8732 // If this is a comparison against something other than 0/1, then we know
8733 // that the condition is never/always true.
8734 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8735 if (Val != 0 && Val != 1) {
8736 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8737 return N->getOperand(0);
8738 // Always !=, turn it into an unconditional branch.
8739 return DAG.getNode(ISD::BR, dl, MVT::Other,
8740 N->getOperand(0), N->getOperand(4));
8743 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8745 // Create the PPCISD altivec 'dot' comparison node.
8747 LHS.getOperand(2), // LHS of compare
8748 LHS.getOperand(3), // RHS of compare
8749 DAG.getConstant(CompareOpc, MVT::i32)
8751 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8752 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8754 // Unpack the result based on how the target uses it.
8755 PPC::Predicate CompOpc;
8756 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8757 default: // Can't happen, don't crash on invalid number though.
8758 case 0: // Branch on the value of the EQ bit of CR6.
8759 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8761 case 1: // Branch on the inverted value of the EQ bit of CR6.
8762 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8764 case 2: // Branch on the value of the LT bit of CR6.
8765 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8767 case 3: // Branch on the inverted value of the LT bit of CR6.
8768 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8772 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8773 DAG.getConstant(CompOpc, MVT::i32),
8774 DAG.getRegister(PPC::CR6, MVT::i32),
8775 N->getOperand(4), CompNode.getValue(1));
8784 //===----------------------------------------------------------------------===//
8785 // Inline Assembly Support
8786 //===----------------------------------------------------------------------===//
8788 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8791 const SelectionDAG &DAG,
8792 unsigned Depth) const {
8793 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8794 switch (Op.getOpcode()) {
8796 case PPCISD::LBRX: {
8797 // lhbrx is known to have the top bits cleared out.
8798 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8799 KnownZero = 0xFFFF0000;
8802 case ISD::INTRINSIC_WO_CHAIN: {
8803 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8805 case Intrinsic::ppc_altivec_vcmpbfp_p:
8806 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8807 case Intrinsic::ppc_altivec_vcmpequb_p:
8808 case Intrinsic::ppc_altivec_vcmpequh_p:
8809 case Intrinsic::ppc_altivec_vcmpequw_p:
8810 case Intrinsic::ppc_altivec_vcmpgefp_p:
8811 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8812 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8813 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8814 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8815 case Intrinsic::ppc_altivec_vcmpgtub_p:
8816 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8817 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8818 KnownZero = ~1U; // All bits but the low one are known to be zero.
8826 /// getConstraintType - Given a constraint, return the type of
8827 /// constraint it is for this target.
8828 PPCTargetLowering::ConstraintType
8829 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8830 if (Constraint.size() == 1) {
8831 switch (Constraint[0]) {
8838 return C_RegisterClass;
8840 // FIXME: While Z does indicate a memory constraint, it specifically
8841 // indicates an r+r address (used in conjunction with the 'y' modifier
8842 // in the replacement string). Currently, we're forcing the base
8843 // register to be r0 in the asm printer (which is interpreted as zero)
8844 // and forming the complete address in the second register. This is
8848 } else if (Constraint == "wc") { // individual CR bits.
8849 return C_RegisterClass;
8850 } else if (Constraint == "wa" || Constraint == "wd" ||
8851 Constraint == "wf" || Constraint == "ws") {
8852 return C_RegisterClass; // VSX registers.
8854 return TargetLowering::getConstraintType(Constraint);
8857 /// Examine constraint type and operand type and determine a weight value.
8858 /// This object must already have been set up with the operand type
8859 /// and the current alternative constraint selected.
8860 TargetLowering::ConstraintWeight
8861 PPCTargetLowering::getSingleConstraintMatchWeight(
8862 AsmOperandInfo &info, const char *constraint) const {
8863 ConstraintWeight weight = CW_Invalid;
8864 Value *CallOperandVal = info.CallOperandVal;
8865 // If we don't have a value, we can't do a match,
8866 // but allow it at the lowest weight.
8867 if (!CallOperandVal)
8869 Type *type = CallOperandVal->getType();
8871 // Look at the constraint type.
8872 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8873 return CW_Register; // an individual CR bit.
8874 else if ((StringRef(constraint) == "wa" ||
8875 StringRef(constraint) == "wd" ||
8876 StringRef(constraint) == "wf") &&
8879 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8882 switch (*constraint) {
8884 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8887 if (type->isIntegerTy())
8888 weight = CW_Register;
8891 if (type->isFloatTy())
8892 weight = CW_Register;
8895 if (type->isDoubleTy())
8896 weight = CW_Register;
8899 if (type->isVectorTy())
8900 weight = CW_Register;
8903 weight = CW_Register;
8912 std::pair<unsigned, const TargetRegisterClass*>
8913 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8915 if (Constraint.size() == 1) {
8916 // GCC RS6000 Constraint Letters
8917 switch (Constraint[0]) {
8919 if (VT == MVT::i64 && Subtarget.isPPC64())
8920 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8921 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8923 if (VT == MVT::i64 && Subtarget.isPPC64())
8924 return std::make_pair(0U, &PPC::G8RCRegClass);
8925 return std::make_pair(0U, &PPC::GPRCRegClass);
8927 if (VT == MVT::f32 || VT == MVT::i32)
8928 return std::make_pair(0U, &PPC::F4RCRegClass);
8929 if (VT == MVT::f64 || VT == MVT::i64)
8930 return std::make_pair(0U, &PPC::F8RCRegClass);
8933 return std::make_pair(0U, &PPC::VRRCRegClass);
8935 return std::make_pair(0U, &PPC::CRRCRegClass);
8937 } else if (Constraint == "wc") { // an individual CR bit.
8938 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8939 } else if (Constraint == "wa" || Constraint == "wd" ||
8940 Constraint == "wf") {
8941 return std::make_pair(0U, &PPC::VSRCRegClass);
8942 } else if (Constraint == "ws") {
8943 return std::make_pair(0U, &PPC::VSFRCRegClass);
8946 std::pair<unsigned, const TargetRegisterClass*> R =
8947 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8949 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8950 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8951 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8953 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8954 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8955 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
8956 PPC::GPRCRegClass.contains(R.first)) {
8957 const TargetRegisterInfo *TRI =
8958 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8959 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8960 PPC::sub_32, &PPC::G8RCRegClass),
8961 &PPC::G8RCRegClass);
8968 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8969 /// vector. If it is invalid, don't add anything to Ops.
8970 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8971 std::string &Constraint,
8972 std::vector<SDValue>&Ops,
8973 SelectionDAG &DAG) const {
8976 // Only support length 1 constraints.
8977 if (Constraint.length() > 1) return;
8979 char Letter = Constraint[0];
8990 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8991 if (!CST) return; // Must be an immediate to match.
8992 unsigned Value = CST->getZExtValue();
8994 default: llvm_unreachable("Unknown constraint letter!");
8995 case 'I': // "I" is a signed 16-bit constant.
8996 if ((short)Value == (int)Value)
8997 Result = DAG.getTargetConstant(Value, Op.getValueType());
8999 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
9000 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
9001 if ((short)Value == 0)
9002 Result = DAG.getTargetConstant(Value, Op.getValueType());
9004 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
9005 if ((Value >> 16) == 0)
9006 Result = DAG.getTargetConstant(Value, Op.getValueType());
9008 case 'M': // "M" is a constant that is greater than 31.
9010 Result = DAG.getTargetConstant(Value, Op.getValueType());
9012 case 'N': // "N" is a positive constant that is an exact power of two.
9013 if ((int)Value > 0 && isPowerOf2_32(Value))
9014 Result = DAG.getTargetConstant(Value, Op.getValueType());
9016 case 'O': // "O" is the constant zero.
9018 Result = DAG.getTargetConstant(Value, Op.getValueType());
9020 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
9021 if ((short)-Value == (int)-Value)
9022 Result = DAG.getTargetConstant(Value, Op.getValueType());
9029 if (Result.getNode()) {
9030 Ops.push_back(Result);
9034 // Handle standard constraint letters.
9035 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9038 // isLegalAddressingMode - Return true if the addressing mode represented
9039 // by AM is legal for this target, for a load/store of the specified type.
9040 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9042 // FIXME: PPC does not allow r+i addressing modes for vectors!
9044 // PPC allows a sign-extended 16-bit immediate field.
9045 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9048 // No global is ever allowed as a base.
9052 // PPC only support r+r,
9054 case 0: // "r+i" or just "i", depending on HasBaseReg.
9057 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
9059 // Otherwise we have r+r or r+i.
9062 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
9064 // Allow 2*r as r+r.
9067 // No other scales are supported.
9074 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9075 SelectionDAG &DAG) const {
9076 MachineFunction &MF = DAG.getMachineFunction();
9077 MachineFrameInfo *MFI = MF.getFrameInfo();
9078 MFI->setReturnAddressIsTaken(true);
9080 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9084 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9086 // Make sure the function does not optimize away the store of the RA to
9088 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9089 FuncInfo->setLRStoreRequired();
9090 bool isPPC64 = Subtarget.isPPC64();
9091 bool isDarwinABI = Subtarget.isDarwinABI();
9094 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9097 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9098 isPPC64? MVT::i64 : MVT::i32);
9099 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9100 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9102 MachinePointerInfo(), false, false, false, 0);
9105 // Just load the return address off the stack.
9106 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9107 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9108 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9111 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9112 SelectionDAG &DAG) const {
9114 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9116 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9117 bool isPPC64 = PtrVT == MVT::i64;
9119 MachineFunction &MF = DAG.getMachineFunction();
9120 MachineFrameInfo *MFI = MF.getFrameInfo();
9121 MFI->setFrameAddressIsTaken(true);
9123 // Naked functions never have a frame pointer, and so we use r1. For all
9124 // other functions, this decision must be delayed until during PEI.
9126 if (MF.getFunction()->getAttributes().hasAttribute(
9127 AttributeSet::FunctionIndex, Attribute::Naked))
9128 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9130 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9132 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9135 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9136 FrameAddr, MachinePointerInfo(), false, false,
9141 // FIXME? Maybe this could be a TableGen attribute on some registers and
9142 // this table could be generated automatically from RegInfo.
9143 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9145 bool isPPC64 = Subtarget.isPPC64();
9146 bool isDarwinABI = Subtarget.isDarwinABI();
9148 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9149 (!isPPC64 && VT != MVT::i32))
9150 report_fatal_error("Invalid register global variable type");
9152 bool is64Bit = isPPC64 && VT == MVT::i64;
9153 unsigned Reg = StringSwitch<unsigned>(RegName)
9154 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9155 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9156 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9157 (is64Bit ? PPC::X13 : PPC::R13))
9162 report_fatal_error("Invalid register name global variable");
9166 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9167 // The PowerPC target isn't yet aware of offsets.
9171 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9173 unsigned Intrinsic) const {
9175 switch (Intrinsic) {
9176 case Intrinsic::ppc_altivec_lvx:
9177 case Intrinsic::ppc_altivec_lvxl:
9178 case Intrinsic::ppc_altivec_lvebx:
9179 case Intrinsic::ppc_altivec_lvehx:
9180 case Intrinsic::ppc_altivec_lvewx:
9181 case Intrinsic::ppc_vsx_lxvd2x:
9182 case Intrinsic::ppc_vsx_lxvw4x: {
9184 switch (Intrinsic) {
9185 case Intrinsic::ppc_altivec_lvebx:
9188 case Intrinsic::ppc_altivec_lvehx:
9191 case Intrinsic::ppc_altivec_lvewx:
9194 case Intrinsic::ppc_vsx_lxvd2x:
9202 Info.opc = ISD::INTRINSIC_W_CHAIN;
9204 Info.ptrVal = I.getArgOperand(0);
9205 Info.offset = -VT.getStoreSize()+1;
9206 Info.size = 2*VT.getStoreSize()-1;
9209 Info.readMem = true;
9210 Info.writeMem = false;
9213 case Intrinsic::ppc_altivec_stvx:
9214 case Intrinsic::ppc_altivec_stvxl:
9215 case Intrinsic::ppc_altivec_stvebx:
9216 case Intrinsic::ppc_altivec_stvehx:
9217 case Intrinsic::ppc_altivec_stvewx:
9218 case Intrinsic::ppc_vsx_stxvd2x:
9219 case Intrinsic::ppc_vsx_stxvw4x: {
9221 switch (Intrinsic) {
9222 case Intrinsic::ppc_altivec_stvebx:
9225 case Intrinsic::ppc_altivec_stvehx:
9228 case Intrinsic::ppc_altivec_stvewx:
9231 case Intrinsic::ppc_vsx_stxvd2x:
9239 Info.opc = ISD::INTRINSIC_VOID;
9241 Info.ptrVal = I.getArgOperand(1);
9242 Info.offset = -VT.getStoreSize()+1;
9243 Info.size = 2*VT.getStoreSize()-1;
9246 Info.readMem = false;
9247 Info.writeMem = true;
9257 /// getOptimalMemOpType - Returns the target specific optimal type for load
9258 /// and store operations as a result of memset, memcpy, and memmove
9259 /// lowering. If DstAlign is zero that means it's safe to destination
9260 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9261 /// means there isn't a need to check it against alignment requirement,
9262 /// probably because the source does not need to be loaded. If 'IsMemset' is
9263 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9264 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9265 /// source is constant so it does not need to be loaded.
9266 /// It returns EVT::Other if the type should be determined using generic
9267 /// target-independent logic.
9268 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9269 unsigned DstAlign, unsigned SrcAlign,
9270 bool IsMemset, bool ZeroMemset,
9272 MachineFunction &MF) const {
9273 if (Subtarget.isPPC64()) {
9280 /// \brief Returns true if it is beneficial to convert a load of a constant
9281 /// to just the constant itself.
9282 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9284 assert(Ty->isIntegerTy());
9286 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9287 if (BitSize == 0 || BitSize > 64)
9292 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9293 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9295 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9296 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9297 return NumBits1 == 64 && NumBits2 == 32;
9300 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9301 if (!VT1.isInteger() || !VT2.isInteger())
9303 unsigned NumBits1 = VT1.getSizeInBits();
9304 unsigned NumBits2 = VT2.getSizeInBits();
9305 return NumBits1 == 64 && NumBits2 == 32;
9308 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9309 return isInt<16>(Imm) || isUInt<16>(Imm);
9312 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9313 return isInt<16>(Imm) || isUInt<16>(Imm);
9316 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9320 if (DisablePPCUnaligned)
9323 // PowerPC supports unaligned memory access for simple non-vector types.
9324 // Although accessing unaligned addresses is not as efficient as accessing
9325 // aligned addresses, it is generally more efficient than manual expansion,
9326 // and generally only traps for software emulation when crossing page
9332 if (VT.getSimpleVT().isVector()) {
9333 if (Subtarget.hasVSX()) {
9334 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9335 VT != MVT::v4f32 && VT != MVT::v4i32)
9342 if (VT == MVT::ppcf128)
9351 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9352 VT = VT.getScalarType();
9357 switch (VT.getSimpleVT().SimpleTy) {
9369 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9370 EVT VT , unsigned DefinedValues) const {
9371 if (VT == MVT::v2i64)
9374 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9377 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9378 if (DisableILPPref || Subtarget.enableMachineScheduler())
9379 return TargetLowering::getSchedulingPreference(N);
9384 // Create a fast isel object.
9386 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9387 const TargetLibraryInfo *LibInfo) const {
9388 return PPC::createFastISel(FuncInfo, LibInfo);