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/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAG.h"
30 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetOptions.h"
43 // FIXME: Remove this once soft-float is supported.
44 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
45 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
47 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
48 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
50 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
51 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
53 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
54 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
56 // FIXME: Remove this once the bug has been fixed!
57 extern cl::opt<bool> ANDIGlueBug;
59 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM)
61 Subtarget(*TM.getSubtargetImpl()) {
62 // Use _setjmp/_longjmp instead of setjmp/longjmp.
63 setUseUnderscoreSetJmp(true);
64 setUseUnderscoreLongJmp(true);
66 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
67 // arguments are at least 4/8 bytes aligned.
68 bool isPPC64 = Subtarget.isPPC64();
69 setMinStackArgumentAlignment(isPPC64 ? 8:4);
71 // Set up the register classes.
72 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
73 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
74 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
76 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
77 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
78 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
80 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
82 // PowerPC has pre-inc load and store's.
83 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
84 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
85 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
86 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
88 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
89 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
90 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
91 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
92 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
94 if (Subtarget.useCRBits()) {
95 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
97 if (isPPC64 || Subtarget.hasFPCVT()) {
98 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
99 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
100 isPPC64 ? MVT::i64 : MVT::i32);
101 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
102 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
103 isPPC64 ? MVT::i64 : MVT::i32);
105 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
106 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
109 // PowerPC does not support direct load / store of condition registers
110 setOperationAction(ISD::LOAD, MVT::i1, Custom);
111 setOperationAction(ISD::STORE, MVT::i1, Custom);
113 // FIXME: Remove this once the ANDI glue bug is fixed:
115 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
117 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
118 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
119 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
120 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
121 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
122 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
124 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
127 // This is used in the ppcf128->int sequence. Note it has different semantics
128 // from FP_ROUND: that rounds to nearest, this rounds to zero.
129 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
131 // We do not currently implement these libm ops for PowerPC.
132 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
133 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
134 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
135 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
136 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
137 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
139 // PowerPC has no SREM/UREM instructions
140 setOperationAction(ISD::SREM, MVT::i32, Expand);
141 setOperationAction(ISD::UREM, MVT::i32, Expand);
142 setOperationAction(ISD::SREM, MVT::i64, Expand);
143 setOperationAction(ISD::UREM, MVT::i64, Expand);
145 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
146 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
147 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
148 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
149 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
150 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
151 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
152 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
153 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
155 // We don't support sin/cos/sqrt/fmod/pow
156 setOperationAction(ISD::FSIN , MVT::f64, Expand);
157 setOperationAction(ISD::FCOS , MVT::f64, Expand);
158 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
159 setOperationAction(ISD::FREM , MVT::f64, Expand);
160 setOperationAction(ISD::FPOW , MVT::f64, Expand);
161 setOperationAction(ISD::FMA , MVT::f64, Legal);
162 setOperationAction(ISD::FSIN , MVT::f32, Expand);
163 setOperationAction(ISD::FCOS , MVT::f32, Expand);
164 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
165 setOperationAction(ISD::FREM , MVT::f32, Expand);
166 setOperationAction(ISD::FPOW , MVT::f32, Expand);
167 setOperationAction(ISD::FMA , MVT::f32, Legal);
169 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
171 // If we're enabling GP optimizations, use hardware square root
172 if (!Subtarget.hasFSQRT() &&
173 !(TM.Options.UnsafeFPMath &&
174 Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
175 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
177 if (!Subtarget.hasFSQRT() &&
178 !(TM.Options.UnsafeFPMath &&
179 Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
180 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
182 if (Subtarget.hasFCPSGN()) {
183 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
184 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
186 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
187 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
190 if (Subtarget.hasFPRND()) {
191 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
192 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
193 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
194 setOperationAction(ISD::FROUND, MVT::f64, Legal);
196 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
197 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
198 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
199 setOperationAction(ISD::FROUND, MVT::f32, Legal);
202 // PowerPC does not have BSWAP, CTPOP or CTTZ
203 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
204 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
205 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
206 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
207 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
208 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
209 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
210 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
212 if (Subtarget.hasPOPCNTD()) {
213 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
214 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
216 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
217 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
220 // PowerPC does not have ROTR
221 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
222 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
224 if (!Subtarget.useCRBits()) {
225 // PowerPC does not have Select
226 setOperationAction(ISD::SELECT, MVT::i32, Expand);
227 setOperationAction(ISD::SELECT, MVT::i64, Expand);
228 setOperationAction(ISD::SELECT, MVT::f32, Expand);
229 setOperationAction(ISD::SELECT, MVT::f64, Expand);
232 // PowerPC wants to turn select_cc of FP into fsel when possible.
233 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
234 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
236 // PowerPC wants to optimize integer setcc a bit
237 if (!Subtarget.useCRBits())
238 setOperationAction(ISD::SETCC, MVT::i32, Custom);
240 // PowerPC does not have BRCOND which requires SetCC
241 if (!Subtarget.useCRBits())
242 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
244 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
246 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
247 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
249 // PowerPC does not have [U|S]INT_TO_FP
250 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
251 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
253 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
254 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
255 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
256 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
258 // We cannot sextinreg(i1). Expand to shifts.
259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
261 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
262 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
263 // support continuation, user-level threading, and etc.. As a result, no
264 // other SjLj exception interfaces are implemented and please don't build
265 // your own exception handling based on them.
266 // LLVM/Clang supports zero-cost DWARF exception handling.
267 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
268 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
270 // We want to legalize GlobalAddress and ConstantPool nodes into the
271 // appropriate instructions to materialize the address.
272 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
273 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
274 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
275 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
276 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
277 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
278 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
279 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
280 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
281 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
284 setOperationAction(ISD::TRAP, MVT::Other, Legal);
286 // TRAMPOLINE is custom lowered.
287 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
288 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
290 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
291 setOperationAction(ISD::VASTART , MVT::Other, Custom);
293 if (Subtarget.isSVR4ABI()) {
295 // VAARG always uses double-word chunks, so promote anything smaller.
296 setOperationAction(ISD::VAARG, MVT::i1, Promote);
297 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
298 setOperationAction(ISD::VAARG, MVT::i8, Promote);
299 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
300 setOperationAction(ISD::VAARG, MVT::i16, Promote);
301 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
302 setOperationAction(ISD::VAARG, MVT::i32, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::Other, Expand);
306 // VAARG is custom lowered with the 32-bit SVR4 ABI.
307 setOperationAction(ISD::VAARG, MVT::Other, Custom);
308 setOperationAction(ISD::VAARG, MVT::i64, Custom);
311 setOperationAction(ISD::VAARG, MVT::Other, Expand);
313 if (Subtarget.isSVR4ABI() && !isPPC64)
314 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
315 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
317 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
319 // Use the default implementation.
320 setOperationAction(ISD::VAEND , MVT::Other, Expand);
321 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
322 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
323 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
324 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
326 // We want to custom lower some of our intrinsics.
327 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
329 // To handle counter-based loop conditions.
330 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
332 // Comparisons that require checking two conditions.
333 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
334 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
335 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
336 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
337 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
338 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
339 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
346 if (Subtarget.has64BitSupport()) {
347 // They also have instructions for converting between i64 and fp.
348 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
349 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
350 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
351 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
352 // This is just the low 32 bits of a (signed) fp->i64 conversion.
353 // We cannot do this with Promote because i64 is not a legal type.
354 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
356 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
357 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
359 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
363 // With the instructions enabled under FPCVT, we can do everything.
364 if (Subtarget.hasFPCVT()) {
365 if (Subtarget.has64BitSupport()) {
366 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
367 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
368 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
369 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
372 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
373 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
374 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
375 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
378 if (Subtarget.use64BitRegs()) {
379 // 64-bit PowerPC implementations can support i64 types directly
380 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
381 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
382 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
383 // 64-bit PowerPC wants to expand i128 shifts itself.
384 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
385 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
386 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
388 // 32-bit PowerPC wants to expand i64 shifts itself.
389 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
390 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
391 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
394 if (Subtarget.hasAltivec()) {
395 // First set operation action for all vector types to expand. Then we
396 // will selectively turn on ones that can be effectively codegen'd.
397 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
398 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
399 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
401 // add/sub are legal for all supported vector VT's.
402 setOperationAction(ISD::ADD , VT, Legal);
403 setOperationAction(ISD::SUB , VT, Legal);
405 // We promote all shuffles to v16i8.
406 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
407 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
409 // We promote all non-typed operations to v4i32.
410 setOperationAction(ISD::AND , VT, Promote);
411 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
412 setOperationAction(ISD::OR , VT, Promote);
413 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
414 setOperationAction(ISD::XOR , VT, Promote);
415 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
416 setOperationAction(ISD::LOAD , VT, Promote);
417 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
418 setOperationAction(ISD::SELECT, VT, Promote);
419 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
420 setOperationAction(ISD::STORE, VT, Promote);
421 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
423 // No other operations are legal.
424 setOperationAction(ISD::MUL , VT, Expand);
425 setOperationAction(ISD::SDIV, VT, Expand);
426 setOperationAction(ISD::SREM, VT, Expand);
427 setOperationAction(ISD::UDIV, VT, Expand);
428 setOperationAction(ISD::UREM, VT, Expand);
429 setOperationAction(ISD::FDIV, VT, Expand);
430 setOperationAction(ISD::FREM, VT, Expand);
431 setOperationAction(ISD::FNEG, VT, Expand);
432 setOperationAction(ISD::FSQRT, VT, Expand);
433 setOperationAction(ISD::FLOG, VT, Expand);
434 setOperationAction(ISD::FLOG10, VT, Expand);
435 setOperationAction(ISD::FLOG2, VT, Expand);
436 setOperationAction(ISD::FEXP, VT, Expand);
437 setOperationAction(ISD::FEXP2, VT, Expand);
438 setOperationAction(ISD::FSIN, VT, Expand);
439 setOperationAction(ISD::FCOS, VT, Expand);
440 setOperationAction(ISD::FABS, VT, Expand);
441 setOperationAction(ISD::FPOWI, VT, Expand);
442 setOperationAction(ISD::FFLOOR, VT, Expand);
443 setOperationAction(ISD::FCEIL, VT, Expand);
444 setOperationAction(ISD::FTRUNC, VT, Expand);
445 setOperationAction(ISD::FRINT, VT, Expand);
446 setOperationAction(ISD::FNEARBYINT, VT, Expand);
447 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
448 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
449 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
450 setOperationAction(ISD::MULHU, VT, Expand);
451 setOperationAction(ISD::MULHS, VT, Expand);
452 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
453 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
454 setOperationAction(ISD::UDIVREM, VT, Expand);
455 setOperationAction(ISD::SDIVREM, VT, Expand);
456 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
457 setOperationAction(ISD::FPOW, VT, Expand);
458 setOperationAction(ISD::BSWAP, VT, Expand);
459 setOperationAction(ISD::CTPOP, VT, Expand);
460 setOperationAction(ISD::CTLZ, VT, Expand);
461 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
462 setOperationAction(ISD::CTTZ, VT, Expand);
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
464 setOperationAction(ISD::VSELECT, VT, Expand);
465 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
467 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
468 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
469 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
470 setTruncStoreAction(VT, InnerVT, Expand);
472 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
473 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
474 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
477 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
478 // with merges, splats, etc.
479 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
481 setOperationAction(ISD::AND , MVT::v4i32, Legal);
482 setOperationAction(ISD::OR , MVT::v4i32, Legal);
483 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
484 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
485 setOperationAction(ISD::SELECT, MVT::v4i32,
486 Subtarget.useCRBits() ? Legal : Expand);
487 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
488 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
489 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
490 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
491 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
492 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
493 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
494 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
495 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
497 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
498 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
499 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
500 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
502 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
503 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
505 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
506 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
507 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
510 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
511 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
512 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
514 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
515 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
517 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
518 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
519 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
520 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
522 // Altivec does not contain unordered floating-point compare instructions
523 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
524 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
525 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
526 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
528 if (Subtarget.hasVSX()) {
529 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
530 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
532 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
533 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
534 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
535 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
536 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
538 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
540 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
541 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
543 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
544 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
546 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
547 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
548 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
549 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
550 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
552 // Share the Altivec comparison restrictions.
553 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
554 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
555 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
556 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
558 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
559 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
561 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
563 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
565 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
566 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
568 // VSX v2i64 only supports non-arithmetic operations.
569 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
570 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
572 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
573 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
574 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
576 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
578 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
579 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
580 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
581 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
583 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
585 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
586 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
587 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
588 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
590 // Vector operation legalization checks the result type of
591 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
592 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
593 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
594 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
595 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
597 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
601 if (Subtarget.has64BitSupport())
602 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
604 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
607 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
608 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
611 setBooleanContents(ZeroOrOneBooleanContent);
612 // Altivec instructions set fields to all zeros or all ones.
613 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
616 // These libcalls are not available in 32-bit.
617 setLibcallName(RTLIB::SHL_I128, nullptr);
618 setLibcallName(RTLIB::SRL_I128, nullptr);
619 setLibcallName(RTLIB::SRA_I128, nullptr);
623 setStackPointerRegisterToSaveRestore(PPC::X1);
624 setExceptionPointerRegister(PPC::X3);
625 setExceptionSelectorRegister(PPC::X4);
627 setStackPointerRegisterToSaveRestore(PPC::R1);
628 setExceptionPointerRegister(PPC::R3);
629 setExceptionSelectorRegister(PPC::R4);
632 // We have target-specific dag combine patterns for the following nodes:
633 setTargetDAGCombine(ISD::SINT_TO_FP);
634 if (Subtarget.hasFPCVT())
635 setTargetDAGCombine(ISD::UINT_TO_FP);
636 setTargetDAGCombine(ISD::LOAD);
637 setTargetDAGCombine(ISD::STORE);
638 setTargetDAGCombine(ISD::BR_CC);
639 if (Subtarget.useCRBits())
640 setTargetDAGCombine(ISD::BRCOND);
641 setTargetDAGCombine(ISD::BSWAP);
642 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
643 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
644 setTargetDAGCombine(ISD::INTRINSIC_VOID);
646 setTargetDAGCombine(ISD::SIGN_EXTEND);
647 setTargetDAGCombine(ISD::ZERO_EXTEND);
648 setTargetDAGCombine(ISD::ANY_EXTEND);
650 if (Subtarget.useCRBits()) {
651 setTargetDAGCombine(ISD::TRUNCATE);
652 setTargetDAGCombine(ISD::SETCC);
653 setTargetDAGCombine(ISD::SELECT_CC);
656 // Use reciprocal estimates.
657 if (TM.Options.UnsafeFPMath) {
658 setTargetDAGCombine(ISD::FDIV);
659 setTargetDAGCombine(ISD::FSQRT);
662 // Darwin long double math library functions have $LDBL128 appended.
663 if (Subtarget.isDarwin()) {
664 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
665 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
666 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
667 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
668 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
669 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
670 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
671 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
672 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
673 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
676 // With 32 condition bits, we don't need to sink (and duplicate) compares
677 // aggressively in CodeGenPrep.
678 if (Subtarget.useCRBits())
679 setHasMultipleConditionRegisters();
681 setMinFunctionAlignment(2);
682 if (Subtarget.isDarwin())
683 setPrefFunctionAlignment(4);
685 switch (Subtarget.getDarwinDirective()) {
689 case PPC::DIR_E500mc:
698 setPrefFunctionAlignment(4);
699 setPrefLoopAlignment(4);
703 setInsertFencesForAtomic(true);
705 if (Subtarget.enableMachineScheduler())
706 setSchedulingPreference(Sched::Source);
708 setSchedulingPreference(Sched::Hybrid);
710 computeRegisterProperties();
712 // The Freescale cores do better with aggressive inlining of memcpy and
713 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
714 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
715 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
716 MaxStoresPerMemset = 32;
717 MaxStoresPerMemsetOptSize = 16;
718 MaxStoresPerMemcpy = 32;
719 MaxStoresPerMemcpyOptSize = 8;
720 MaxStoresPerMemmove = 32;
721 MaxStoresPerMemmoveOptSize = 8;
725 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
726 /// the desired ByVal argument alignment.
727 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
728 unsigned MaxMaxAlign) {
729 if (MaxAlign == MaxMaxAlign)
731 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
732 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
734 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
736 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
737 unsigned EltAlign = 0;
738 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
739 if (EltAlign > MaxAlign)
741 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
742 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
743 unsigned EltAlign = 0;
744 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
745 if (EltAlign > MaxAlign)
747 if (MaxAlign == MaxMaxAlign)
753 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
754 /// function arguments in the caller parameter area.
755 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
756 // Darwin passes everything on 4 byte boundary.
757 if (Subtarget.isDarwin())
760 // 16byte and wider vectors are passed on 16byte boundary.
761 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
762 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
763 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
764 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
768 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
770 default: return nullptr;
771 case PPCISD::FSEL: return "PPCISD::FSEL";
772 case PPCISD::FCFID: return "PPCISD::FCFID";
773 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
774 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
775 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
776 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
777 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
778 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
779 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
780 case PPCISD::FRE: return "PPCISD::FRE";
781 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
782 case PPCISD::STFIWX: return "PPCISD::STFIWX";
783 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
784 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
785 case PPCISD::VPERM: return "PPCISD::VPERM";
786 case PPCISD::CMPB: return "PPCISD::CMPB";
787 case PPCISD::Hi: return "PPCISD::Hi";
788 case PPCISD::Lo: return "PPCISD::Lo";
789 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
790 case PPCISD::LOAD: return "PPCISD::LOAD";
791 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
792 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
793 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
794 case PPCISD::SRL: return "PPCISD::SRL";
795 case PPCISD::SRA: return "PPCISD::SRA";
796 case PPCISD::SHL: return "PPCISD::SHL";
797 case PPCISD::CALL: return "PPCISD::CALL";
798 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
799 case PPCISD::CALL_TLS: return "PPCISD::CALL_TLS";
800 case PPCISD::CALL_NOP_TLS: return "PPCISD::CALL_NOP_TLS";
801 case PPCISD::MTCTR: return "PPCISD::MTCTR";
802 case PPCISD::BCTRL: return "PPCISD::BCTRL";
803 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
804 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
805 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
806 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
807 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
808 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
809 case PPCISD::VCMP: return "PPCISD::VCMP";
810 case PPCISD::VCMPo: return "PPCISD::VCMPo";
811 case PPCISD::LBRX: return "PPCISD::LBRX";
812 case PPCISD::STBRX: return "PPCISD::STBRX";
813 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
814 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
815 case PPCISD::LARX: return "PPCISD::LARX";
816 case PPCISD::STCX: return "PPCISD::STCX";
817 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
818 case PPCISD::BDNZ: return "PPCISD::BDNZ";
819 case PPCISD::BDZ: return "PPCISD::BDZ";
820 case PPCISD::MFFS: return "PPCISD::MFFS";
821 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
822 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
823 case PPCISD::CR6SET: return "PPCISD::CR6SET";
824 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
825 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
826 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
827 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
828 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
829 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
830 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
831 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
832 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
833 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
834 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
835 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
836 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
837 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
838 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
839 case PPCISD::SC: return "PPCISD::SC";
843 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
845 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
846 return VT.changeVectorElementTypeToInteger();
849 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
850 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
854 //===----------------------------------------------------------------------===//
855 // Node matching predicates, for use by the tblgen matching code.
856 //===----------------------------------------------------------------------===//
858 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
859 static bool isFloatingPointZero(SDValue Op) {
860 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
861 return CFP->getValueAPF().isZero();
862 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
863 // Maybe this has already been legalized into the constant pool?
864 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
865 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
866 return CFP->getValueAPF().isZero();
871 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
872 /// true if Op is undef or if it matches the specified value.
873 static bool isConstantOrUndef(int Op, int Val) {
874 return Op < 0 || Op == Val;
877 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
878 /// VPKUHUM instruction.
879 /// The ShuffleKind distinguishes between big-endian operations with
880 /// two different inputs (0), either-endian operations with two identical
881 /// inputs (1), and little-endian operantion with two different inputs (2).
882 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
883 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
885 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
886 if (ShuffleKind == 0) {
889 for (unsigned i = 0; i != 16; ++i)
890 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
892 } else if (ShuffleKind == 2) {
895 for (unsigned i = 0; i != 16; ++i)
896 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
898 } else if (ShuffleKind == 1) {
899 unsigned j = IsLE ? 0 : 1;
900 for (unsigned i = 0; i != 8; ++i)
901 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
902 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
908 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
909 /// VPKUWUM instruction.
910 /// The ShuffleKind distinguishes between big-endian operations with
911 /// two different inputs (0), either-endian operations with two identical
912 /// inputs (1), and little-endian operantion with two different inputs (2).
913 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
914 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
916 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
917 if (ShuffleKind == 0) {
920 for (unsigned i = 0; i != 16; i += 2)
921 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
922 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
924 } else if (ShuffleKind == 2) {
927 for (unsigned i = 0; i != 16; i += 2)
928 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
929 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
931 } else if (ShuffleKind == 1) {
932 unsigned j = IsLE ? 0 : 2;
933 for (unsigned i = 0; i != 8; i += 2)
934 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
935 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
936 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
937 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
943 /// isVMerge - Common function, used to match vmrg* shuffles.
945 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
946 unsigned LHSStart, unsigned RHSStart) {
947 if (N->getValueType(0) != MVT::v16i8)
949 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
950 "Unsupported merge size!");
952 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
953 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
954 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
955 LHSStart+j+i*UnitSize) ||
956 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
957 RHSStart+j+i*UnitSize))
963 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
964 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
965 /// The ShuffleKind distinguishes between big-endian merges with two
966 /// different inputs (0), either-endian merges with two identical inputs (1),
967 /// and little-endian merges with two different inputs (2). For the latter,
968 /// the input operands are swapped (see PPCInstrAltivec.td).
969 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
970 unsigned ShuffleKind, SelectionDAG &DAG) {
971 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
972 if (ShuffleKind == 1) // unary
973 return isVMerge(N, UnitSize, 0, 0);
974 else if (ShuffleKind == 2) // swapped
975 return isVMerge(N, UnitSize, 0, 16);
979 if (ShuffleKind == 1) // unary
980 return isVMerge(N, UnitSize, 8, 8);
981 else if (ShuffleKind == 0) // normal
982 return isVMerge(N, UnitSize, 8, 24);
988 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
989 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
990 /// The ShuffleKind distinguishes between big-endian merges with two
991 /// different inputs (0), either-endian merges with two identical inputs (1),
992 /// and little-endian merges with two different inputs (2). For the latter,
993 /// the input operands are swapped (see PPCInstrAltivec.td).
994 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
995 unsigned ShuffleKind, SelectionDAG &DAG) {
996 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
997 if (ShuffleKind == 1) // unary
998 return isVMerge(N, UnitSize, 8, 8);
999 else if (ShuffleKind == 2) // swapped
1000 return isVMerge(N, UnitSize, 8, 24);
1004 if (ShuffleKind == 1) // unary
1005 return isVMerge(N, UnitSize, 0, 0);
1006 else if (ShuffleKind == 0) // normal
1007 return isVMerge(N, UnitSize, 0, 16);
1014 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1015 /// amount, otherwise return -1.
1016 /// The ShuffleKind distinguishes between big-endian operations with two
1017 /// different inputs (0), either-endian operations with two identical inputs
1018 /// (1), and little-endian operations with two different inputs (2). For the
1019 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1020 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1021 SelectionDAG &DAG) {
1022 if (N->getValueType(0) != MVT::v16i8)
1025 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1027 // Find the first non-undef value in the shuffle mask.
1029 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1032 if (i == 16) return -1; // all undef.
1034 // Otherwise, check to see if the rest of the elements are consecutively
1035 // numbered from this value.
1036 unsigned ShiftAmt = SVOp->getMaskElt(i);
1037 if (ShiftAmt < i) return -1;
1040 bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1043 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1044 // Check the rest of the elements to see if they are consecutive.
1045 for (++i; i != 16; ++i)
1046 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1048 } else if (ShuffleKind == 1) {
1049 // Check the rest of the elements to see if they are consecutive.
1050 for (++i; i != 16; ++i)
1051 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1056 if (ShuffleKind == 2 && isLE)
1057 ShiftAmt = 16 - ShiftAmt;
1062 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1063 /// specifies a splat of a single element that is suitable for input to
1064 /// VSPLTB/VSPLTH/VSPLTW.
1065 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1066 assert(N->getValueType(0) == MVT::v16i8 &&
1067 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1069 // This is a splat operation if each element of the permute is the same, and
1070 // if the value doesn't reference the second vector.
1071 unsigned ElementBase = N->getMaskElt(0);
1073 // FIXME: Handle UNDEF elements too!
1074 if (ElementBase >= 16)
1077 // Check that the indices are consecutive, in the case of a multi-byte element
1078 // splatted with a v16i8 mask.
1079 for (unsigned i = 1; i != EltSize; ++i)
1080 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1083 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1084 if (N->getMaskElt(i) < 0) continue;
1085 for (unsigned j = 0; j != EltSize; ++j)
1086 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1092 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1094 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1095 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1097 APInt APVal, APUndef;
1101 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1102 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1103 return CFP->getValueAPF().isNegZero();
1108 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1109 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1110 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1111 SelectionDAG &DAG) {
1112 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1113 assert(isSplatShuffleMask(SVOp, EltSize));
1114 if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1115 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1117 return SVOp->getMaskElt(0) / EltSize;
1120 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1121 /// by using a vspltis[bhw] instruction of the specified element size, return
1122 /// the constant being splatted. The ByteSize field indicates the number of
1123 /// bytes of each element [124] -> [bhw].
1124 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1125 SDValue OpVal(nullptr, 0);
1127 // If ByteSize of the splat is bigger than the element size of the
1128 // build_vector, then we have a case where we are checking for a splat where
1129 // multiple elements of the buildvector are folded together into a single
1130 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1131 unsigned EltSize = 16/N->getNumOperands();
1132 if (EltSize < ByteSize) {
1133 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1134 SDValue UniquedVals[4];
1135 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1137 // See if all of the elements in the buildvector agree across.
1138 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1139 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1140 // If the element isn't a constant, bail fully out.
1141 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1144 if (!UniquedVals[i&(Multiple-1)].getNode())
1145 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1146 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1147 return SDValue(); // no match.
1150 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1151 // either constant or undef values that are identical for each chunk. See
1152 // if these chunks can form into a larger vspltis*.
1154 // Check to see if all of the leading entries are either 0 or -1. If
1155 // neither, then this won't fit into the immediate field.
1156 bool LeadingZero = true;
1157 bool LeadingOnes = true;
1158 for (unsigned i = 0; i != Multiple-1; ++i) {
1159 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1161 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1162 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1164 // Finally, check the least significant entry.
1166 if (!UniquedVals[Multiple-1].getNode())
1167 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1168 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1170 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1173 if (!UniquedVals[Multiple-1].getNode())
1174 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1175 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1176 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1177 return DAG.getTargetConstant(Val, MVT::i32);
1183 // Check to see if this buildvec has a single non-undef value in its elements.
1184 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1185 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1186 if (!OpVal.getNode())
1187 OpVal = N->getOperand(i);
1188 else if (OpVal != N->getOperand(i))
1192 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1194 unsigned ValSizeInBytes = EltSize;
1196 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1197 Value = CN->getZExtValue();
1198 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1199 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1200 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1203 // If the splat value is larger than the element value, then we can never do
1204 // this splat. The only case that we could fit the replicated bits into our
1205 // immediate field for would be zero, and we prefer to use vxor for it.
1206 if (ValSizeInBytes < ByteSize) return SDValue();
1208 // If the element value is larger than the splat value, cut it in half and
1209 // check to see if the two halves are equal. Continue doing this until we
1210 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1211 while (ValSizeInBytes > ByteSize) {
1212 ValSizeInBytes >>= 1;
1214 // If the top half equals the bottom half, we're still ok.
1215 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1216 (Value & ((1 << (8*ValSizeInBytes))-1)))
1220 // Properly sign extend the value.
1221 int MaskVal = SignExtend32(Value, ByteSize * 8);
1223 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1224 if (MaskVal == 0) return SDValue();
1226 // Finally, if this value fits in a 5 bit sext field, return it
1227 if (SignExtend32<5>(MaskVal) == MaskVal)
1228 return DAG.getTargetConstant(MaskVal, MVT::i32);
1232 //===----------------------------------------------------------------------===//
1233 // Addressing Mode Selection
1234 //===----------------------------------------------------------------------===//
1236 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1237 /// or 64-bit immediate, and if the value can be accurately represented as a
1238 /// sign extension from a 16-bit value. If so, this returns true and the
1240 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1241 if (!isa<ConstantSDNode>(N))
1244 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1245 if (N->getValueType(0) == MVT::i32)
1246 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1248 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1250 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1251 return isIntS16Immediate(Op.getNode(), Imm);
1255 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1256 /// can be represented as an indexed [r+r] operation. Returns false if it
1257 /// can be more efficiently represented with [r+imm].
1258 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1260 SelectionDAG &DAG) const {
1262 if (N.getOpcode() == ISD::ADD) {
1263 if (isIntS16Immediate(N.getOperand(1), imm))
1264 return false; // r+i
1265 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1266 return false; // r+i
1268 Base = N.getOperand(0);
1269 Index = N.getOperand(1);
1271 } else if (N.getOpcode() == ISD::OR) {
1272 if (isIntS16Immediate(N.getOperand(1), imm))
1273 return false; // r+i can fold it if we can.
1275 // If this is an or of disjoint bitfields, we can codegen this as an add
1276 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1278 APInt LHSKnownZero, LHSKnownOne;
1279 APInt RHSKnownZero, RHSKnownOne;
1280 DAG.computeKnownBits(N.getOperand(0),
1281 LHSKnownZero, LHSKnownOne);
1283 if (LHSKnownZero.getBoolValue()) {
1284 DAG.computeKnownBits(N.getOperand(1),
1285 RHSKnownZero, RHSKnownOne);
1286 // If all of the bits are known zero on the LHS or RHS, the add won't
1288 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1289 Base = N.getOperand(0);
1290 Index = N.getOperand(1);
1299 // If we happen to be doing an i64 load or store into a stack slot that has
1300 // less than a 4-byte alignment, then the frame-index elimination may need to
1301 // use an indexed load or store instruction (because the offset may not be a
1302 // multiple of 4). The extra register needed to hold the offset comes from the
1303 // register scavenger, and it is possible that the scavenger will need to use
1304 // an emergency spill slot. As a result, we need to make sure that a spill slot
1305 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1307 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1308 // FIXME: This does not handle the LWA case.
1312 // NOTE: We'll exclude negative FIs here, which come from argument
1313 // lowering, because there are no known test cases triggering this problem
1314 // using packed structures (or similar). We can remove this exclusion if
1315 // we find such a test case. The reason why this is so test-case driven is
1316 // because this entire 'fixup' is only to prevent crashes (from the
1317 // register scavenger) on not-really-valid inputs. For example, if we have:
1319 // %b = bitcast i1* %a to i64*
1320 // store i64* a, i64 b
1321 // then the store should really be marked as 'align 1', but is not. If it
1322 // were marked as 'align 1' then the indexed form would have been
1323 // instruction-selected initially, and the problem this 'fixup' is preventing
1324 // won't happen regardless.
1328 MachineFunction &MF = DAG.getMachineFunction();
1329 MachineFrameInfo *MFI = MF.getFrameInfo();
1331 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1335 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1336 FuncInfo->setHasNonRISpills();
1339 /// Returns true if the address N can be represented by a base register plus
1340 /// a signed 16-bit displacement [r+imm], and if it is not better
1341 /// represented as reg+reg. If Aligned is true, only accept displacements
1342 /// suitable for STD and friends, i.e. multiples of 4.
1343 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1346 bool Aligned) const {
1347 // FIXME dl should come from parent load or store, not from address
1349 // If this can be more profitably realized as r+r, fail.
1350 if (SelectAddressRegReg(N, Disp, Base, DAG))
1353 if (N.getOpcode() == ISD::ADD) {
1355 if (isIntS16Immediate(N.getOperand(1), imm) &&
1356 (!Aligned || (imm & 3) == 0)) {
1357 Disp = DAG.getTargetConstant(imm, N.getValueType());
1358 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1359 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1360 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1362 Base = N.getOperand(0);
1364 return true; // [r+i]
1365 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1366 // Match LOAD (ADD (X, Lo(G))).
1367 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1368 && "Cannot handle constant offsets yet!");
1369 Disp = N.getOperand(1).getOperand(0); // The global address.
1370 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1371 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1372 Disp.getOpcode() == ISD::TargetConstantPool ||
1373 Disp.getOpcode() == ISD::TargetJumpTable);
1374 Base = N.getOperand(0);
1375 return true; // [&g+r]
1377 } else if (N.getOpcode() == ISD::OR) {
1379 if (isIntS16Immediate(N.getOperand(1), imm) &&
1380 (!Aligned || (imm & 3) == 0)) {
1381 // If this is an or of disjoint bitfields, we can codegen this as an add
1382 // (for better address arithmetic) if the LHS and RHS of the OR are
1383 // provably disjoint.
1384 APInt LHSKnownZero, LHSKnownOne;
1385 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1387 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1388 // If all of the bits are known zero on the LHS or RHS, the add won't
1390 if (FrameIndexSDNode *FI =
1391 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1392 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1393 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1395 Base = N.getOperand(0);
1397 Disp = DAG.getTargetConstant(imm, N.getValueType());
1401 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1402 // Loading from a constant address.
1404 // If this address fits entirely in a 16-bit sext immediate field, codegen
1407 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1408 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1409 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1410 CN->getValueType(0));
1414 // Handle 32-bit sext immediates with LIS + addr mode.
1415 if ((CN->getValueType(0) == MVT::i32 ||
1416 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1417 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1418 int Addr = (int)CN->getZExtValue();
1420 // Otherwise, break this down into an LIS + disp.
1421 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1423 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1424 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1425 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1430 Disp = DAG.getTargetConstant(0, getPointerTy());
1431 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1432 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1433 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1436 return true; // [r+0]
1439 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1440 /// represented as an indexed [r+r] operation.
1441 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1443 SelectionDAG &DAG) const {
1444 // Check to see if we can easily represent this as an [r+r] address. This
1445 // will fail if it thinks that the address is more profitably represented as
1446 // reg+imm, e.g. where imm = 0.
1447 if (SelectAddressRegReg(N, Base, Index, DAG))
1450 // If the operand is an addition, always emit this as [r+r], since this is
1451 // better (for code size, and execution, as the memop does the add for free)
1452 // than emitting an explicit add.
1453 if (N.getOpcode() == ISD::ADD) {
1454 Base = N.getOperand(0);
1455 Index = N.getOperand(1);
1459 // Otherwise, do it the hard way, using R0 as the base register.
1460 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1466 /// getPreIndexedAddressParts - returns true by value, base pointer and
1467 /// offset pointer and addressing mode by reference if the node's address
1468 /// can be legally represented as pre-indexed load / store address.
1469 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1471 ISD::MemIndexedMode &AM,
1472 SelectionDAG &DAG) const {
1473 if (DisablePPCPreinc) return false;
1479 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1480 Ptr = LD->getBasePtr();
1481 VT = LD->getMemoryVT();
1482 Alignment = LD->getAlignment();
1483 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1484 Ptr = ST->getBasePtr();
1485 VT = ST->getMemoryVT();
1486 Alignment = ST->getAlignment();
1491 // PowerPC doesn't have preinc load/store instructions for vectors.
1495 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1497 // Common code will reject creating a pre-inc form if the base pointer
1498 // is a frame index, or if N is a store and the base pointer is either
1499 // the same as or a predecessor of the value being stored. Check for
1500 // those situations here, and try with swapped Base/Offset instead.
1503 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1506 SDValue Val = cast<StoreSDNode>(N)->getValue();
1507 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1512 std::swap(Base, Offset);
1518 // LDU/STU can only handle immediates that are a multiple of 4.
1519 if (VT != MVT::i64) {
1520 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1523 // LDU/STU need an address with at least 4-byte alignment.
1527 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1531 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1532 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1533 // sext i32 to i64 when addr mode is r+i.
1534 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1535 LD->getExtensionType() == ISD::SEXTLOAD &&
1536 isa<ConstantSDNode>(Offset))
1544 //===----------------------------------------------------------------------===//
1545 // LowerOperation implementation
1546 //===----------------------------------------------------------------------===//
1548 /// GetLabelAccessInfo - Return true if we should reference labels using a
1549 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1550 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1551 unsigned &LoOpFlags,
1552 const GlobalValue *GV = nullptr) {
1553 HiOpFlags = PPCII::MO_HA;
1554 LoOpFlags = PPCII::MO_LO;
1556 // Don't use the pic base if not in PIC relocation model.
1557 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1560 HiOpFlags |= PPCII::MO_PIC_FLAG;
1561 LoOpFlags |= PPCII::MO_PIC_FLAG;
1564 // If this is a reference to a global value that requires a non-lazy-ptr, make
1565 // sure that instruction lowering adds it.
1566 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1567 HiOpFlags |= PPCII::MO_NLP_FLAG;
1568 LoOpFlags |= PPCII::MO_NLP_FLAG;
1570 if (GV->hasHiddenVisibility()) {
1571 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1572 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1579 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1580 SelectionDAG &DAG) {
1581 EVT PtrVT = HiPart.getValueType();
1582 SDValue Zero = DAG.getConstant(0, PtrVT);
1585 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1586 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1588 // With PIC, the first instruction is actually "GR+hi(&G)".
1590 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1591 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1593 // Generate non-pic code that has direct accesses to the constant pool.
1594 // The address of the global is just (hi(&g)+lo(&g)).
1595 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1598 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1599 SelectionDAG &DAG) const {
1600 EVT PtrVT = Op.getValueType();
1601 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1602 const Constant *C = CP->getConstVal();
1604 // 64-bit SVR4 ABI code is always position-independent.
1605 // The actual address of the GlobalValue is stored in the TOC.
1606 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1607 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1608 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1609 DAG.getRegister(PPC::X2, MVT::i64));
1612 unsigned MOHiFlag, MOLoFlag;
1613 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1615 if (isPIC && Subtarget.isSVR4ABI()) {
1616 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1617 PPCII::MO_PIC_FLAG);
1619 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1620 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1624 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1626 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1627 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1630 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1631 EVT PtrVT = Op.getValueType();
1632 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1634 // 64-bit SVR4 ABI code is always position-independent.
1635 // The actual address of the GlobalValue is stored in the TOC.
1636 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1637 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1638 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1639 DAG.getRegister(PPC::X2, MVT::i64));
1642 unsigned MOHiFlag, MOLoFlag;
1643 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1645 if (isPIC && Subtarget.isSVR4ABI()) {
1646 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1647 PPCII::MO_PIC_FLAG);
1649 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1650 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1653 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1654 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1655 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1658 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1659 SelectionDAG &DAG) const {
1660 EVT PtrVT = Op.getValueType();
1661 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1662 const BlockAddress *BA = BASDN->getBlockAddress();
1664 // 64-bit SVR4 ABI code is always position-independent.
1665 // The actual BlockAddress is stored in the TOC.
1666 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1667 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1668 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1669 DAG.getRegister(PPC::X2, MVT::i64));
1672 unsigned MOHiFlag, MOLoFlag;
1673 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1674 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1675 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1676 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1679 // Generate a call to __tls_get_addr for the given GOT entry Op.
1680 std::pair<SDValue,SDValue>
1681 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1682 SelectionDAG &DAG) const {
1684 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1685 TargetLowering::ArgListTy Args;
1686 TargetLowering::ArgListEntry Entry;
1688 Entry.Ty = IntPtrTy;
1689 Args.push_back(Entry);
1691 TargetLowering::CallLoweringInfo CLI(DAG);
1692 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1693 .setCallee(CallingConv::C, IntPtrTy,
1694 DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1695 std::move(Args), 0);
1697 return LowerCallTo(CLI);
1700 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1701 SelectionDAG &DAG) const {
1703 // FIXME: TLS addresses currently use medium model code sequences,
1704 // which is the most useful form. Eventually support for small and
1705 // large models could be added if users need it, at the cost of
1706 // additional complexity.
1707 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1709 const GlobalValue *GV = GA->getGlobal();
1710 EVT PtrVT = getPointerTy();
1711 bool is64bit = Subtarget.isPPC64();
1712 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1713 PICLevel::Level picLevel = M->getPICLevel();
1715 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1717 if (Model == TLSModel::LocalExec) {
1718 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1719 PPCII::MO_TPREL_HA);
1720 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1721 PPCII::MO_TPREL_LO);
1722 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1723 is64bit ? MVT::i64 : MVT::i32);
1724 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1725 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1728 if (Model == TLSModel::InitialExec) {
1729 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1730 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1734 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1735 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1736 PtrVT, GOTReg, TGA);
1738 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1739 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1740 PtrVT, TGA, GOTPtr);
1741 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1744 if (Model == TLSModel::GeneralDynamic) {
1745 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1749 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1750 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1753 if (picLevel == PICLevel::Small)
1754 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1756 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1758 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1760 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1761 return CallResult.first;
1764 if (Model == TLSModel::LocalDynamic) {
1765 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1769 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1770 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1773 if (picLevel == PICLevel::Small)
1774 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1776 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1778 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1780 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1781 SDValue TLSAddr = CallResult.first;
1782 SDValue Chain = CallResult.second;
1783 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1784 Chain, TLSAddr, TGA);
1785 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1788 llvm_unreachable("Unknown TLS model!");
1791 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1792 SelectionDAG &DAG) const {
1793 EVT PtrVT = Op.getValueType();
1794 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1796 const GlobalValue *GV = GSDN->getGlobal();
1798 // 64-bit SVR4 ABI code is always position-independent.
1799 // The actual address of the GlobalValue is stored in the TOC.
1800 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1801 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1802 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1803 DAG.getRegister(PPC::X2, MVT::i64));
1806 unsigned MOHiFlag, MOLoFlag;
1807 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1809 if (isPIC && Subtarget.isSVR4ABI()) {
1810 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1812 PPCII::MO_PIC_FLAG);
1813 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1814 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1818 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1820 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1822 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1824 // If the global reference is actually to a non-lazy-pointer, we have to do an
1825 // extra load to get the address of the global.
1826 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1827 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1828 false, false, false, 0);
1832 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1833 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1836 if (Op.getValueType() == MVT::v2i64) {
1837 // When the operands themselves are v2i64 values, we need to do something
1838 // special because VSX has no underlying comparison operations for these.
1839 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1840 // Equality can be handled by casting to the legal type for Altivec
1841 // comparisons, everything else needs to be expanded.
1842 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1843 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1844 DAG.getSetCC(dl, MVT::v4i32,
1845 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1846 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1853 // We handle most of these in the usual way.
1857 // If we're comparing for equality to zero, expose the fact that this is
1858 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1859 // fold the new nodes.
1860 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1861 if (C->isNullValue() && CC == ISD::SETEQ) {
1862 EVT VT = Op.getOperand(0).getValueType();
1863 SDValue Zext = Op.getOperand(0);
1864 if (VT.bitsLT(MVT::i32)) {
1866 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1868 unsigned Log2b = Log2_32(VT.getSizeInBits());
1869 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1870 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1871 DAG.getConstant(Log2b, MVT::i32));
1872 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1874 // Leave comparisons against 0 and -1 alone for now, since they're usually
1875 // optimized. FIXME: revisit this when we can custom lower all setcc
1877 if (C->isAllOnesValue() || C->isNullValue())
1881 // If we have an integer seteq/setne, turn it into a compare against zero
1882 // by xor'ing the rhs with the lhs, which is faster than setting a
1883 // condition register, reading it back out, and masking the correct bit. The
1884 // normal approach here uses sub to do this instead of xor. Using xor exposes
1885 // the result to other bit-twiddling opportunities.
1886 EVT LHSVT = Op.getOperand(0).getValueType();
1887 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1888 EVT VT = Op.getValueType();
1889 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1891 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1896 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1897 const PPCSubtarget &Subtarget) const {
1898 SDNode *Node = Op.getNode();
1899 EVT VT = Node->getValueType(0);
1900 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1901 SDValue InChain = Node->getOperand(0);
1902 SDValue VAListPtr = Node->getOperand(1);
1903 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1906 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1909 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1910 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1911 false, false, false, 0);
1912 InChain = GprIndex.getValue(1);
1914 if (VT == MVT::i64) {
1915 // Check if GprIndex is even
1916 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1917 DAG.getConstant(1, MVT::i32));
1918 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1919 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1920 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1921 DAG.getConstant(1, MVT::i32));
1922 // Align GprIndex to be even if it isn't
1923 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1927 // fpr index is 1 byte after gpr
1928 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1929 DAG.getConstant(1, MVT::i32));
1932 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1933 FprPtr, MachinePointerInfo(SV), MVT::i8,
1934 false, false, false, 0);
1935 InChain = FprIndex.getValue(1);
1937 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1938 DAG.getConstant(8, MVT::i32));
1940 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1941 DAG.getConstant(4, MVT::i32));
1944 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1945 MachinePointerInfo(), false, false,
1947 InChain = OverflowArea.getValue(1);
1949 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1950 MachinePointerInfo(), false, false,
1952 InChain = RegSaveArea.getValue(1);
1954 // select overflow_area if index > 8
1955 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1956 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1958 // adjustment constant gpr_index * 4/8
1959 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1960 VT.isInteger() ? GprIndex : FprIndex,
1961 DAG.getConstant(VT.isInteger() ? 4 : 8,
1964 // OurReg = RegSaveArea + RegConstant
1965 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1968 // Floating types are 32 bytes into RegSaveArea
1969 if (VT.isFloatingPoint())
1970 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1971 DAG.getConstant(32, MVT::i32));
1973 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1974 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1975 VT.isInteger() ? GprIndex : FprIndex,
1976 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1979 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1980 VT.isInteger() ? VAListPtr : FprPtr,
1981 MachinePointerInfo(SV),
1982 MVT::i8, false, false, 0);
1984 // determine if we should load from reg_save_area or overflow_area
1985 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1987 // increase overflow_area by 4/8 if gpr/fpr > 8
1988 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1989 DAG.getConstant(VT.isInteger() ? 4 : 8,
1992 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1995 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1997 MachinePointerInfo(),
1998 MVT::i32, false, false, 0);
2000 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2001 false, false, false, 0);
2004 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2005 const PPCSubtarget &Subtarget) const {
2006 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2008 // We have to copy the entire va_list struct:
2009 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2010 return DAG.getMemcpy(Op.getOperand(0), Op,
2011 Op.getOperand(1), Op.getOperand(2),
2012 DAG.getConstant(12, MVT::i32), 8, false, true,
2013 MachinePointerInfo(), MachinePointerInfo());
2016 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2017 SelectionDAG &DAG) const {
2018 return Op.getOperand(0);
2021 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2022 SelectionDAG &DAG) const {
2023 SDValue Chain = Op.getOperand(0);
2024 SDValue Trmp = Op.getOperand(1); // trampoline
2025 SDValue FPtr = Op.getOperand(2); // nested function
2026 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2029 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2030 bool isPPC64 = (PtrVT == MVT::i64);
2032 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2035 TargetLowering::ArgListTy Args;
2036 TargetLowering::ArgListEntry Entry;
2038 Entry.Ty = IntPtrTy;
2039 Entry.Node = Trmp; Args.push_back(Entry);
2041 // TrampSize == (isPPC64 ? 48 : 40);
2042 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2043 isPPC64 ? MVT::i64 : MVT::i32);
2044 Args.push_back(Entry);
2046 Entry.Node = FPtr; Args.push_back(Entry);
2047 Entry.Node = Nest; Args.push_back(Entry);
2049 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2050 TargetLowering::CallLoweringInfo CLI(DAG);
2051 CLI.setDebugLoc(dl).setChain(Chain)
2052 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2053 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2054 std::move(Args), 0);
2056 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2057 return CallResult.second;
2060 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2061 const PPCSubtarget &Subtarget) const {
2062 MachineFunction &MF = DAG.getMachineFunction();
2063 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2067 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2068 // vastart just stores the address of the VarArgsFrameIndex slot into the
2069 // memory location argument.
2070 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2071 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2072 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2073 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2074 MachinePointerInfo(SV),
2078 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2079 // We suppose the given va_list is already allocated.
2082 // char gpr; /* index into the array of 8 GPRs
2083 // * stored in the register save area
2084 // * gpr=0 corresponds to r3,
2085 // * gpr=1 to r4, etc.
2087 // char fpr; /* index into the array of 8 FPRs
2088 // * stored in the register save area
2089 // * fpr=0 corresponds to f1,
2090 // * fpr=1 to f2, etc.
2092 // char *overflow_arg_area;
2093 // /* location on stack that holds
2094 // * the next overflow argument
2096 // char *reg_save_area;
2097 // /* where r3:r10 and f1:f8 (if saved)
2103 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2104 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2107 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2109 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2111 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2114 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2115 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2117 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2118 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2120 uint64_t FPROffset = 1;
2121 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2123 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2125 // Store first byte : number of int regs
2126 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2128 MachinePointerInfo(SV),
2129 MVT::i8, false, false, 0);
2130 uint64_t nextOffset = FPROffset;
2131 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2134 // Store second byte : number of float regs
2135 SDValue secondStore =
2136 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2137 MachinePointerInfo(SV, nextOffset), MVT::i8,
2139 nextOffset += StackOffset;
2140 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2142 // Store second word : arguments given on stack
2143 SDValue thirdStore =
2144 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2145 MachinePointerInfo(SV, nextOffset),
2147 nextOffset += FrameOffset;
2148 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2150 // Store third word : arguments given in registers
2151 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2152 MachinePointerInfo(SV, nextOffset),
2157 #include "PPCGenCallingConv.inc"
2159 // Function whose sole purpose is to kill compiler warnings
2160 // stemming from unused functions included from PPCGenCallingConv.inc.
2161 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2162 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2165 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2166 CCValAssign::LocInfo &LocInfo,
2167 ISD::ArgFlagsTy &ArgFlags,
2172 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2174 CCValAssign::LocInfo &LocInfo,
2175 ISD::ArgFlagsTy &ArgFlags,
2177 static const MCPhysReg ArgRegs[] = {
2178 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2179 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2181 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2183 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2185 // Skip one register if the first unallocated register has an even register
2186 // number and there are still argument registers available which have not been
2187 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2188 // need to skip a register if RegNum is odd.
2189 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2190 State.AllocateReg(ArgRegs[RegNum]);
2193 // Always return false here, as this function only makes sure that the first
2194 // unallocated register has an odd register number and does not actually
2195 // allocate a register for the current argument.
2199 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2201 CCValAssign::LocInfo &LocInfo,
2202 ISD::ArgFlagsTy &ArgFlags,
2204 static const MCPhysReg ArgRegs[] = {
2205 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2209 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2211 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2213 // If there is only one Floating-point register left we need to put both f64
2214 // values of a split ppc_fp128 value on the stack.
2215 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2216 State.AllocateReg(ArgRegs[RegNum]);
2219 // Always return false here, as this function only makes sure that the two f64
2220 // values a ppc_fp128 value is split into are both passed in registers or both
2221 // passed on the stack and does not actually allocate a register for the
2222 // current argument.
2226 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2228 static const MCPhysReg *GetFPR() {
2229 static const MCPhysReg FPR[] = {
2230 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2231 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2237 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2239 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2240 unsigned PtrByteSize) {
2241 unsigned ArgSize = ArgVT.getStoreSize();
2242 if (Flags.isByVal())
2243 ArgSize = Flags.getByValSize();
2245 // Round up to multiples of the pointer size, except for array members,
2246 // which are always packed.
2247 if (!Flags.isInConsecutiveRegs())
2248 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2253 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2255 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2256 ISD::ArgFlagsTy Flags,
2257 unsigned PtrByteSize) {
2258 unsigned Align = PtrByteSize;
2260 // Altivec parameters are padded to a 16 byte boundary.
2261 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2262 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2263 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2266 // ByVal parameters are aligned as requested.
2267 if (Flags.isByVal()) {
2268 unsigned BVAlign = Flags.getByValAlign();
2269 if (BVAlign > PtrByteSize) {
2270 if (BVAlign % PtrByteSize != 0)
2272 "ByVal alignment is not a multiple of the pointer size");
2278 // Array members are always packed to their original alignment.
2279 if (Flags.isInConsecutiveRegs()) {
2280 // If the array member was split into multiple registers, the first
2281 // needs to be aligned to the size of the full type. (Except for
2282 // ppcf128, which is only aligned as its f64 components.)
2283 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2284 Align = OrigVT.getStoreSize();
2286 Align = ArgVT.getStoreSize();
2292 /// CalculateStackSlotUsed - Return whether this argument will use its
2293 /// stack slot (instead of being passed in registers). ArgOffset,
2294 /// AvailableFPRs, and AvailableVRs must hold the current argument
2295 /// position, and will be updated to account for this argument.
2296 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2297 ISD::ArgFlagsTy Flags,
2298 unsigned PtrByteSize,
2299 unsigned LinkageSize,
2300 unsigned ParamAreaSize,
2301 unsigned &ArgOffset,
2302 unsigned &AvailableFPRs,
2303 unsigned &AvailableVRs) {
2304 bool UseMemory = false;
2306 // Respect alignment of argument on the stack.
2308 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2309 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2310 // If there's no space left in the argument save area, we must
2311 // use memory (this check also catches zero-sized arguments).
2312 if (ArgOffset >= LinkageSize + ParamAreaSize)
2315 // Allocate argument on the stack.
2316 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2317 if (Flags.isInConsecutiveRegsLast())
2318 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2319 // If we overran the argument save area, we must use memory
2320 // (this check catches arguments passed partially in memory)
2321 if (ArgOffset > LinkageSize + ParamAreaSize)
2324 // However, if the argument is actually passed in an FPR or a VR,
2325 // we don't use memory after all.
2326 if (!Flags.isByVal()) {
2327 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2328 if (AvailableFPRs > 0) {
2332 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2333 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2334 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2335 if (AvailableVRs > 0) {
2344 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2345 /// ensure minimum alignment required for target.
2346 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2347 unsigned NumBytes) {
2348 unsigned TargetAlign =
2349 Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2350 unsigned AlignMask = TargetAlign - 1;
2351 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2356 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2357 CallingConv::ID CallConv, bool isVarArg,
2358 const SmallVectorImpl<ISD::InputArg>
2360 SDLoc dl, SelectionDAG &DAG,
2361 SmallVectorImpl<SDValue> &InVals)
2363 if (Subtarget.isSVR4ABI()) {
2364 if (Subtarget.isPPC64())
2365 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2368 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2371 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2377 PPCTargetLowering::LowerFormalArguments_32SVR4(
2379 CallingConv::ID CallConv, bool isVarArg,
2380 const SmallVectorImpl<ISD::InputArg>
2382 SDLoc dl, SelectionDAG &DAG,
2383 SmallVectorImpl<SDValue> &InVals) const {
2385 // 32-bit SVR4 ABI Stack Frame Layout:
2386 // +-----------------------------------+
2387 // +--> | Back chain |
2388 // | +-----------------------------------+
2389 // | | Floating-point register save area |
2390 // | +-----------------------------------+
2391 // | | General register save area |
2392 // | +-----------------------------------+
2393 // | | CR save word |
2394 // | +-----------------------------------+
2395 // | | VRSAVE save word |
2396 // | +-----------------------------------+
2397 // | | Alignment padding |
2398 // | +-----------------------------------+
2399 // | | Vector register save area |
2400 // | +-----------------------------------+
2401 // | | Local variable space |
2402 // | +-----------------------------------+
2403 // | | Parameter list area |
2404 // | +-----------------------------------+
2405 // | | LR save word |
2406 // | +-----------------------------------+
2407 // SP--> +--- | Back chain |
2408 // +-----------------------------------+
2411 // System V Application Binary Interface PowerPC Processor Supplement
2412 // AltiVec Technology Programming Interface Manual
2414 MachineFunction &MF = DAG.getMachineFunction();
2415 MachineFrameInfo *MFI = MF.getFrameInfo();
2416 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2418 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2419 // Potential tail calls could cause overwriting of argument stack slots.
2420 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2421 (CallConv == CallingConv::Fast));
2422 unsigned PtrByteSize = 4;
2424 // Assign locations to all of the incoming arguments.
2425 SmallVector<CCValAssign, 16> ArgLocs;
2426 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2429 // Reserve space for the linkage area on the stack.
2430 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2431 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2433 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2435 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2436 CCValAssign &VA = ArgLocs[i];
2438 // Arguments stored in registers.
2439 if (VA.isRegLoc()) {
2440 const TargetRegisterClass *RC;
2441 EVT ValVT = VA.getValVT();
2443 switch (ValVT.getSimpleVT().SimpleTy) {
2445 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2448 RC = &PPC::GPRCRegClass;
2451 RC = &PPC::F4RCRegClass;
2454 if (Subtarget.hasVSX())
2455 RC = &PPC::VSFRCRegClass;
2457 RC = &PPC::F8RCRegClass;
2463 RC = &PPC::VRRCRegClass;
2467 RC = &PPC::VSHRCRegClass;
2471 // Transform the arguments stored in physical registers into virtual ones.
2472 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2473 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2474 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2476 if (ValVT == MVT::i1)
2477 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2479 InVals.push_back(ArgValue);
2481 // Argument stored in memory.
2482 assert(VA.isMemLoc());
2484 unsigned ArgSize = VA.getLocVT().getStoreSize();
2485 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2488 // Create load nodes to retrieve arguments from the stack.
2489 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2490 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2491 MachinePointerInfo(),
2492 false, false, false, 0));
2496 // Assign locations to all of the incoming aggregate by value arguments.
2497 // Aggregates passed by value are stored in the local variable space of the
2498 // caller's stack frame, right above the parameter list area.
2499 SmallVector<CCValAssign, 16> ByValArgLocs;
2500 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2501 ByValArgLocs, *DAG.getContext());
2503 // Reserve stack space for the allocations in CCInfo.
2504 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2506 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2508 // Area that is at least reserved in the caller of this function.
2509 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2510 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2512 // Set the size that is at least reserved in caller of this function. Tail
2513 // call optimized function's reserved stack space needs to be aligned so that
2514 // taking the difference between two stack areas will result in an aligned
2516 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2517 FuncInfo->setMinReservedArea(MinReservedArea);
2519 SmallVector<SDValue, 8> MemOps;
2521 // If the function takes variable number of arguments, make a frame index for
2522 // the start of the first vararg value... for expansion of llvm.va_start.
2524 static const MCPhysReg GPArgRegs[] = {
2525 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2526 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2528 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2530 static const MCPhysReg FPArgRegs[] = {
2531 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2534 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2535 if (DisablePPCFloatInVariadic)
2538 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2540 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2543 // Make room for NumGPArgRegs and NumFPArgRegs.
2544 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2545 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2547 FuncInfo->setVarArgsStackOffset(
2548 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2549 CCInfo.getNextStackOffset(), true));
2551 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2552 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2554 // The fixed integer arguments of a variadic function are stored to the
2555 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2556 // the result of va_next.
2557 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2558 // Get an existing live-in vreg, or add a new one.
2559 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2561 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2563 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2564 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2565 MachinePointerInfo(), false, false, 0);
2566 MemOps.push_back(Store);
2567 // Increment the address by four for the next argument to store
2568 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2569 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2572 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2574 // The double arguments are stored to the VarArgsFrameIndex
2576 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2577 // Get an existing live-in vreg, or add a new one.
2578 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2580 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2582 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2583 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2584 MachinePointerInfo(), false, false, 0);
2585 MemOps.push_back(Store);
2586 // Increment the address by eight for the next argument to store
2587 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2589 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2593 if (!MemOps.empty())
2594 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2599 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2600 // value to MVT::i64 and then truncate to the correct register size.
2602 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2603 SelectionDAG &DAG, SDValue ArgVal,
2606 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2607 DAG.getValueType(ObjectVT));
2608 else if (Flags.isZExt())
2609 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2610 DAG.getValueType(ObjectVT));
2612 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2616 PPCTargetLowering::LowerFormalArguments_64SVR4(
2618 CallingConv::ID CallConv, bool isVarArg,
2619 const SmallVectorImpl<ISD::InputArg>
2621 SDLoc dl, SelectionDAG &DAG,
2622 SmallVectorImpl<SDValue> &InVals) const {
2623 // TODO: add description of PPC stack frame format, or at least some docs.
2625 bool isELFv2ABI = Subtarget.isELFv2ABI();
2626 bool isLittleEndian = Subtarget.isLittleEndian();
2627 MachineFunction &MF = DAG.getMachineFunction();
2628 MachineFrameInfo *MFI = MF.getFrameInfo();
2629 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2631 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2632 // Potential tail calls could cause overwriting of argument stack slots.
2633 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2634 (CallConv == CallingConv::Fast));
2635 unsigned PtrByteSize = 8;
2637 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2640 static const MCPhysReg GPR[] = {
2641 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2642 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2645 static const MCPhysReg *FPR = GetFPR();
2647 static const MCPhysReg VR[] = {
2648 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2649 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2651 static const MCPhysReg VSRH[] = {
2652 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2653 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2656 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2657 const unsigned Num_FPR_Regs = 13;
2658 const unsigned Num_VR_Regs = array_lengthof(VR);
2660 // Do a first pass over the arguments to determine whether the ABI
2661 // guarantees that our caller has allocated the parameter save area
2662 // on its stack frame. In the ELFv1 ABI, this is always the case;
2663 // in the ELFv2 ABI, it is true if this is a vararg function or if
2664 // any parameter is located in a stack slot.
2666 bool HasParameterArea = !isELFv2ABI || isVarArg;
2667 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2668 unsigned NumBytes = LinkageSize;
2669 unsigned AvailableFPRs = Num_FPR_Regs;
2670 unsigned AvailableVRs = Num_VR_Regs;
2671 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2672 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2673 PtrByteSize, LinkageSize, ParamAreaSize,
2674 NumBytes, AvailableFPRs, AvailableVRs))
2675 HasParameterArea = true;
2677 // Add DAG nodes to load the arguments or copy them out of registers. On
2678 // entry to a function on PPC, the arguments start after the linkage area,
2679 // although the first ones are often in registers.
2681 unsigned ArgOffset = LinkageSize;
2682 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2683 SmallVector<SDValue, 8> MemOps;
2684 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2685 unsigned CurArgIdx = 0;
2686 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2688 bool needsLoad = false;
2689 EVT ObjectVT = Ins[ArgNo].VT;
2690 EVT OrigVT = Ins[ArgNo].ArgVT;
2691 unsigned ObjSize = ObjectVT.getStoreSize();
2692 unsigned ArgSize = ObjSize;
2693 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2694 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2695 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2697 /* Respect alignment of argument on the stack. */
2699 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2700 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2701 unsigned CurArgOffset = ArgOffset;
2703 /* Compute GPR index associated with argument offset. */
2704 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2705 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2707 // FIXME the codegen can be much improved in some cases.
2708 // We do not have to keep everything in memory.
2709 if (Flags.isByVal()) {
2710 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2711 ObjSize = Flags.getByValSize();
2712 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2713 // Empty aggregate parameters do not take up registers. Examples:
2717 // etc. However, we have to provide a place-holder in InVals, so
2718 // pretend we have an 8-byte item at the current address for that
2721 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2722 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2723 InVals.push_back(FIN);
2727 // Create a stack object covering all stack doublewords occupied
2728 // by the argument. If the argument is (fully or partially) on
2729 // the stack, or if the argument is fully in registers but the
2730 // caller has allocated the parameter save anyway, we can refer
2731 // directly to the caller's stack frame. Otherwise, create a
2732 // local copy in our own frame.
2734 if (HasParameterArea ||
2735 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2736 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2738 FI = MFI->CreateStackObject(ArgSize, Align, false);
2739 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2741 // Handle aggregates smaller than 8 bytes.
2742 if (ObjSize < PtrByteSize) {
2743 // The value of the object is its address, which differs from the
2744 // address of the enclosing doubleword on big-endian systems.
2746 if (!isLittleEndian) {
2747 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2748 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2750 InVals.push_back(Arg);
2752 if (GPR_idx != Num_GPR_Regs) {
2753 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2754 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2757 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2758 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2759 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2760 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2761 MachinePointerInfo(FuncArg),
2762 ObjType, false, false, 0);
2764 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2765 // store the whole register as-is to the parameter save area
2767 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2768 MachinePointerInfo(FuncArg),
2772 MemOps.push_back(Store);
2774 // Whether we copied from a register or not, advance the offset
2775 // into the parameter save area by a full doubleword.
2776 ArgOffset += PtrByteSize;
2780 // The value of the object is its address, which is the address of
2781 // its first stack doubleword.
2782 InVals.push_back(FIN);
2784 // Store whatever pieces of the object are in registers to memory.
2785 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2786 if (GPR_idx == Num_GPR_Regs)
2789 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2790 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2793 SDValue Off = DAG.getConstant(j, PtrVT);
2794 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2796 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2797 MachinePointerInfo(FuncArg, j),
2799 MemOps.push_back(Store);
2802 ArgOffset += ArgSize;
2806 switch (ObjectVT.getSimpleVT().SimpleTy) {
2807 default: llvm_unreachable("Unhandled argument type!");
2811 // These can be scalar arguments or elements of an integer array type
2812 // passed directly. Clang may use those instead of "byval" aggregate
2813 // types to avoid forcing arguments to memory unnecessarily.
2814 if (GPR_idx != Num_GPR_Regs) {
2815 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2816 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2818 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2819 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2820 // value to MVT::i64 and then truncate to the correct register size.
2821 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2824 ArgSize = PtrByteSize;
2831 // These can be scalar arguments or elements of a float array type
2832 // passed directly. The latter are used to implement ELFv2 homogenous
2833 // float aggregates.
2834 if (FPR_idx != Num_FPR_Regs) {
2837 if (ObjectVT == MVT::f32)
2838 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2840 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2841 &PPC::VSFRCRegClass :
2842 &PPC::F8RCRegClass);
2844 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2846 } else if (GPR_idx != Num_GPR_Regs) {
2847 // This can only ever happen in the presence of f32 array types,
2848 // since otherwise we never run out of FPRs before running out
2850 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2851 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2853 if (ObjectVT == MVT::f32) {
2854 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2855 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2856 DAG.getConstant(32, MVT::i32));
2857 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2860 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2865 // When passing an array of floats, the array occupies consecutive
2866 // space in the argument area; only round up to the next doubleword
2867 // at the end of the array. Otherwise, each float takes 8 bytes.
2868 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2869 ArgOffset += ArgSize;
2870 if (Flags.isInConsecutiveRegsLast())
2871 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2879 // These can be scalar arguments or elements of a vector array type
2880 // passed directly. The latter are used to implement ELFv2 homogenous
2881 // vector aggregates.
2882 if (VR_idx != Num_VR_Regs) {
2883 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2884 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2885 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2886 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2895 // We need to load the argument to a virtual register if we determined
2896 // above that we ran out of physical registers of the appropriate type.
2898 if (ObjSize < ArgSize && !isLittleEndian)
2899 CurArgOffset += ArgSize - ObjSize;
2900 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2901 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2902 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2903 false, false, false, 0);
2906 InVals.push_back(ArgVal);
2909 // Area that is at least reserved in the caller of this function.
2910 unsigned MinReservedArea;
2911 if (HasParameterArea)
2912 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2914 MinReservedArea = LinkageSize;
2916 // Set the size that is at least reserved in caller of this function. Tail
2917 // call optimized functions' reserved stack space needs to be aligned so that
2918 // taking the difference between two stack areas will result in an aligned
2920 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2921 FuncInfo->setMinReservedArea(MinReservedArea);
2923 // If the function takes variable number of arguments, make a frame index for
2924 // the start of the first vararg value... for expansion of llvm.va_start.
2926 int Depth = ArgOffset;
2928 FuncInfo->setVarArgsFrameIndex(
2929 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2930 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2932 // If this function is vararg, store any remaining integer argument regs
2933 // to their spots on the stack so that they may be loaded by deferencing the
2934 // result of va_next.
2935 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2936 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2937 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2938 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2939 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2940 MachinePointerInfo(), false, false, 0);
2941 MemOps.push_back(Store);
2942 // Increment the address by four for the next argument to store
2943 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2944 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2948 if (!MemOps.empty())
2949 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2955 PPCTargetLowering::LowerFormalArguments_Darwin(
2957 CallingConv::ID CallConv, bool isVarArg,
2958 const SmallVectorImpl<ISD::InputArg>
2960 SDLoc dl, SelectionDAG &DAG,
2961 SmallVectorImpl<SDValue> &InVals) const {
2962 // TODO: add description of PPC stack frame format, or at least some docs.
2964 MachineFunction &MF = DAG.getMachineFunction();
2965 MachineFrameInfo *MFI = MF.getFrameInfo();
2966 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2968 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2969 bool isPPC64 = PtrVT == MVT::i64;
2970 // Potential tail calls could cause overwriting of argument stack slots.
2971 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2972 (CallConv == CallingConv::Fast));
2973 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2975 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2977 unsigned ArgOffset = LinkageSize;
2978 // Area that is at least reserved in caller of this function.
2979 unsigned MinReservedArea = ArgOffset;
2981 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2982 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2983 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2985 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2986 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2987 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2990 static const MCPhysReg *FPR = GetFPR();
2992 static const MCPhysReg VR[] = {
2993 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2994 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2997 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2998 const unsigned Num_FPR_Regs = 13;
2999 const unsigned Num_VR_Regs = array_lengthof( VR);
3001 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3003 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3005 // In 32-bit non-varargs functions, the stack space for vectors is after the
3006 // stack space for non-vectors. We do not use this space unless we have
3007 // too many vectors to fit in registers, something that only occurs in
3008 // constructed examples:), but we have to walk the arglist to figure
3009 // that out...for the pathological case, compute VecArgOffset as the
3010 // start of the vector parameter area. Computing VecArgOffset is the
3011 // entire point of the following loop.
3012 unsigned VecArgOffset = ArgOffset;
3013 if (!isVarArg && !isPPC64) {
3014 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3016 EVT ObjectVT = Ins[ArgNo].VT;
3017 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3019 if (Flags.isByVal()) {
3020 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3021 unsigned ObjSize = Flags.getByValSize();
3023 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3024 VecArgOffset += ArgSize;
3028 switch(ObjectVT.getSimpleVT().SimpleTy) {
3029 default: llvm_unreachable("Unhandled argument type!");
3035 case MVT::i64: // PPC64
3037 // FIXME: We are guaranteed to be !isPPC64 at this point.
3038 // Does MVT::i64 apply?
3045 // Nothing to do, we're only looking at Nonvector args here.
3050 // We've found where the vector parameter area in memory is. Skip the
3051 // first 12 parameters; these don't use that memory.
3052 VecArgOffset = ((VecArgOffset+15)/16)*16;
3053 VecArgOffset += 12*16;
3055 // Add DAG nodes to load the arguments or copy them out of registers. On
3056 // entry to a function on PPC, the arguments start after the linkage area,
3057 // although the first ones are often in registers.
3059 SmallVector<SDValue, 8> MemOps;
3060 unsigned nAltivecParamsAtEnd = 0;
3061 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3062 unsigned CurArgIdx = 0;
3063 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3065 bool needsLoad = false;
3066 EVT ObjectVT = Ins[ArgNo].VT;
3067 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3068 unsigned ArgSize = ObjSize;
3069 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3070 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3071 CurArgIdx = Ins[ArgNo].OrigArgIndex;
3073 unsigned CurArgOffset = ArgOffset;
3075 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3076 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3077 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3078 if (isVarArg || isPPC64) {
3079 MinReservedArea = ((MinReservedArea+15)/16)*16;
3080 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3083 } else nAltivecParamsAtEnd++;
3085 // Calculate min reserved area.
3086 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3090 // FIXME the codegen can be much improved in some cases.
3091 // We do not have to keep everything in memory.
3092 if (Flags.isByVal()) {
3093 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3094 ObjSize = Flags.getByValSize();
3095 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3096 // Objects of size 1 and 2 are right justified, everything else is
3097 // left justified. This means the memory address is adjusted forwards.
3098 if (ObjSize==1 || ObjSize==2) {
3099 CurArgOffset = CurArgOffset + (4 - ObjSize);
3101 // The value of the object is its address.
3102 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3103 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3104 InVals.push_back(FIN);
3105 if (ObjSize==1 || ObjSize==2) {
3106 if (GPR_idx != Num_GPR_Regs) {
3109 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3111 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3112 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3113 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3114 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3115 MachinePointerInfo(FuncArg),
3116 ObjType, false, false, 0);
3117 MemOps.push_back(Store);
3121 ArgOffset += PtrByteSize;
3125 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3126 // Store whatever pieces of the object are in registers
3127 // to memory. ArgOffset will be the address of the beginning
3129 if (GPR_idx != Num_GPR_Regs) {
3132 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3134 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3135 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3136 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3137 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3138 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3139 MachinePointerInfo(FuncArg, j),
3141 MemOps.push_back(Store);
3143 ArgOffset += PtrByteSize;
3145 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3152 switch (ObjectVT.getSimpleVT().SimpleTy) {
3153 default: llvm_unreachable("Unhandled argument type!");
3157 if (GPR_idx != Num_GPR_Regs) {
3158 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3159 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3161 if (ObjectVT == MVT::i1)
3162 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3167 ArgSize = PtrByteSize;
3169 // All int arguments reserve stack space in the Darwin ABI.
3170 ArgOffset += PtrByteSize;
3174 case MVT::i64: // PPC64
3175 if (GPR_idx != Num_GPR_Regs) {
3176 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3177 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3179 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3180 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3181 // value to MVT::i64 and then truncate to the correct register size.
3182 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3187 ArgSize = PtrByteSize;
3189 // All int arguments reserve stack space in the Darwin ABI.
3195 // Every 4 bytes of argument space consumes one of the GPRs available for
3196 // argument passing.
3197 if (GPR_idx != Num_GPR_Regs) {
3199 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3202 if (FPR_idx != Num_FPR_Regs) {
3205 if (ObjectVT == MVT::f32)
3206 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3208 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3210 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3216 // All FP arguments reserve stack space in the Darwin ABI.
3217 ArgOffset += isPPC64 ? 8 : ObjSize;
3223 // Note that vector arguments in registers don't reserve stack space,
3224 // except in varargs functions.
3225 if (VR_idx != Num_VR_Regs) {
3226 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3227 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3229 while ((ArgOffset % 16) != 0) {
3230 ArgOffset += PtrByteSize;
3231 if (GPR_idx != Num_GPR_Regs)
3235 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3239 if (!isVarArg && !isPPC64) {
3240 // Vectors go after all the nonvectors.
3241 CurArgOffset = VecArgOffset;
3244 // Vectors are aligned.
3245 ArgOffset = ((ArgOffset+15)/16)*16;
3246 CurArgOffset = ArgOffset;
3254 // We need to load the argument to a virtual register if we determined above
3255 // that we ran out of physical registers of the appropriate type.
3257 int FI = MFI->CreateFixedObject(ObjSize,
3258 CurArgOffset + (ArgSize - ObjSize),
3260 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3261 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3262 false, false, false, 0);
3265 InVals.push_back(ArgVal);
3268 // Allow for Altivec parameters at the end, if needed.
3269 if (nAltivecParamsAtEnd) {
3270 MinReservedArea = ((MinReservedArea+15)/16)*16;
3271 MinReservedArea += 16*nAltivecParamsAtEnd;
3274 // Area that is at least reserved in the caller of this function.
3275 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3277 // Set the size that is at least reserved in caller of this function. Tail
3278 // call optimized functions' reserved stack space needs to be aligned so that
3279 // taking the difference between two stack areas will result in an aligned
3281 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3282 FuncInfo->setMinReservedArea(MinReservedArea);
3284 // If the function takes variable number of arguments, make a frame index for
3285 // the start of the first vararg value... for expansion of llvm.va_start.
3287 int Depth = ArgOffset;
3289 FuncInfo->setVarArgsFrameIndex(
3290 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3292 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3294 // If this function is vararg, store any remaining integer argument regs
3295 // to their spots on the stack so that they may be loaded by deferencing the
3296 // result of va_next.
3297 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3301 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3303 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3305 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3306 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3307 MachinePointerInfo(), false, false, 0);
3308 MemOps.push_back(Store);
3309 // Increment the address by four for the next argument to store
3310 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3311 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3315 if (!MemOps.empty())
3316 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3321 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3322 /// adjusted to accommodate the arguments for the tailcall.
3323 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3324 unsigned ParamSize) {
3326 if (!isTailCall) return 0;
3328 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3329 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3330 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3331 // Remember only if the new adjustement is bigger.
3332 if (SPDiff < FI->getTailCallSPDelta())
3333 FI->setTailCallSPDelta(SPDiff);
3338 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3339 /// for tail call optimization. Targets which want to do tail call
3340 /// optimization should implement this function.
3342 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3343 CallingConv::ID CalleeCC,
3345 const SmallVectorImpl<ISD::InputArg> &Ins,
3346 SelectionDAG& DAG) const {
3347 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3350 // Variable argument functions are not supported.
3354 MachineFunction &MF = DAG.getMachineFunction();
3355 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3356 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3357 // Functions containing by val parameters are not supported.
3358 for (unsigned i = 0; i != Ins.size(); i++) {
3359 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3360 if (Flags.isByVal()) return false;
3363 // Non-PIC/GOT tail calls are supported.
3364 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3367 // At the moment we can only do local tail calls (in same module, hidden
3368 // or protected) if we are generating PIC.
3369 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3370 return G->getGlobal()->hasHiddenVisibility()
3371 || G->getGlobal()->hasProtectedVisibility();
3377 /// isCallCompatibleAddress - Return the immediate to use if the specified
3378 /// 32-bit value is representable in the immediate field of a BxA instruction.
3379 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3380 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3381 if (!C) return nullptr;
3383 int Addr = C->getZExtValue();
3384 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3385 SignExtend32<26>(Addr) != Addr)
3386 return nullptr; // Top 6 bits have to be sext of immediate.
3388 return DAG.getConstant((int)C->getZExtValue() >> 2,
3389 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3394 struct TailCallArgumentInfo {
3399 TailCallArgumentInfo() : FrameIdx(0) {}
3404 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3406 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3408 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3409 SmallVectorImpl<SDValue> &MemOpChains,
3411 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3412 SDValue Arg = TailCallArgs[i].Arg;
3413 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3414 int FI = TailCallArgs[i].FrameIdx;
3415 // Store relative to framepointer.
3416 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3417 MachinePointerInfo::getFixedStack(FI),
3422 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3423 /// the appropriate stack slot for the tail call optimized function call.
3424 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3425 MachineFunction &MF,
3434 // Calculate the new stack slot for the return address.
3435 int SlotSize = isPPC64 ? 8 : 4;
3436 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3438 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3439 NewRetAddrLoc, true);
3440 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3441 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3442 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3443 MachinePointerInfo::getFixedStack(NewRetAddr),
3446 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3447 // slot as the FP is never overwritten.
3450 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3451 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3453 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3454 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3455 MachinePointerInfo::getFixedStack(NewFPIdx),
3462 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3463 /// the position of the argument.
3465 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3466 SDValue Arg, int SPDiff, unsigned ArgOffset,
3467 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3468 int Offset = ArgOffset + SPDiff;
3469 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3470 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3471 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3472 SDValue FIN = DAG.getFrameIndex(FI, VT);
3473 TailCallArgumentInfo Info;
3475 Info.FrameIdxOp = FIN;
3477 TailCallArguments.push_back(Info);
3480 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3481 /// stack slot. Returns the chain as result and the loaded frame pointers in
3482 /// LROpOut/FPOpout. Used when tail calling.
3483 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3491 // Load the LR and FP stack slot for later adjusting.
3492 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3493 LROpOut = getReturnAddrFrameIndex(DAG);
3494 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3495 false, false, false, 0);
3496 Chain = SDValue(LROpOut.getNode(), 1);
3498 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3499 // slot as the FP is never overwritten.
3501 FPOpOut = getFramePointerFrameIndex(DAG);
3502 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3503 false, false, false, 0);
3504 Chain = SDValue(FPOpOut.getNode(), 1);
3510 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3511 /// by "Src" to address "Dst" of size "Size". Alignment information is
3512 /// specified by the specific parameter attribute. The copy will be passed as
3513 /// a byval function parameter.
3514 /// Sometimes what we are copying is the end of a larger object, the part that
3515 /// does not fit in registers.
3517 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3518 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3520 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3521 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3522 false, false, MachinePointerInfo(),
3523 MachinePointerInfo());
3526 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3529 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3530 SDValue Arg, SDValue PtrOff, int SPDiff,
3531 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3532 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3533 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3535 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3540 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3542 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3543 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3544 DAG.getConstant(ArgOffset, PtrVT));
3546 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3547 MachinePointerInfo(), false, false, 0));
3548 // Calculate and remember argument location.
3549 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3554 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3555 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3556 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3557 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3558 MachineFunction &MF = DAG.getMachineFunction();
3560 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3561 // might overwrite each other in case of tail call optimization.
3562 SmallVector<SDValue, 8> MemOpChains2;
3563 // Do not flag preceding copytoreg stuff together with the following stuff.
3565 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3567 if (!MemOpChains2.empty())
3568 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3570 // Store the return address to the appropriate stack slot.
3571 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3572 isPPC64, isDarwinABI, dl);
3574 // Emit callseq_end just before tailcall node.
3575 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3576 DAG.getIntPtrConstant(0, true), InFlag, dl);
3577 InFlag = Chain.getValue(1);
3581 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3582 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3583 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3584 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3585 const PPCSubtarget &Subtarget) {
3587 bool isPPC64 = Subtarget.isPPC64();
3588 bool isSVR4ABI = Subtarget.isSVR4ABI();
3589 bool isELFv2ABI = Subtarget.isELFv2ABI();
3591 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3592 NodeTys.push_back(MVT::Other); // Returns a chain
3593 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3595 unsigned CallOpc = PPCISD::CALL;
3597 bool needIndirectCall = true;
3598 if (!isSVR4ABI || !isPPC64)
3599 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3600 // If this is an absolute destination address, use the munged value.
3601 Callee = SDValue(Dest, 0);
3602 needIndirectCall = false;
3605 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3606 unsigned OpFlags = 0;
3607 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3608 (Subtarget.getTargetTriple().isMacOSX() &&
3609 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3610 (G->getGlobal()->isDeclaration() ||
3611 G->getGlobal()->isWeakForLinker())) ||
3612 (Subtarget.isTargetELF() && !isPPC64 &&
3613 !G->getGlobal()->hasLocalLinkage() &&
3614 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3615 // PC-relative references to external symbols should go through $stub,
3616 // unless we're building with the leopard linker or later, which
3617 // automatically synthesizes these stubs.
3618 OpFlags = PPCII::MO_PLT_OR_STUB;
3621 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3622 // every direct call is) turn it into a TargetGlobalAddress /
3623 // TargetExternalSymbol node so that legalize doesn't hack it.
3624 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3625 Callee.getValueType(), 0, OpFlags);
3626 needIndirectCall = false;
3629 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3630 unsigned char OpFlags = 0;
3632 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3633 (Subtarget.getTargetTriple().isMacOSX() &&
3634 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3635 (Subtarget.isTargetELF() && !isPPC64 &&
3636 DAG.getTarget().getRelocationModel() == Reloc::PIC_) ) {
3637 // PC-relative references to external symbols should go through $stub,
3638 // unless we're building with the leopard linker or later, which
3639 // automatically synthesizes these stubs.
3640 OpFlags = PPCII::MO_PLT_OR_STUB;
3643 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3645 needIndirectCall = false;
3648 if (needIndirectCall) {
3649 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3650 // to do the call, we can't use PPCISD::CALL.
3651 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3653 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3654 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3655 // entry point, but to the function descriptor (the function entry point
3656 // address is part of the function descriptor though).
3657 // The function descriptor is a three doubleword structure with the
3658 // following fields: function entry point, TOC base address and
3659 // environment pointer.
3660 // Thus for a call through a function pointer, the following actions need
3662 // 1. Save the TOC of the caller in the TOC save area of its stack
3663 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3664 // 2. Load the address of the function entry point from the function
3666 // 3. Load the TOC of the callee from the function descriptor into r2.
3667 // 4. Load the environment pointer from the function descriptor into
3669 // 5. Branch to the function entry point address.
3670 // 6. On return of the callee, the TOC of the caller needs to be
3671 // restored (this is done in FinishCall()).
3673 // All those operations are flagged together to ensure that no other
3674 // operations can be scheduled in between. E.g. without flagging the
3675 // operations together, a TOC access in the caller could be scheduled
3676 // between the load of the callee TOC and the branch to the callee, which
3677 // results in the TOC access going through the TOC of the callee instead
3678 // of going through the TOC of the caller, which leads to incorrect code.
3680 // Load the address of the function entry point from the function
3682 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3683 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3684 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3685 Chain = LoadFuncPtr.getValue(1);
3686 InFlag = LoadFuncPtr.getValue(2);
3688 // Load environment pointer into r11.
3689 // Offset of the environment pointer within the function descriptor.
3690 SDValue PtrOff = DAG.getIntPtrConstant(16);
3692 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3693 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3695 Chain = LoadEnvPtr.getValue(1);
3696 InFlag = LoadEnvPtr.getValue(2);
3698 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3700 Chain = EnvVal.getValue(0);
3701 InFlag = EnvVal.getValue(1);
3703 // Load TOC of the callee into r2. We are using a target-specific load
3704 // with r2 hard coded, because the result of a target-independent load
3705 // would never go directly into r2, since r2 is a reserved register (which
3706 // prevents the register allocator from allocating it), resulting in an
3707 // additional register being allocated and an unnecessary move instruction
3709 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3710 SDValue TOCOff = DAG.getIntPtrConstant(8);
3711 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3712 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3714 Chain = LoadTOCPtr.getValue(0);
3715 InFlag = LoadTOCPtr.getValue(1);
3717 MTCTROps[0] = Chain;
3718 MTCTROps[1] = LoadFuncPtr;
3719 MTCTROps[2] = InFlag;
3722 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3723 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3724 InFlag = Chain.getValue(1);
3727 NodeTys.push_back(MVT::Other);
3728 NodeTys.push_back(MVT::Glue);
3729 Ops.push_back(Chain);
3730 CallOpc = PPCISD::BCTRL;
3731 Callee.setNode(nullptr);
3732 // Add use of X11 (holding environment pointer)
3733 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3734 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3735 // Add CTR register as callee so a bctr can be emitted later.
3737 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3740 // If this is a direct call, pass the chain and the callee.
3741 if (Callee.getNode()) {
3742 Ops.push_back(Chain);
3743 Ops.push_back(Callee);
3745 // If this is a call to __tls_get_addr, find the symbol whose address
3746 // is to be taken and add it to the list. This will be used to
3747 // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld).
3748 // We find the symbol by walking the chain to the CopyFromReg, walking
3749 // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and
3750 // pulling the symbol from that node.
3751 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
3752 if (!strcmp(S->getSymbol(), "__tls_get_addr")) {
3753 assert(!needIndirectCall && "Indirect call to __tls_get_addr???");
3754 SDNode *AddI = Chain.getNode()->getOperand(2).getNode();
3755 SDValue TGTAddr = AddI->getOperand(1);
3756 assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress &&
3757 "Didn't find target global TLS address where we expected one");
3758 Ops.push_back(TGTAddr);
3759 CallOpc = PPCISD::CALL_TLS;
3762 // If this is a tail call add stack pointer delta.
3764 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3766 // Add argument registers to the end of the list so that they are known live
3768 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3769 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3770 RegsToPass[i].second.getValueType()));
3772 // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3773 if (Callee.getNode() && isELFv2ABI)
3774 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3780 bool isLocalCall(const SDValue &Callee)
3782 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3783 return !G->getGlobal()->isDeclaration() &&
3784 !G->getGlobal()->isWeakForLinker();
3789 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3790 CallingConv::ID CallConv, bool isVarArg,
3791 const SmallVectorImpl<ISD::InputArg> &Ins,
3792 SDLoc dl, SelectionDAG &DAG,
3793 SmallVectorImpl<SDValue> &InVals) const {
3795 SmallVector<CCValAssign, 16> RVLocs;
3796 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3798 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3800 // Copy all of the result registers out of their specified physreg.
3801 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3802 CCValAssign &VA = RVLocs[i];
3803 assert(VA.isRegLoc() && "Can only return in registers!");
3805 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3806 VA.getLocReg(), VA.getLocVT(), InFlag);
3807 Chain = Val.getValue(1);
3808 InFlag = Val.getValue(2);
3810 switch (VA.getLocInfo()) {
3811 default: llvm_unreachable("Unknown loc info!");
3812 case CCValAssign::Full: break;
3813 case CCValAssign::AExt:
3814 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3816 case CCValAssign::ZExt:
3817 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3818 DAG.getValueType(VA.getValVT()));
3819 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3821 case CCValAssign::SExt:
3822 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3823 DAG.getValueType(VA.getValVT()));
3824 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3828 InVals.push_back(Val);
3835 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3836 bool isTailCall, bool isVarArg,
3838 SmallVector<std::pair<unsigned, SDValue>, 8>
3840 SDValue InFlag, SDValue Chain,
3842 int SPDiff, unsigned NumBytes,
3843 const SmallVectorImpl<ISD::InputArg> &Ins,
3844 SmallVectorImpl<SDValue> &InVals) const {
3846 bool isELFv2ABI = Subtarget.isELFv2ABI();
3847 std::vector<EVT> NodeTys;
3848 SmallVector<SDValue, 8> Ops;
3849 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3850 isTailCall, RegsToPass, Ops, NodeTys,
3853 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3854 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3855 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3857 // When performing tail call optimization the callee pops its arguments off
3858 // the stack. Account for this here so these bytes can be pushed back on in
3859 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3860 int BytesCalleePops =
3861 (CallConv == CallingConv::Fast &&
3862 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3864 // Add a register mask operand representing the call-preserved registers.
3865 const TargetRegisterInfo *TRI =
3866 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3867 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3868 assert(Mask && "Missing call preserved mask for calling convention");
3869 Ops.push_back(DAG.getRegisterMask(Mask));
3871 if (InFlag.getNode())
3872 Ops.push_back(InFlag);
3876 assert(((Callee.getOpcode() == ISD::Register &&
3877 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3878 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3879 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3880 isa<ConstantSDNode>(Callee)) &&
3881 "Expecting an global address, external symbol, absolute value or register");
3883 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3886 // Add a NOP immediately after the branch instruction when using the 64-bit
3887 // SVR4 ABI. At link time, if caller and callee are in a different module and
3888 // thus have a different TOC, the call will be replaced with a call to a stub
3889 // function which saves the current TOC, loads the TOC of the callee and
3890 // branches to the callee. The NOP will be replaced with a load instruction
3891 // which restores the TOC of the caller from the TOC save slot of the current
3892 // stack frame. If caller and callee belong to the same module (and have the
3893 // same TOC), the NOP will remain unchanged.
3895 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3896 if (CallOpc == PPCISD::BCTRL) {
3897 // This is a call through a function pointer.
3898 // Restore the caller TOC from the save area into R2.
3899 // See PrepareCall() for more information about calls through function
3900 // pointers in the 64-bit SVR4 ABI.
3901 // We are using a target-specific load with r2 hard coded, because the
3902 // result of a target-independent load would never go directly into r2,
3903 // since r2 is a reserved register (which prevents the register allocator
3904 // from allocating it), resulting in an additional register being
3905 // allocated and an unnecessary move instruction being generated.
3906 CallOpc = PPCISD::BCTRL_LOAD_TOC;
3908 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3909 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3910 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3911 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3912 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3914 // The address needs to go after the chain input but before the flag (or
3915 // any other variadic arguments).
3916 Ops.insert(std::next(Ops.begin()), AddTOC);
3917 } else if ((CallOpc == PPCISD::CALL) &&
3918 (!isLocalCall(Callee) ||
3919 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3920 // Otherwise insert NOP for non-local calls.
3921 CallOpc = PPCISD::CALL_NOP;
3922 } else if (CallOpc == PPCISD::CALL_TLS)
3923 // For 64-bit SVR4, TLS calls are always non-local.
3924 CallOpc = PPCISD::CALL_NOP_TLS;
3927 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3928 InFlag = Chain.getValue(1);
3930 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3931 DAG.getIntPtrConstant(BytesCalleePops, true),
3934 InFlag = Chain.getValue(1);
3936 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3937 Ins, dl, DAG, InVals);
3941 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3942 SmallVectorImpl<SDValue> &InVals) const {
3943 SelectionDAG &DAG = CLI.DAG;
3945 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3946 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3947 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3948 SDValue Chain = CLI.Chain;
3949 SDValue Callee = CLI.Callee;
3950 bool &isTailCall = CLI.IsTailCall;
3951 CallingConv::ID CallConv = CLI.CallConv;
3952 bool isVarArg = CLI.IsVarArg;
3955 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3958 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3959 report_fatal_error("failed to perform tail call elimination on a call "
3960 "site marked musttail");
3962 if (Subtarget.isSVR4ABI()) {
3963 if (Subtarget.isPPC64())
3964 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3965 isTailCall, Outs, OutVals, Ins,
3968 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3969 isTailCall, Outs, OutVals, Ins,
3973 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3974 isTailCall, Outs, OutVals, Ins,
3979 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3980 CallingConv::ID CallConv, bool isVarArg,
3982 const SmallVectorImpl<ISD::OutputArg> &Outs,
3983 const SmallVectorImpl<SDValue> &OutVals,
3984 const SmallVectorImpl<ISD::InputArg> &Ins,
3985 SDLoc dl, SelectionDAG &DAG,
3986 SmallVectorImpl<SDValue> &InVals) const {
3987 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3988 // of the 32-bit SVR4 ABI stack frame layout.
3990 assert((CallConv == CallingConv::C ||
3991 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3993 unsigned PtrByteSize = 4;
3995 MachineFunction &MF = DAG.getMachineFunction();
3997 // Mark this function as potentially containing a function that contains a
3998 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3999 // and restoring the callers stack pointer in this functions epilog. This is
4000 // done because by tail calling the called function might overwrite the value
4001 // in this function's (MF) stack pointer stack slot 0(SP).
4002 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4003 CallConv == CallingConv::Fast)
4004 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4006 // Count how many bytes are to be pushed on the stack, including the linkage
4007 // area, parameter list area and the part of the local variable space which
4008 // contains copies of aggregates which are passed by value.
4010 // Assign locations to all of the outgoing arguments.
4011 SmallVector<CCValAssign, 16> ArgLocs;
4012 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4015 // Reserve space for the linkage area on the stack.
4016 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4020 // Handle fixed and variable vector arguments differently.
4021 // Fixed vector arguments go into registers as long as registers are
4022 // available. Variable vector arguments always go into memory.
4023 unsigned NumArgs = Outs.size();
4025 for (unsigned i = 0; i != NumArgs; ++i) {
4026 MVT ArgVT = Outs[i].VT;
4027 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4030 if (Outs[i].IsFixed) {
4031 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4034 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4040 errs() << "Call operand #" << i << " has unhandled type "
4041 << EVT(ArgVT).getEVTString() << "\n";
4043 llvm_unreachable(nullptr);
4047 // All arguments are treated the same.
4048 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4051 // Assign locations to all of the outgoing aggregate by value arguments.
4052 SmallVector<CCValAssign, 16> ByValArgLocs;
4053 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4054 ByValArgLocs, *DAG.getContext());
4056 // Reserve stack space for the allocations in CCInfo.
4057 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4059 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4061 // Size of the linkage area, parameter list area and the part of the local
4062 // space variable where copies of aggregates which are passed by value are
4064 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4066 // Calculate by how many bytes the stack has to be adjusted in case of tail
4067 // call optimization.
4068 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4070 // Adjust the stack pointer for the new arguments...
4071 // These operations are automatically eliminated by the prolog/epilog pass
4072 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4074 SDValue CallSeqStart = Chain;
4076 // Load the return address and frame pointer so it can be moved somewhere else
4079 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4082 // Set up a copy of the stack pointer for use loading and storing any
4083 // arguments that may not fit in the registers available for argument
4085 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4087 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4088 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4089 SmallVector<SDValue, 8> MemOpChains;
4091 bool seenFloatArg = false;
4092 // Walk the register/memloc assignments, inserting copies/loads.
4093 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4096 CCValAssign &VA = ArgLocs[i];
4097 SDValue Arg = OutVals[i];
4098 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4100 if (Flags.isByVal()) {
4101 // Argument is an aggregate which is passed by value, thus we need to
4102 // create a copy of it in the local variable space of the current stack
4103 // frame (which is the stack frame of the caller) and pass the address of
4104 // this copy to the callee.
4105 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4106 CCValAssign &ByValVA = ByValArgLocs[j++];
4107 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4109 // Memory reserved in the local variable space of the callers stack frame.
4110 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4112 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4113 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4115 // Create a copy of the argument in the local area of the current
4117 SDValue MemcpyCall =
4118 CreateCopyOfByValArgument(Arg, PtrOff,
4119 CallSeqStart.getNode()->getOperand(0),
4122 // This must go outside the CALLSEQ_START..END.
4123 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4124 CallSeqStart.getNode()->getOperand(1),
4126 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4127 NewCallSeqStart.getNode());
4128 Chain = CallSeqStart = NewCallSeqStart;
4130 // Pass the address of the aggregate copy on the stack either in a
4131 // physical register or in the parameter list area of the current stack
4132 // frame to the callee.
4136 if (VA.isRegLoc()) {
4137 if (Arg.getValueType() == MVT::i1)
4138 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4140 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4141 // Put argument in a physical register.
4142 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4144 // Put argument in the parameter list area of the current stack frame.
4145 assert(VA.isMemLoc());
4146 unsigned LocMemOffset = VA.getLocMemOffset();
4149 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4150 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4152 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4153 MachinePointerInfo(),
4156 // Calculate and remember argument location.
4157 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4163 if (!MemOpChains.empty())
4164 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4166 // Build a sequence of copy-to-reg nodes chained together with token chain
4167 // and flag operands which copy the outgoing args into the appropriate regs.
4169 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4170 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4171 RegsToPass[i].second, InFlag);
4172 InFlag = Chain.getValue(1);
4175 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4178 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4179 SDValue Ops[] = { Chain, InFlag };
4181 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4182 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4184 InFlag = Chain.getValue(1);
4188 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4189 false, TailCallArguments);
4191 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4192 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4196 // Copy an argument into memory, being careful to do this outside the
4197 // call sequence for the call to which the argument belongs.
4199 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4200 SDValue CallSeqStart,
4201 ISD::ArgFlagsTy Flags,
4204 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4205 CallSeqStart.getNode()->getOperand(0),
4207 // The MEMCPY must go outside the CALLSEQ_START..END.
4208 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4209 CallSeqStart.getNode()->getOperand(1),
4211 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4212 NewCallSeqStart.getNode());
4213 return NewCallSeqStart;
4217 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4218 CallingConv::ID CallConv, bool isVarArg,
4220 const SmallVectorImpl<ISD::OutputArg> &Outs,
4221 const SmallVectorImpl<SDValue> &OutVals,
4222 const SmallVectorImpl<ISD::InputArg> &Ins,
4223 SDLoc dl, SelectionDAG &DAG,
4224 SmallVectorImpl<SDValue> &InVals) const {
4226 bool isELFv2ABI = Subtarget.isELFv2ABI();
4227 bool isLittleEndian = Subtarget.isLittleEndian();
4228 unsigned NumOps = Outs.size();
4230 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4231 unsigned PtrByteSize = 8;
4233 MachineFunction &MF = DAG.getMachineFunction();
4235 // Mark this function as potentially containing a function that contains a
4236 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4237 // and restoring the callers stack pointer in this functions epilog. This is
4238 // done because by tail calling the called function might overwrite the value
4239 // in this function's (MF) stack pointer stack slot 0(SP).
4240 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4241 CallConv == CallingConv::Fast)
4242 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4244 // Count how many bytes are to be pushed on the stack, including the linkage
4245 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4246 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4247 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4248 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4250 unsigned NumBytes = LinkageSize;
4252 // Add up all the space actually used.
4253 for (unsigned i = 0; i != NumOps; ++i) {
4254 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4255 EVT ArgVT = Outs[i].VT;
4256 EVT OrigVT = Outs[i].ArgVT;
4258 /* Respect alignment of argument on the stack. */
4260 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4261 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4263 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4264 if (Flags.isInConsecutiveRegsLast())
4265 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4268 unsigned NumBytesActuallyUsed = NumBytes;
4270 // The prolog code of the callee may store up to 8 GPR argument registers to
4271 // the stack, allowing va_start to index over them in memory if its varargs.
4272 // Because we cannot tell if this is needed on the caller side, we have to
4273 // conservatively assume that it is needed. As such, make sure we have at
4274 // least enough stack space for the caller to store the 8 GPRs.
4275 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4276 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4278 // Tail call needs the stack to be aligned.
4279 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4280 CallConv == CallingConv::Fast)
4281 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4283 // Calculate by how many bytes the stack has to be adjusted in case of tail
4284 // call optimization.
4285 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4287 // To protect arguments on the stack from being clobbered in a tail call,
4288 // force all the loads to happen before doing any other lowering.
4290 Chain = DAG.getStackArgumentTokenFactor(Chain);
4292 // Adjust the stack pointer for the new arguments...
4293 // These operations are automatically eliminated by the prolog/epilog pass
4294 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4296 SDValue CallSeqStart = Chain;
4298 // Load the return address and frame pointer so it can be move somewhere else
4301 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4304 // Set up a copy of the stack pointer for use loading and storing any
4305 // arguments that may not fit in the registers available for argument
4307 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4309 // Figure out which arguments are going to go in registers, and which in
4310 // memory. Also, if this is a vararg function, floating point operations
4311 // must be stored to our stack, and loaded into integer regs as well, if
4312 // any integer regs are available for argument passing.
4313 unsigned ArgOffset = LinkageSize;
4314 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4316 static const MCPhysReg GPR[] = {
4317 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4318 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4320 static const MCPhysReg *FPR = GetFPR();
4322 static const MCPhysReg VR[] = {
4323 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4324 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4326 static const MCPhysReg VSRH[] = {
4327 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4328 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4331 const unsigned NumGPRs = array_lengthof(GPR);
4332 const unsigned NumFPRs = 13;
4333 const unsigned NumVRs = array_lengthof(VR);
4335 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4336 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4338 SmallVector<SDValue, 8> MemOpChains;
4339 for (unsigned i = 0; i != NumOps; ++i) {
4340 SDValue Arg = OutVals[i];
4341 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4342 EVT ArgVT = Outs[i].VT;
4343 EVT OrigVT = Outs[i].ArgVT;
4345 /* Respect alignment of argument on the stack. */
4347 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4348 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4350 /* Compute GPR index associated with argument offset. */
4351 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4352 GPR_idx = std::min(GPR_idx, NumGPRs);
4354 // PtrOff will be used to store the current argument to the stack if a
4355 // register cannot be found for it.
4358 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4360 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4362 // Promote integers to 64-bit values.
4363 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4364 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4365 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4366 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4369 // FIXME memcpy is used way more than necessary. Correctness first.
4370 // Note: "by value" is code for passing a structure by value, not
4372 if (Flags.isByVal()) {
4373 // Note: Size includes alignment padding, so
4374 // struct x { short a; char b; }
4375 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4376 // These are the proper values we need for right-justifying the
4377 // aggregate in a parameter register.
4378 unsigned Size = Flags.getByValSize();
4380 // An empty aggregate parameter takes up no storage and no
4385 // All aggregates smaller than 8 bytes must be passed right-justified.
4386 if (Size==1 || Size==2 || Size==4) {
4387 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4388 if (GPR_idx != NumGPRs) {
4389 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4390 MachinePointerInfo(), VT,
4391 false, false, false, 0);
4392 MemOpChains.push_back(Load.getValue(1));
4393 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4395 ArgOffset += PtrByteSize;
4400 if (GPR_idx == NumGPRs && Size < 8) {
4401 SDValue AddPtr = PtrOff;
4402 if (!isLittleEndian) {
4403 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4404 PtrOff.getValueType());
4405 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4407 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4410 ArgOffset += PtrByteSize;
4413 // Copy entire object into memory. There are cases where gcc-generated
4414 // code assumes it is there, even if it could be put entirely into
4415 // registers. (This is not what the doc says.)
4417 // FIXME: The above statement is likely due to a misunderstanding of the
4418 // documents. All arguments must be copied into the parameter area BY
4419 // THE CALLEE in the event that the callee takes the address of any
4420 // formal argument. That has not yet been implemented. However, it is
4421 // reasonable to use the stack area as a staging area for the register
4424 // Skip this for small aggregates, as we will use the same slot for a
4425 // right-justified copy, below.
4427 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4431 // When a register is available, pass a small aggregate right-justified.
4432 if (Size < 8 && GPR_idx != NumGPRs) {
4433 // The easiest way to get this right-justified in a register
4434 // is to copy the structure into the rightmost portion of a
4435 // local variable slot, then load the whole slot into the
4437 // FIXME: The memcpy seems to produce pretty awful code for
4438 // small aggregates, particularly for packed ones.
4439 // FIXME: It would be preferable to use the slot in the
4440 // parameter save area instead of a new local variable.
4441 SDValue AddPtr = PtrOff;
4442 if (!isLittleEndian) {
4443 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4444 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4446 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4450 // Load the slot into the register.
4451 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4452 MachinePointerInfo(),
4453 false, false, false, 0);
4454 MemOpChains.push_back(Load.getValue(1));
4455 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4457 // Done with this argument.
4458 ArgOffset += PtrByteSize;
4462 // For aggregates larger than PtrByteSize, copy the pieces of the
4463 // object that fit into registers from the parameter save area.
4464 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4465 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4466 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4467 if (GPR_idx != NumGPRs) {
4468 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4469 MachinePointerInfo(),
4470 false, false, false, 0);
4471 MemOpChains.push_back(Load.getValue(1));
4472 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4473 ArgOffset += PtrByteSize;
4475 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4482 switch (Arg.getSimpleValueType().SimpleTy) {
4483 default: llvm_unreachable("Unexpected ValueType for argument!");
4487 // These can be scalar arguments or elements of an integer array type
4488 // passed directly. Clang may use those instead of "byval" aggregate
4489 // types to avoid forcing arguments to memory unnecessarily.
4490 if (GPR_idx != NumGPRs) {
4491 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4493 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4494 true, isTailCall, false, MemOpChains,
4495 TailCallArguments, dl);
4497 ArgOffset += PtrByteSize;
4501 // These can be scalar arguments or elements of a float array type
4502 // passed directly. The latter are used to implement ELFv2 homogenous
4503 // float aggregates.
4505 // Named arguments go into FPRs first, and once they overflow, the
4506 // remaining arguments go into GPRs and then the parameter save area.
4507 // Unnamed arguments for vararg functions always go to GPRs and
4508 // then the parameter save area. For now, put all arguments to vararg
4509 // routines always in both locations (FPR *and* GPR or stack slot).
4510 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4512 // First load the argument into the next available FPR.
4513 if (FPR_idx != NumFPRs)
4514 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4516 // Next, load the argument into GPR or stack slot if needed.
4517 if (!NeedGPROrStack)
4519 else if (GPR_idx != NumGPRs) {
4520 // In the non-vararg case, this can only ever happen in the
4521 // presence of f32 array types, since otherwise we never run
4522 // out of FPRs before running out of GPRs.
4525 // Double values are always passed in a single GPR.
4526 if (Arg.getValueType() != MVT::f32) {
4527 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4529 // Non-array float values are extended and passed in a GPR.
4530 } else if (!Flags.isInConsecutiveRegs()) {
4531 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4532 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4534 // If we have an array of floats, we collect every odd element
4535 // together with its predecessor into one GPR.
4536 } else if (ArgOffset % PtrByteSize != 0) {
4538 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4539 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4540 if (!isLittleEndian)
4542 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4544 // The final element, if even, goes into the first half of a GPR.
4545 } else if (Flags.isInConsecutiveRegsLast()) {
4546 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4547 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4548 if (!isLittleEndian)
4549 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4550 DAG.getConstant(32, MVT::i32));
4552 // Non-final even elements are skipped; they will be handled
4553 // together the with subsequent argument on the next go-around.
4557 if (ArgVal.getNode())
4558 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4560 // Single-precision floating-point values are mapped to the
4561 // second (rightmost) word of the stack doubleword.
4562 if (Arg.getValueType() == MVT::f32 &&
4563 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4564 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4565 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4568 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4569 true, isTailCall, false, MemOpChains,
4570 TailCallArguments, dl);
4572 // When passing an array of floats, the array occupies consecutive
4573 // space in the argument area; only round up to the next doubleword
4574 // at the end of the array. Otherwise, each float takes 8 bytes.
4575 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4576 Flags.isInConsecutiveRegs()) ? 4 : 8;
4577 if (Flags.isInConsecutiveRegsLast())
4578 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4587 // These can be scalar arguments or elements of a vector array type
4588 // passed directly. The latter are used to implement ELFv2 homogenous
4589 // vector aggregates.
4591 // For a varargs call, named arguments go into VRs or on the stack as
4592 // usual; unnamed arguments always go to the stack or the corresponding
4593 // GPRs when within range. For now, we always put the value in both
4594 // locations (or even all three).
4596 // We could elide this store in the case where the object fits
4597 // entirely in R registers. Maybe later.
4598 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4599 MachinePointerInfo(), false, false, 0);
4600 MemOpChains.push_back(Store);
4601 if (VR_idx != NumVRs) {
4602 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4603 MachinePointerInfo(),
4604 false, false, false, 0);
4605 MemOpChains.push_back(Load.getValue(1));
4607 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4608 Arg.getSimpleValueType() == MVT::v2i64) ?
4609 VSRH[VR_idx] : VR[VR_idx];
4612 RegsToPass.push_back(std::make_pair(VReg, Load));
4615 for (unsigned i=0; i<16; i+=PtrByteSize) {
4616 if (GPR_idx == NumGPRs)
4618 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4619 DAG.getConstant(i, PtrVT));
4620 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4621 false, false, false, 0);
4622 MemOpChains.push_back(Load.getValue(1));
4623 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4628 // Non-varargs Altivec params go into VRs or on the stack.
4629 if (VR_idx != NumVRs) {
4630 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4631 Arg.getSimpleValueType() == MVT::v2i64) ?
4632 VSRH[VR_idx] : VR[VR_idx];
4635 RegsToPass.push_back(std::make_pair(VReg, Arg));
4637 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4638 true, isTailCall, true, MemOpChains,
4639 TailCallArguments, dl);
4646 assert(NumBytesActuallyUsed == ArgOffset);
4647 (void)NumBytesActuallyUsed;
4649 if (!MemOpChains.empty())
4650 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4652 // Check if this is an indirect call (MTCTR/BCTRL).
4653 // See PrepareCall() for more information about calls through function
4654 // pointers in the 64-bit SVR4 ABI.
4656 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4657 !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4658 // Load r2 into a virtual register and store it to the TOC save area.
4659 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4660 // TOC save area offset.
4661 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4662 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4663 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4664 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4666 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4667 // This does not mean the MTCTR instruction must use R12; it's easier
4668 // to model this as an extra parameter, so do that.
4670 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4673 // Build a sequence of copy-to-reg nodes chained together with token chain
4674 // and flag operands which copy the outgoing args into the appropriate regs.
4676 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4677 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4678 RegsToPass[i].second, InFlag);
4679 InFlag = Chain.getValue(1);
4683 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4684 FPOp, true, TailCallArguments);
4686 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4687 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4692 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4693 CallingConv::ID CallConv, bool isVarArg,
4695 const SmallVectorImpl<ISD::OutputArg> &Outs,
4696 const SmallVectorImpl<SDValue> &OutVals,
4697 const SmallVectorImpl<ISD::InputArg> &Ins,
4698 SDLoc dl, SelectionDAG &DAG,
4699 SmallVectorImpl<SDValue> &InVals) const {
4701 unsigned NumOps = Outs.size();
4703 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4704 bool isPPC64 = PtrVT == MVT::i64;
4705 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4707 MachineFunction &MF = DAG.getMachineFunction();
4709 // Mark this function as potentially containing a function that contains a
4710 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4711 // and restoring the callers stack pointer in this functions epilog. This is
4712 // done because by tail calling the called function might overwrite the value
4713 // in this function's (MF) stack pointer stack slot 0(SP).
4714 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4715 CallConv == CallingConv::Fast)
4716 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4718 // Count how many bytes are to be pushed on the stack, including the linkage
4719 // area, and parameter passing area. We start with 24/48 bytes, which is
4720 // prereserved space for [SP][CR][LR][3 x unused].
4721 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4723 unsigned NumBytes = LinkageSize;
4725 // Add up all the space actually used.
4726 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4727 // they all go in registers, but we must reserve stack space for them for
4728 // possible use by the caller. In varargs or 64-bit calls, parameters are
4729 // assigned stack space in order, with padding so Altivec parameters are
4731 unsigned nAltivecParamsAtEnd = 0;
4732 for (unsigned i = 0; i != NumOps; ++i) {
4733 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4734 EVT ArgVT = Outs[i].VT;
4735 // Varargs Altivec parameters are padded to a 16 byte boundary.
4736 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4737 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4738 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4739 if (!isVarArg && !isPPC64) {
4740 // Non-varargs Altivec parameters go after all the non-Altivec
4741 // parameters; handle those later so we know how much padding we need.
4742 nAltivecParamsAtEnd++;
4745 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4746 NumBytes = ((NumBytes+15)/16)*16;
4748 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4751 // Allow for Altivec parameters at the end, if needed.
4752 if (nAltivecParamsAtEnd) {
4753 NumBytes = ((NumBytes+15)/16)*16;
4754 NumBytes += 16*nAltivecParamsAtEnd;
4757 // The prolog code of the callee may store up to 8 GPR argument registers to
4758 // the stack, allowing va_start to index over them in memory if its varargs.
4759 // Because we cannot tell if this is needed on the caller side, we have to
4760 // conservatively assume that it is needed. As such, make sure we have at
4761 // least enough stack space for the caller to store the 8 GPRs.
4762 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4764 // Tail call needs the stack to be aligned.
4765 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4766 CallConv == CallingConv::Fast)
4767 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4769 // Calculate by how many bytes the stack has to be adjusted in case of tail
4770 // call optimization.
4771 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4773 // To protect arguments on the stack from being clobbered in a tail call,
4774 // force all the loads to happen before doing any other lowering.
4776 Chain = DAG.getStackArgumentTokenFactor(Chain);
4778 // Adjust the stack pointer for the new arguments...
4779 // These operations are automatically eliminated by the prolog/epilog pass
4780 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4782 SDValue CallSeqStart = Chain;
4784 // Load the return address and frame pointer so it can be move somewhere else
4787 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4790 // Set up a copy of the stack pointer for use loading and storing any
4791 // arguments that may not fit in the registers available for argument
4795 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4797 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4799 // Figure out which arguments are going to go in registers, and which in
4800 // memory. Also, if this is a vararg function, floating point operations
4801 // must be stored to our stack, and loaded into integer regs as well, if
4802 // any integer regs are available for argument passing.
4803 unsigned ArgOffset = LinkageSize;
4804 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4806 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4807 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4808 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4810 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4811 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4812 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4814 static const MCPhysReg *FPR = GetFPR();
4816 static const MCPhysReg VR[] = {
4817 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4818 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4820 const unsigned NumGPRs = array_lengthof(GPR_32);
4821 const unsigned NumFPRs = 13;
4822 const unsigned NumVRs = array_lengthof(VR);
4824 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4826 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4827 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4829 SmallVector<SDValue, 8> MemOpChains;
4830 for (unsigned i = 0; i != NumOps; ++i) {
4831 SDValue Arg = OutVals[i];
4832 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4834 // PtrOff will be used to store the current argument to the stack if a
4835 // register cannot be found for it.
4838 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4840 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4842 // On PPC64, promote integers to 64-bit values.
4843 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4844 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4845 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4846 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4849 // FIXME memcpy is used way more than necessary. Correctness first.
4850 // Note: "by value" is code for passing a structure by value, not
4852 if (Flags.isByVal()) {
4853 unsigned Size = Flags.getByValSize();
4854 // Very small objects are passed right-justified. Everything else is
4855 // passed left-justified.
4856 if (Size==1 || Size==2) {
4857 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4858 if (GPR_idx != NumGPRs) {
4859 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4860 MachinePointerInfo(), VT,
4861 false, false, false, 0);
4862 MemOpChains.push_back(Load.getValue(1));
4863 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4865 ArgOffset += PtrByteSize;
4867 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4868 PtrOff.getValueType());
4869 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4870 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4873 ArgOffset += PtrByteSize;
4877 // Copy entire object into memory. There are cases where gcc-generated
4878 // code assumes it is there, even if it could be put entirely into
4879 // registers. (This is not what the doc says.)
4880 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4884 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4885 // copy the pieces of the object that fit into registers from the
4886 // parameter save area.
4887 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4888 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4889 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4890 if (GPR_idx != NumGPRs) {
4891 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4892 MachinePointerInfo(),
4893 false, false, false, 0);
4894 MemOpChains.push_back(Load.getValue(1));
4895 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4896 ArgOffset += PtrByteSize;
4898 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4905 switch (Arg.getSimpleValueType().SimpleTy) {
4906 default: llvm_unreachable("Unexpected ValueType for argument!");
4910 if (GPR_idx != NumGPRs) {
4911 if (Arg.getValueType() == MVT::i1)
4912 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4914 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4916 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4917 isPPC64, isTailCall, false, MemOpChains,
4918 TailCallArguments, dl);
4920 ArgOffset += PtrByteSize;
4924 if (FPR_idx != NumFPRs) {
4925 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4928 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4929 MachinePointerInfo(), false, false, 0);
4930 MemOpChains.push_back(Store);
4932 // Float varargs are always shadowed in available integer registers
4933 if (GPR_idx != NumGPRs) {
4934 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4935 MachinePointerInfo(), false, false,
4937 MemOpChains.push_back(Load.getValue(1));
4938 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4940 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4941 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4942 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4943 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4944 MachinePointerInfo(),
4945 false, false, false, 0);
4946 MemOpChains.push_back(Load.getValue(1));
4947 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4950 // If we have any FPRs remaining, we may also have GPRs remaining.
4951 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4953 if (GPR_idx != NumGPRs)
4955 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4956 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4960 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4961 isPPC64, isTailCall, false, MemOpChains,
4962 TailCallArguments, dl);
4966 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4973 // These go aligned on the stack, or in the corresponding R registers
4974 // when within range. The Darwin PPC ABI doc claims they also go in
4975 // V registers; in fact gcc does this only for arguments that are
4976 // prototyped, not for those that match the ... We do it for all
4977 // arguments, seems to work.
4978 while (ArgOffset % 16 !=0) {
4979 ArgOffset += PtrByteSize;
4980 if (GPR_idx != NumGPRs)
4983 // We could elide this store in the case where the object fits
4984 // entirely in R registers. Maybe later.
4985 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4986 DAG.getConstant(ArgOffset, PtrVT));
4987 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4988 MachinePointerInfo(), false, false, 0);
4989 MemOpChains.push_back(Store);
4990 if (VR_idx != NumVRs) {
4991 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4992 MachinePointerInfo(),
4993 false, false, false, 0);
4994 MemOpChains.push_back(Load.getValue(1));
4995 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4998 for (unsigned i=0; i<16; i+=PtrByteSize) {
4999 if (GPR_idx == NumGPRs)
5001 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5002 DAG.getConstant(i, PtrVT));
5003 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5004 false, false, false, 0);
5005 MemOpChains.push_back(Load.getValue(1));
5006 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5011 // Non-varargs Altivec params generally go in registers, but have
5012 // stack space allocated at the end.
5013 if (VR_idx != NumVRs) {
5014 // Doesn't have GPR space allocated.
5015 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5016 } else if (nAltivecParamsAtEnd==0) {
5017 // We are emitting Altivec params in order.
5018 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5019 isPPC64, isTailCall, true, MemOpChains,
5020 TailCallArguments, dl);
5026 // If all Altivec parameters fit in registers, as they usually do,
5027 // they get stack space following the non-Altivec parameters. We
5028 // don't track this here because nobody below needs it.
5029 // If there are more Altivec parameters than fit in registers emit
5031 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5033 // Offset is aligned; skip 1st 12 params which go in V registers.
5034 ArgOffset = ((ArgOffset+15)/16)*16;
5036 for (unsigned i = 0; i != NumOps; ++i) {
5037 SDValue Arg = OutVals[i];
5038 EVT ArgType = Outs[i].VT;
5039 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5040 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5043 // We are emitting Altivec params in order.
5044 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5045 isPPC64, isTailCall, true, MemOpChains,
5046 TailCallArguments, dl);
5053 if (!MemOpChains.empty())
5054 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5056 // On Darwin, R12 must contain the address of an indirect callee. This does
5057 // not mean the MTCTR instruction must use R12; it's easier to model this as
5058 // an extra parameter, so do that.
5060 !dyn_cast<GlobalAddressSDNode>(Callee) &&
5061 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
5062 !isBLACompatibleAddress(Callee, DAG))
5063 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5064 PPC::R12), Callee));
5066 // Build a sequence of copy-to-reg nodes chained together with token chain
5067 // and flag operands which copy the outgoing args into the appropriate regs.
5069 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5070 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5071 RegsToPass[i].second, InFlag);
5072 InFlag = Chain.getValue(1);
5076 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5077 FPOp, true, TailCallArguments);
5079 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5080 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5085 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5086 MachineFunction &MF, bool isVarArg,
5087 const SmallVectorImpl<ISD::OutputArg> &Outs,
5088 LLVMContext &Context) const {
5089 SmallVector<CCValAssign, 16> RVLocs;
5090 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5091 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5095 PPCTargetLowering::LowerReturn(SDValue Chain,
5096 CallingConv::ID CallConv, bool isVarArg,
5097 const SmallVectorImpl<ISD::OutputArg> &Outs,
5098 const SmallVectorImpl<SDValue> &OutVals,
5099 SDLoc dl, SelectionDAG &DAG) const {
5101 SmallVector<CCValAssign, 16> RVLocs;
5102 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5104 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5107 SmallVector<SDValue, 4> RetOps(1, Chain);
5109 // Copy the result values into the output registers.
5110 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5111 CCValAssign &VA = RVLocs[i];
5112 assert(VA.isRegLoc() && "Can only return in registers!");
5114 SDValue Arg = OutVals[i];
5116 switch (VA.getLocInfo()) {
5117 default: llvm_unreachable("Unknown loc info!");
5118 case CCValAssign::Full: break;
5119 case CCValAssign::AExt:
5120 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5122 case CCValAssign::ZExt:
5123 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5125 case CCValAssign::SExt:
5126 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5130 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5131 Flag = Chain.getValue(1);
5132 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5135 RetOps[0] = Chain; // Update chain.
5137 // Add the flag if we have it.
5139 RetOps.push_back(Flag);
5141 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5144 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5145 const PPCSubtarget &Subtarget) const {
5146 // When we pop the dynamic allocation we need to restore the SP link.
5149 // Get the corect type for pointers.
5150 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5152 // Construct the stack pointer operand.
5153 bool isPPC64 = Subtarget.isPPC64();
5154 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5155 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5157 // Get the operands for the STACKRESTORE.
5158 SDValue Chain = Op.getOperand(0);
5159 SDValue SaveSP = Op.getOperand(1);
5161 // Load the old link SP.
5162 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5163 MachinePointerInfo(),
5164 false, false, false, 0);
5166 // Restore the stack pointer.
5167 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5169 // Store the old link SP.
5170 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5177 PPCTargetLowering::getReturnAddrFrameIndex(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 RASI = FI->getReturnAddrSaveIndex();
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 LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5192 // Allocate the frame index for frame pointer save area.
5193 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5195 FI->setReturnAddrSaveIndex(RASI);
5197 return DAG.getFrameIndex(RASI, PtrVT);
5201 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5202 MachineFunction &MF = DAG.getMachineFunction();
5203 bool isPPC64 = Subtarget.isPPC64();
5204 bool isDarwinABI = Subtarget.isDarwinABI();
5205 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5207 // Get current frame pointer save index. The users of this index will be
5208 // primarily DYNALLOC instructions.
5209 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5210 int FPSI = FI->getFramePointerSaveIndex();
5212 // If the frame pointer save index hasn't been defined yet.
5214 // Find out what the fix offset of the frame pointer save area.
5215 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5218 // Allocate the frame index for frame pointer save area.
5219 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5221 FI->setFramePointerSaveIndex(FPSI);
5223 return DAG.getFrameIndex(FPSI, PtrVT);
5226 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5228 const PPCSubtarget &Subtarget) const {
5230 SDValue Chain = Op.getOperand(0);
5231 SDValue Size = Op.getOperand(1);
5234 // Get the corect type for pointers.
5235 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5237 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5238 DAG.getConstant(0, PtrVT), Size);
5239 // Construct a node for the frame pointer save index.
5240 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5241 // Build a DYNALLOC node.
5242 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5243 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5244 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5247 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5248 SelectionDAG &DAG) const {
5250 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5251 DAG.getVTList(MVT::i32, MVT::Other),
5252 Op.getOperand(0), Op.getOperand(1));
5255 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5256 SelectionDAG &DAG) const {
5258 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5259 Op.getOperand(0), Op.getOperand(1));
5262 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5263 assert(Op.getValueType() == MVT::i1 &&
5264 "Custom lowering only for i1 loads");
5266 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5269 LoadSDNode *LD = cast<LoadSDNode>(Op);
5271 SDValue Chain = LD->getChain();
5272 SDValue BasePtr = LD->getBasePtr();
5273 MachineMemOperand *MMO = LD->getMemOperand();
5275 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5276 BasePtr, MVT::i8, MMO);
5277 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5279 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5280 return DAG.getMergeValues(Ops, dl);
5283 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5284 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5285 "Custom lowering only for i1 stores");
5287 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5290 StoreSDNode *ST = cast<StoreSDNode>(Op);
5292 SDValue Chain = ST->getChain();
5293 SDValue BasePtr = ST->getBasePtr();
5294 SDValue Value = ST->getValue();
5295 MachineMemOperand *MMO = ST->getMemOperand();
5297 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5298 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5301 // FIXME: Remove this once the ANDI glue bug is fixed:
5302 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5303 assert(Op.getValueType() == MVT::i1 &&
5304 "Custom lowering only for i1 results");
5307 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5311 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5313 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5314 // Not FP? Not a fsel.
5315 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5316 !Op.getOperand(2).getValueType().isFloatingPoint())
5319 // We might be able to do better than this under some circumstances, but in
5320 // general, fsel-based lowering of select is a finite-math-only optimization.
5321 // For more information, see section F.3 of the 2.06 ISA specification.
5322 if (!DAG.getTarget().Options.NoInfsFPMath ||
5323 !DAG.getTarget().Options.NoNaNsFPMath)
5326 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5328 EVT ResVT = Op.getValueType();
5329 EVT CmpVT = Op.getOperand(0).getValueType();
5330 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5331 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5334 // If the RHS of the comparison is a 0.0, we don't need to do the
5335 // subtraction at all.
5337 if (isFloatingPointZero(RHS))
5339 default: break; // SETUO etc aren't handled by fsel.
5343 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5344 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5345 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5346 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5347 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5348 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5349 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5352 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5355 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5356 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5357 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5360 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5363 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5364 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5365 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5366 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5371 default: break; // SETUO etc aren't handled by fsel.
5375 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5376 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5377 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5378 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5379 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5380 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5381 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5382 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5385 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5386 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5387 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5388 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5391 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5392 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5393 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5394 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5397 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5398 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5399 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5400 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5403 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5404 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5405 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5406 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5411 // FIXME: Split this code up when LegalizeDAGTypes lands.
5412 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5414 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5415 SDValue Src = Op.getOperand(0);
5416 if (Src.getValueType() == MVT::f32)
5417 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5420 switch (Op.getSimpleValueType().SimpleTy) {
5421 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5423 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5424 (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5429 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5430 "i64 FP_TO_UINT is supported only with FPCVT");
5431 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5437 // Convert the FP value to an int value through memory.
5438 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5439 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5440 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5441 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5442 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5444 // Emit a store to the stack slot.
5447 MachineFunction &MF = DAG.getMachineFunction();
5448 MachineMemOperand *MMO =
5449 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5450 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5451 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5452 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5454 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5455 MPI, false, false, 0);
5457 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5459 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5460 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5461 DAG.getConstant(4, FIPtr.getValueType()));
5462 MPI = MachinePointerInfo();
5465 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5466 false, false, false, 0);
5469 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5470 SelectionDAG &DAG) const {
5472 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5473 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5476 if (Op.getOperand(0).getValueType() == MVT::i1)
5477 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5478 DAG.getConstantFP(1.0, Op.getValueType()),
5479 DAG.getConstantFP(0.0, Op.getValueType()));
5481 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5482 "UINT_TO_FP is supported only with FPCVT");
5484 // If we have FCFIDS, then use it when converting to single-precision.
5485 // Otherwise, convert to double-precision and then round.
5486 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5487 (Op.getOpcode() == ISD::UINT_TO_FP ?
5488 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5489 (Op.getOpcode() == ISD::UINT_TO_FP ?
5490 PPCISD::FCFIDU : PPCISD::FCFID);
5491 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5492 MVT::f32 : MVT::f64;
5494 if (Op.getOperand(0).getValueType() == MVT::i64) {
5495 SDValue SINT = Op.getOperand(0);
5496 // When converting to single-precision, we actually need to convert
5497 // to double-precision first and then round to single-precision.
5498 // To avoid double-rounding effects during that operation, we have
5499 // to prepare the input operand. Bits that might be truncated when
5500 // converting to double-precision are replaced by a bit that won't
5501 // be lost at this stage, but is below the single-precision rounding
5504 // However, if -enable-unsafe-fp-math is in effect, accept double
5505 // rounding to avoid the extra overhead.
5506 if (Op.getValueType() == MVT::f32 &&
5507 !Subtarget.hasFPCVT() &&
5508 !DAG.getTarget().Options.UnsafeFPMath) {
5510 // Twiddle input to make sure the low 11 bits are zero. (If this
5511 // is the case, we are guaranteed the value will fit into the 53 bit
5512 // mantissa of an IEEE double-precision value without rounding.)
5513 // If any of those low 11 bits were not zero originally, make sure
5514 // bit 12 (value 2048) is set instead, so that the final rounding
5515 // to single-precision gets the correct result.
5516 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5517 SINT, DAG.getConstant(2047, MVT::i64));
5518 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5519 Round, DAG.getConstant(2047, MVT::i64));
5520 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5521 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5522 Round, DAG.getConstant(-2048, MVT::i64));
5524 // However, we cannot use that value unconditionally: if the magnitude
5525 // of the input value is small, the bit-twiddling we did above might
5526 // end up visibly changing the output. Fortunately, in that case, we
5527 // don't need to twiddle bits since the original input will convert
5528 // exactly to double-precision floating-point already. Therefore,
5529 // construct a conditional to use the original value if the top 11
5530 // bits are all sign-bit copies, and use the rounded value computed
5532 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5533 SINT, DAG.getConstant(53, MVT::i32));
5534 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5535 Cond, DAG.getConstant(1, MVT::i64));
5536 Cond = DAG.getSetCC(dl, MVT::i32,
5537 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5539 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5542 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5543 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5545 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5546 FP = DAG.getNode(ISD::FP_ROUND, dl,
5547 MVT::f32, FP, DAG.getIntPtrConstant(0));
5551 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5552 "Unhandled INT_TO_FP type in custom expander!");
5553 // Since we only generate this in 64-bit mode, we can take advantage of
5554 // 64-bit registers. In particular, sign extend the input value into the
5555 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5556 // then lfd it and fcfid it.
5557 MachineFunction &MF = DAG.getMachineFunction();
5558 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5559 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5562 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5563 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5564 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5566 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5567 MachinePointerInfo::getFixedStack(FrameIdx),
5570 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5571 "Expected an i32 store");
5572 MachineMemOperand *MMO =
5573 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5574 MachineMemOperand::MOLoad, 4, 4);
5575 SDValue Ops[] = { Store, FIdx };
5576 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5577 PPCISD::LFIWZX : PPCISD::LFIWAX,
5578 dl, DAG.getVTList(MVT::f64, MVT::Other),
5579 Ops, MVT::i32, MMO);
5581 assert(Subtarget.isPPC64() &&
5582 "i32->FP without LFIWAX supported only on PPC64");
5584 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5585 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5587 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5590 // STD the extended value into the stack slot.
5591 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5592 MachinePointerInfo::getFixedStack(FrameIdx),
5595 // Load the value as a double.
5596 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5597 MachinePointerInfo::getFixedStack(FrameIdx),
5598 false, false, false, 0);
5601 // FCFID it and return it.
5602 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5603 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5604 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5608 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5609 SelectionDAG &DAG) const {
5612 The rounding mode is in bits 30:31 of FPSR, and has the following
5619 FLT_ROUNDS, on the other hand, expects the following:
5626 To perform the conversion, we do:
5627 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5630 MachineFunction &MF = DAG.getMachineFunction();
5631 EVT VT = Op.getValueType();
5632 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5634 // Save FP Control Word to register
5636 MVT::f64, // return register
5637 MVT::Glue // unused in this context
5639 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5641 // Save FP register to stack slot
5642 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5643 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5644 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5645 StackSlot, MachinePointerInfo(), false, false,0);
5647 // Load FP Control Word from low 32 bits of stack slot.
5648 SDValue Four = DAG.getConstant(4, PtrVT);
5649 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5650 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5651 false, false, false, 0);
5653 // Transform as necessary
5655 DAG.getNode(ISD::AND, dl, MVT::i32,
5656 CWD, DAG.getConstant(3, MVT::i32));
5658 DAG.getNode(ISD::SRL, dl, MVT::i32,
5659 DAG.getNode(ISD::AND, dl, MVT::i32,
5660 DAG.getNode(ISD::XOR, dl, MVT::i32,
5661 CWD, DAG.getConstant(3, MVT::i32)),
5662 DAG.getConstant(3, MVT::i32)),
5663 DAG.getConstant(1, MVT::i32));
5666 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5668 return DAG.getNode((VT.getSizeInBits() < 16 ?
5669 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5672 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5673 EVT VT = Op.getValueType();
5674 unsigned BitWidth = VT.getSizeInBits();
5676 assert(Op.getNumOperands() == 3 &&
5677 VT == Op.getOperand(1).getValueType() &&
5680 // Expand into a bunch of logical ops. Note that these ops
5681 // depend on the PPC behavior for oversized shift amounts.
5682 SDValue Lo = Op.getOperand(0);
5683 SDValue Hi = Op.getOperand(1);
5684 SDValue Amt = Op.getOperand(2);
5685 EVT AmtVT = Amt.getValueType();
5687 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5688 DAG.getConstant(BitWidth, AmtVT), Amt);
5689 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5690 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5691 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5692 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5693 DAG.getConstant(-BitWidth, AmtVT));
5694 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5695 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5696 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5697 SDValue OutOps[] = { OutLo, OutHi };
5698 return DAG.getMergeValues(OutOps, dl);
5701 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5702 EVT VT = Op.getValueType();
5704 unsigned BitWidth = VT.getSizeInBits();
5705 assert(Op.getNumOperands() == 3 &&
5706 VT == Op.getOperand(1).getValueType() &&
5709 // Expand into a bunch of logical ops. Note that these ops
5710 // depend on the PPC behavior for oversized shift amounts.
5711 SDValue Lo = Op.getOperand(0);
5712 SDValue Hi = Op.getOperand(1);
5713 SDValue Amt = Op.getOperand(2);
5714 EVT AmtVT = Amt.getValueType();
5716 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5717 DAG.getConstant(BitWidth, AmtVT), Amt);
5718 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5719 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5720 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5721 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5722 DAG.getConstant(-BitWidth, AmtVT));
5723 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5724 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5725 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5726 SDValue OutOps[] = { OutLo, OutHi };
5727 return DAG.getMergeValues(OutOps, dl);
5730 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5732 EVT VT = Op.getValueType();
5733 unsigned BitWidth = VT.getSizeInBits();
5734 assert(Op.getNumOperands() == 3 &&
5735 VT == Op.getOperand(1).getValueType() &&
5738 // Expand into a bunch of logical ops, followed by a select_cc.
5739 SDValue Lo = Op.getOperand(0);
5740 SDValue Hi = Op.getOperand(1);
5741 SDValue Amt = Op.getOperand(2);
5742 EVT AmtVT = Amt.getValueType();
5744 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5745 DAG.getConstant(BitWidth, AmtVT), Amt);
5746 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5747 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5748 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5749 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5750 DAG.getConstant(-BitWidth, AmtVT));
5751 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5752 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5753 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5754 Tmp4, Tmp6, ISD::SETLE);
5755 SDValue OutOps[] = { OutLo, OutHi };
5756 return DAG.getMergeValues(OutOps, dl);
5759 //===----------------------------------------------------------------------===//
5760 // Vector related lowering.
5763 /// BuildSplatI - Build a canonical splati of Val with an element size of
5764 /// SplatSize. Cast the result to VT.
5765 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5766 SelectionDAG &DAG, SDLoc dl) {
5767 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5769 static const EVT VTys[] = { // canonical VT to use for each size.
5770 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5773 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5775 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5779 EVT CanonicalVT = VTys[SplatSize-1];
5781 // Build a canonical splat for this value.
5782 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5783 SmallVector<SDValue, 8> Ops;
5784 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5785 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5786 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5789 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5790 /// specified intrinsic ID.
5791 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5792 SelectionDAG &DAG, SDLoc dl,
5793 EVT DestVT = MVT::Other) {
5794 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5795 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5796 DAG.getConstant(IID, MVT::i32), Op);
5799 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5800 /// specified intrinsic ID.
5801 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5802 SelectionDAG &DAG, SDLoc dl,
5803 EVT DestVT = MVT::Other) {
5804 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5805 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5806 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5809 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5810 /// specified intrinsic ID.
5811 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5812 SDValue Op2, SelectionDAG &DAG,
5813 SDLoc dl, EVT DestVT = MVT::Other) {
5814 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5815 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5816 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5820 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5821 /// amount. The result has the specified value type.
5822 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5823 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5824 // Force LHS/RHS to be the right type.
5825 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5826 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5829 for (unsigned i = 0; i != 16; ++i)
5831 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5832 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5835 // If this is a case we can't handle, return null and let the default
5836 // expansion code take care of it. If we CAN select this case, and if it
5837 // selects to a single instruction, return Op. Otherwise, if we can codegen
5838 // this case more efficiently than a constant pool load, lower it to the
5839 // sequence of ops that should be used.
5840 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5841 SelectionDAG &DAG) const {
5843 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5844 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5846 // Check if this is a splat of a constant value.
5847 APInt APSplatBits, APSplatUndef;
5848 unsigned SplatBitSize;
5850 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5851 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5854 unsigned SplatBits = APSplatBits.getZExtValue();
5855 unsigned SplatUndef = APSplatUndef.getZExtValue();
5856 unsigned SplatSize = SplatBitSize / 8;
5858 // First, handle single instruction cases.
5861 if (SplatBits == 0) {
5862 // Canonicalize all zero vectors to be v4i32.
5863 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5864 SDValue Z = DAG.getConstant(0, MVT::i32);
5865 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5866 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5871 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5872 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5874 if (SextVal >= -16 && SextVal <= 15)
5875 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5878 // Two instruction sequences.
5880 // If this value is in the range [-32,30] and is even, use:
5881 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5882 // If this value is in the range [17,31] and is odd, use:
5883 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5884 // If this value is in the range [-31,-17] and is odd, use:
5885 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5886 // Note the last two are three-instruction sequences.
5887 if (SextVal >= -32 && SextVal <= 31) {
5888 // To avoid having these optimizations undone by constant folding,
5889 // we convert to a pseudo that will be expanded later into one of
5891 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5892 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5893 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5894 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5895 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5896 if (VT == Op.getValueType())
5899 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5902 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5903 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5905 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5906 // Make -1 and vspltisw -1:
5907 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5909 // Make the VSLW intrinsic, computing 0x8000_0000.
5910 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5913 // xor by OnesV to invert it.
5914 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5915 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5918 // The remaining cases assume either big endian element order or
5919 // a splat-size that equates to the element size of the vector
5920 // to be built. An example that doesn't work for little endian is
5921 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5922 // and a vector element size of 16 bits. The code below will
5923 // produce the vector in big endian element order, which for little
5924 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5926 // For now, just avoid these optimizations in that case.
5927 // FIXME: Develop correct optimizations for LE with mismatched
5928 // splat and element sizes.
5930 if (Subtarget.isLittleEndian() &&
5931 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5934 // Check to see if this is a wide variety of vsplti*, binop self cases.
5935 static const signed char SplatCsts[] = {
5936 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5937 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5940 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5941 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5942 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5943 int i = SplatCsts[idx];
5945 // Figure out what shift amount will be used by altivec if shifted by i in
5947 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5949 // vsplti + shl self.
5950 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5951 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5952 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5953 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5954 Intrinsic::ppc_altivec_vslw
5956 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5957 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5960 // vsplti + srl self.
5961 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5962 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5963 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5964 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5965 Intrinsic::ppc_altivec_vsrw
5967 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5968 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5971 // vsplti + sra self.
5972 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5973 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5974 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5975 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5976 Intrinsic::ppc_altivec_vsraw
5978 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5979 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5982 // vsplti + rol self.
5983 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5984 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5985 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5986 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5987 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5988 Intrinsic::ppc_altivec_vrlw
5990 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5991 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5994 // t = vsplti c, result = vsldoi t, t, 1
5995 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5996 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5997 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5999 // t = vsplti c, result = vsldoi t, t, 2
6000 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6001 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6002 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6004 // t = vsplti c, result = vsldoi t, t, 3
6005 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6006 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6007 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6014 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6015 /// the specified operations to build the shuffle.
6016 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6017 SDValue RHS, SelectionDAG &DAG,
6019 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6020 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6021 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6024 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6036 if (OpNum == OP_COPY) {
6037 if (LHSID == (1*9+2)*9+3) return LHS;
6038 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6042 SDValue OpLHS, OpRHS;
6043 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6044 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6048 default: llvm_unreachable("Unknown i32 permute!");
6050 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6051 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6052 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6053 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6056 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6057 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6058 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6059 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6062 for (unsigned i = 0; i != 16; ++i)
6063 ShufIdxs[i] = (i&3)+0;
6066 for (unsigned i = 0; i != 16; ++i)
6067 ShufIdxs[i] = (i&3)+4;
6070 for (unsigned i = 0; i != 16; ++i)
6071 ShufIdxs[i] = (i&3)+8;
6074 for (unsigned i = 0; i != 16; ++i)
6075 ShufIdxs[i] = (i&3)+12;
6078 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6080 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6082 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6084 EVT VT = OpLHS.getValueType();
6085 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6086 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6087 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6088 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6091 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6092 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6093 /// return the code it can be lowered into. Worst case, it can always be
6094 /// lowered into a vperm.
6095 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6096 SelectionDAG &DAG) const {
6098 SDValue V1 = Op.getOperand(0);
6099 SDValue V2 = Op.getOperand(1);
6100 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6101 EVT VT = Op.getValueType();
6102 bool isLittleEndian = Subtarget.isLittleEndian();
6104 // Cases that are handled by instructions that take permute immediates
6105 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6106 // selected by the instruction selector.
6107 if (V2.getOpcode() == ISD::UNDEF) {
6108 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6109 PPC::isSplatShuffleMask(SVOp, 2) ||
6110 PPC::isSplatShuffleMask(SVOp, 4) ||
6111 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6112 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6113 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6114 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6115 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6116 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6117 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6118 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6119 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6124 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6125 // and produce a fixed permutation. If any of these match, do not lower to
6127 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6128 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6129 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6130 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6131 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6132 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6133 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6134 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6135 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6136 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6139 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6140 // perfect shuffle table to emit an optimal matching sequence.
6141 ArrayRef<int> PermMask = SVOp->getMask();
6143 unsigned PFIndexes[4];
6144 bool isFourElementShuffle = true;
6145 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6146 unsigned EltNo = 8; // Start out undef.
6147 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6148 if (PermMask[i*4+j] < 0)
6149 continue; // Undef, ignore it.
6151 unsigned ByteSource = PermMask[i*4+j];
6152 if ((ByteSource & 3) != j) {
6153 isFourElementShuffle = false;
6158 EltNo = ByteSource/4;
6159 } else if (EltNo != ByteSource/4) {
6160 isFourElementShuffle = false;
6164 PFIndexes[i] = EltNo;
6167 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6168 // perfect shuffle vector to determine if it is cost effective to do this as
6169 // discrete instructions, or whether we should use a vperm.
6170 // For now, we skip this for little endian until such time as we have a
6171 // little-endian perfect shuffle table.
6172 if (isFourElementShuffle && !isLittleEndian) {
6173 // Compute the index in the perfect shuffle table.
6174 unsigned PFTableIndex =
6175 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6177 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6178 unsigned Cost = (PFEntry >> 30);
6180 // Determining when to avoid vperm is tricky. Many things affect the cost
6181 // of vperm, particularly how many times the perm mask needs to be computed.
6182 // For example, if the perm mask can be hoisted out of a loop or is already
6183 // used (perhaps because there are multiple permutes with the same shuffle
6184 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6185 // the loop requires an extra register.
6187 // As a compromise, we only emit discrete instructions if the shuffle can be
6188 // generated in 3 or fewer operations. When we have loop information
6189 // available, if this block is within a loop, we should avoid using vperm
6190 // for 3-operation perms and use a constant pool load instead.
6192 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6195 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6196 // vector that will get spilled to the constant pool.
6197 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6199 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6200 // that it is in input element units, not in bytes. Convert now.
6202 // For little endian, the order of the input vectors is reversed, and
6203 // the permutation mask is complemented with respect to 31. This is
6204 // necessary to produce proper semantics with the big-endian-biased vperm
6206 EVT EltVT = V1.getValueType().getVectorElementType();
6207 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6209 SmallVector<SDValue, 16> ResultMask;
6210 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6211 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6213 for (unsigned j = 0; j != BytesPerElement; ++j)
6215 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6218 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6222 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6225 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6228 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6232 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6233 /// altivec comparison. If it is, return true and fill in Opc/isDot with
6234 /// information about the intrinsic.
6235 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6237 unsigned IntrinsicID =
6238 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6241 switch (IntrinsicID) {
6242 default: return false;
6243 // Comparison predicates.
6244 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
6245 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6246 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
6247 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
6248 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6249 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6250 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6251 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6252 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6253 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6254 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6255 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6256 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6258 // Normal Comparisons.
6259 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
6260 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
6261 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
6262 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
6263 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
6264 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
6265 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
6266 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
6267 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
6268 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
6269 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
6270 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
6271 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
6276 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6277 /// lower, do it, otherwise return null.
6278 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6279 SelectionDAG &DAG) const {
6280 // If this is a lowered altivec predicate compare, CompareOpc is set to the
6281 // opcode number of the comparison.
6285 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6286 return SDValue(); // Don't custom lower most intrinsics.
6288 // If this is a non-dot comparison, make the VCMP node and we are done.
6290 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6291 Op.getOperand(1), Op.getOperand(2),
6292 DAG.getConstant(CompareOpc, MVT::i32));
6293 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6296 // Create the PPCISD altivec 'dot' comparison node.
6298 Op.getOperand(2), // LHS
6299 Op.getOperand(3), // RHS
6300 DAG.getConstant(CompareOpc, MVT::i32)
6302 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6303 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6305 // Now that we have the comparison, emit a copy from the CR to a GPR.
6306 // This is flagged to the above dot comparison.
6307 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6308 DAG.getRegister(PPC::CR6, MVT::i32),
6309 CompNode.getValue(1));
6311 // Unpack the result based on how the target uses it.
6312 unsigned BitNo; // Bit # of CR6.
6313 bool InvertBit; // Invert result?
6314 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6315 default: // Can't happen, don't crash on invalid number though.
6316 case 0: // Return the value of the EQ bit of CR6.
6317 BitNo = 0; InvertBit = false;
6319 case 1: // Return the inverted value of the EQ bit of CR6.
6320 BitNo = 0; InvertBit = true;
6322 case 2: // Return the value of the LT bit of CR6.
6323 BitNo = 2; InvertBit = false;
6325 case 3: // Return the inverted value of the LT bit of CR6.
6326 BitNo = 2; InvertBit = true;
6330 // Shift the bit into the low position.
6331 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6332 DAG.getConstant(8-(3-BitNo), MVT::i32));
6334 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6335 DAG.getConstant(1, MVT::i32));
6337 // If we are supposed to, toggle the bit.
6339 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6340 DAG.getConstant(1, MVT::i32));
6344 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6345 SelectionDAG &DAG) const {
6347 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6348 // instructions), but for smaller types, we need to first extend up to v2i32
6349 // before doing going farther.
6350 if (Op.getValueType() == MVT::v2i64) {
6351 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6352 if (ExtVT != MVT::v2i32) {
6353 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6354 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6355 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6356 ExtVT.getVectorElementType(), 4)));
6357 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6358 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6359 DAG.getValueType(MVT::v2i32));
6368 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6369 SelectionDAG &DAG) const {
6371 // Create a stack slot that is 16-byte aligned.
6372 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6373 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6374 EVT PtrVT = getPointerTy();
6375 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6377 // Store the input value into Value#0 of the stack slot.
6378 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6379 Op.getOperand(0), FIdx, MachinePointerInfo(),
6382 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6383 false, false, false, 0);
6386 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6388 if (Op.getValueType() == MVT::v4i32) {
6389 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6391 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6392 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6394 SDValue RHSSwap = // = vrlw RHS, 16
6395 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6397 // Shrinkify inputs to v8i16.
6398 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6399 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6400 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6402 // Low parts multiplied together, generating 32-bit results (we ignore the
6404 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6405 LHS, RHS, DAG, dl, MVT::v4i32);
6407 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6408 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6409 // Shift the high parts up 16 bits.
6410 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6412 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6413 } else if (Op.getValueType() == MVT::v8i16) {
6414 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6416 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6418 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6419 LHS, RHS, Zero, DAG, dl);
6420 } else if (Op.getValueType() == MVT::v16i8) {
6421 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6422 bool isLittleEndian = Subtarget.isLittleEndian();
6424 // Multiply the even 8-bit parts, producing 16-bit sums.
6425 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6426 LHS, RHS, DAG, dl, MVT::v8i16);
6427 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6429 // Multiply the odd 8-bit parts, producing 16-bit sums.
6430 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6431 LHS, RHS, DAG, dl, MVT::v8i16);
6432 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6434 // Merge the results together. Because vmuleub and vmuloub are
6435 // instructions with a big-endian bias, we must reverse the
6436 // element numbering and reverse the meaning of "odd" and "even"
6437 // when generating little endian code.
6439 for (unsigned i = 0; i != 8; ++i) {
6440 if (isLittleEndian) {
6442 Ops[i*2+1] = 2*i+16;
6445 Ops[i*2+1] = 2*i+1+16;
6449 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6451 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6453 llvm_unreachable("Unknown mul to lower!");
6457 /// LowerOperation - Provide custom lowering hooks for some operations.
6459 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6460 switch (Op.getOpcode()) {
6461 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6462 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6463 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6464 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6465 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6466 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6467 case ISD::SETCC: return LowerSETCC(Op, DAG);
6468 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6469 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6471 return LowerVASTART(Op, DAG, Subtarget);
6474 return LowerVAARG(Op, DAG, Subtarget);
6477 return LowerVACOPY(Op, DAG, Subtarget);
6479 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
6480 case ISD::DYNAMIC_STACKALLOC:
6481 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6483 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6484 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6486 case ISD::LOAD: return LowerLOAD(Op, DAG);
6487 case ISD::STORE: return LowerSTORE(Op, DAG);
6488 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6489 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6490 case ISD::FP_TO_UINT:
6491 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6493 case ISD::UINT_TO_FP:
6494 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6495 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6497 // Lower 64-bit shifts.
6498 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6499 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6500 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6502 // Vector-related lowering.
6503 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6504 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6505 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6506 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6507 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6508 case ISD::MUL: return LowerMUL(Op, DAG);
6510 // For counter-based loop handling.
6511 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6513 // Frame & Return address.
6514 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6515 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6519 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6520 SmallVectorImpl<SDValue>&Results,
6521 SelectionDAG &DAG) const {
6522 const TargetMachine &TM = getTargetMachine();
6524 switch (N->getOpcode()) {
6526 llvm_unreachable("Do not know how to custom type legalize this operation!");
6527 case ISD::READCYCLECOUNTER: {
6528 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6529 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6531 Results.push_back(RTB);
6532 Results.push_back(RTB.getValue(1));
6533 Results.push_back(RTB.getValue(2));
6536 case ISD::INTRINSIC_W_CHAIN: {
6537 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6538 Intrinsic::ppc_is_decremented_ctr_nonzero)
6541 assert(N->getValueType(0) == MVT::i1 &&
6542 "Unexpected result type for CTR decrement intrinsic");
6543 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6544 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6545 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6548 Results.push_back(NewInt);
6549 Results.push_back(NewInt.getValue(1));
6553 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6554 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6557 EVT VT = N->getValueType(0);
6559 if (VT == MVT::i64) {
6560 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6562 Results.push_back(NewNode);
6563 Results.push_back(NewNode.getValue(1));
6567 case ISD::FP_ROUND_INREG: {
6568 assert(N->getValueType(0) == MVT::ppcf128);
6569 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6570 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6571 MVT::f64, N->getOperand(0),
6572 DAG.getIntPtrConstant(0));
6573 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6574 MVT::f64, N->getOperand(0),
6575 DAG.getIntPtrConstant(1));
6577 // Add the two halves of the long double in round-to-zero mode.
6578 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6580 // We know the low half is about to be thrown away, so just use something
6582 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6586 case ISD::FP_TO_SINT:
6587 // LowerFP_TO_INT() can only handle f32 and f64.
6588 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6590 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6596 //===----------------------------------------------------------------------===//
6597 // Other Lowering Code
6598 //===----------------------------------------------------------------------===//
6600 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6601 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6602 Function *Func = Intrinsic::getDeclaration(M, Id);
6603 return Builder.CreateCall(Func);
6606 // The mappings for emitLeading/TrailingFence is taken from
6607 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6608 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6609 AtomicOrdering Ord, bool IsStore,
6610 bool IsLoad) const {
6611 if (Ord == SequentiallyConsistent)
6612 return callIntrinsic(Builder, Intrinsic::ppc_sync);
6613 else if (isAtLeastRelease(Ord))
6614 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6619 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6620 AtomicOrdering Ord, bool IsStore,
6621 bool IsLoad) const {
6622 if (IsLoad && isAtLeastAcquire(Ord))
6623 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6624 // FIXME: this is too conservative, a dependent branch + isync is enough.
6625 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6626 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6627 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6633 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6634 bool is64bit, unsigned BinOpcode) const {
6635 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6636 const TargetInstrInfo *TII =
6637 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6639 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6640 MachineFunction *F = BB->getParent();
6641 MachineFunction::iterator It = BB;
6644 unsigned dest = MI->getOperand(0).getReg();
6645 unsigned ptrA = MI->getOperand(1).getReg();
6646 unsigned ptrB = MI->getOperand(2).getReg();
6647 unsigned incr = MI->getOperand(3).getReg();
6648 DebugLoc dl = MI->getDebugLoc();
6650 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6651 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6652 F->insert(It, loopMBB);
6653 F->insert(It, exitMBB);
6654 exitMBB->splice(exitMBB->begin(), BB,
6655 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6656 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6658 MachineRegisterInfo &RegInfo = F->getRegInfo();
6659 unsigned TmpReg = (!BinOpcode) ? incr :
6660 RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6661 : &PPC::GPRCRegClass);
6665 // fallthrough --> loopMBB
6666 BB->addSuccessor(loopMBB);
6669 // l[wd]arx dest, ptr
6670 // add r0, dest, incr
6671 // st[wd]cx. r0, ptr
6673 // fallthrough --> exitMBB
6675 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6676 .addReg(ptrA).addReg(ptrB);
6678 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6679 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6680 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6681 BuildMI(BB, dl, TII->get(PPC::BCC))
6682 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6683 BB->addSuccessor(loopMBB);
6684 BB->addSuccessor(exitMBB);
6693 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6694 MachineBasicBlock *BB,
6695 bool is8bit, // operation
6696 unsigned BinOpcode) const {
6697 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6698 const TargetInstrInfo *TII =
6699 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6700 // In 64 bit mode we have to use 64 bits for addresses, even though the
6701 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6702 // registers without caring whether they're 32 or 64, but here we're
6703 // doing actual arithmetic on the addresses.
6704 bool is64bit = Subtarget.isPPC64();
6705 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6707 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6708 MachineFunction *F = BB->getParent();
6709 MachineFunction::iterator It = BB;
6712 unsigned dest = MI->getOperand(0).getReg();
6713 unsigned ptrA = MI->getOperand(1).getReg();
6714 unsigned ptrB = MI->getOperand(2).getReg();
6715 unsigned incr = MI->getOperand(3).getReg();
6716 DebugLoc dl = MI->getDebugLoc();
6718 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6719 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6720 F->insert(It, loopMBB);
6721 F->insert(It, exitMBB);
6722 exitMBB->splice(exitMBB->begin(), BB,
6723 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6724 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6726 MachineRegisterInfo &RegInfo = F->getRegInfo();
6727 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
6728 : &PPC::GPRCRegClass;
6729 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6730 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6731 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6732 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6733 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6734 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6735 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6736 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6737 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6738 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6739 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6741 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6745 // fallthrough --> loopMBB
6746 BB->addSuccessor(loopMBB);
6748 // The 4-byte load must be aligned, while a char or short may be
6749 // anywhere in the word. Hence all this nasty bookkeeping code.
6750 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6751 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6752 // xori shift, shift1, 24 [16]
6753 // rlwinm ptr, ptr1, 0, 0, 29
6754 // slw incr2, incr, shift
6755 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6756 // slw mask, mask2, shift
6758 // lwarx tmpDest, ptr
6759 // add tmp, tmpDest, incr2
6760 // andc tmp2, tmpDest, mask
6761 // and tmp3, tmp, mask
6762 // or tmp4, tmp3, tmp2
6765 // fallthrough --> exitMBB
6766 // srw dest, tmpDest, shift
6767 if (ptrA != ZeroReg) {
6768 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6769 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6770 .addReg(ptrA).addReg(ptrB);
6774 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6775 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6776 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6777 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6779 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6780 .addReg(Ptr1Reg).addImm(0).addImm(61);
6782 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6783 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6784 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6785 .addReg(incr).addReg(ShiftReg);
6787 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6789 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6790 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6792 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6793 .addReg(Mask2Reg).addReg(ShiftReg);
6796 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6797 .addReg(ZeroReg).addReg(PtrReg);
6799 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6800 .addReg(Incr2Reg).addReg(TmpDestReg);
6801 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6802 .addReg(TmpDestReg).addReg(MaskReg);
6803 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6804 .addReg(TmpReg).addReg(MaskReg);
6805 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6806 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6807 BuildMI(BB, dl, TII->get(PPC::STWCX))
6808 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6809 BuildMI(BB, dl, TII->get(PPC::BCC))
6810 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6811 BB->addSuccessor(loopMBB);
6812 BB->addSuccessor(exitMBB);
6817 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6822 llvm::MachineBasicBlock*
6823 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6824 MachineBasicBlock *MBB) const {
6825 DebugLoc DL = MI->getDebugLoc();
6826 const TargetInstrInfo *TII =
6827 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6829 MachineFunction *MF = MBB->getParent();
6830 MachineRegisterInfo &MRI = MF->getRegInfo();
6832 const BasicBlock *BB = MBB->getBasicBlock();
6833 MachineFunction::iterator I = MBB;
6837 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6838 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6840 unsigned DstReg = MI->getOperand(0).getReg();
6841 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6842 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6843 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6844 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6846 MVT PVT = getPointerTy();
6847 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6848 "Invalid Pointer Size!");
6849 // For v = setjmp(buf), we generate
6852 // SjLjSetup mainMBB
6858 // buf[LabelOffset] = LR
6862 // v = phi(main, restore)
6865 MachineBasicBlock *thisMBB = MBB;
6866 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6867 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6868 MF->insert(I, mainMBB);
6869 MF->insert(I, sinkMBB);
6871 MachineInstrBuilder MIB;
6873 // Transfer the remainder of BB and its successor edges to sinkMBB.
6874 sinkMBB->splice(sinkMBB->begin(), MBB,
6875 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6876 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6878 // Note that the structure of the jmp_buf used here is not compatible
6879 // with that used by libc, and is not designed to be. Specifically, it
6880 // stores only those 'reserved' registers that LLVM does not otherwise
6881 // understand how to spill. Also, by convention, by the time this
6882 // intrinsic is called, Clang has already stored the frame address in the
6883 // first slot of the buffer and stack address in the third. Following the
6884 // X86 target code, we'll store the jump address in the second slot. We also
6885 // need to save the TOC pointer (R2) to handle jumps between shared
6886 // libraries, and that will be stored in the fourth slot. The thread
6887 // identifier (R13) is not affected.
6890 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6891 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6892 const int64_t BPOffset = 4 * PVT.getStoreSize();
6894 // Prepare IP either in reg.
6895 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6896 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6897 unsigned BufReg = MI->getOperand(1).getReg();
6899 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6900 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6904 MIB.setMemRefs(MMOBegin, MMOEnd);
6907 // Naked functions never have a base pointer, and so we use r1. For all
6908 // other functions, this decision must be delayed until during PEI.
6910 if (MF->getFunction()->getAttributes().hasAttribute(
6911 AttributeSet::FunctionIndex, Attribute::Naked))
6912 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6914 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6916 MIB = BuildMI(*thisMBB, MI, DL,
6917 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6921 MIB.setMemRefs(MMOBegin, MMOEnd);
6924 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6925 const PPCRegisterInfo *TRI =
6926 getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
6927 MIB.addRegMask(TRI->getNoPreservedMask());
6929 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6931 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6933 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6935 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6936 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6940 MIB = BuildMI(mainMBB, DL,
6941 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6944 if (Subtarget.isPPC64()) {
6945 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6947 .addImm(LabelOffset)
6950 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6952 .addImm(LabelOffset)
6956 MIB.setMemRefs(MMOBegin, MMOEnd);
6958 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6959 mainMBB->addSuccessor(sinkMBB);
6962 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6963 TII->get(PPC::PHI), DstReg)
6964 .addReg(mainDstReg).addMBB(mainMBB)
6965 .addReg(restoreDstReg).addMBB(thisMBB);
6967 MI->eraseFromParent();
6972 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6973 MachineBasicBlock *MBB) const {
6974 DebugLoc DL = MI->getDebugLoc();
6975 const TargetInstrInfo *TII =
6976 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6978 MachineFunction *MF = MBB->getParent();
6979 MachineRegisterInfo &MRI = MF->getRegInfo();
6982 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6983 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6985 MVT PVT = getPointerTy();
6986 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6987 "Invalid Pointer Size!");
6989 const TargetRegisterClass *RC =
6990 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6991 unsigned Tmp = MRI.createVirtualRegister(RC);
6992 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6993 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6994 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6995 unsigned BP = (PVT == MVT::i64) ? PPC::X30 :
6996 (Subtarget.isSVR4ABI() &&
6997 MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6998 PPC::R29 : PPC::R30);
7000 MachineInstrBuilder MIB;
7002 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7003 const int64_t SPOffset = 2 * PVT.getStoreSize();
7004 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7005 const int64_t BPOffset = 4 * PVT.getStoreSize();
7007 unsigned BufReg = MI->getOperand(0).getReg();
7009 // Reload FP (the jumped-to function may not have had a
7010 // frame pointer, and if so, then its r31 will be restored
7012 if (PVT == MVT::i64) {
7013 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7017 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7021 MIB.setMemRefs(MMOBegin, MMOEnd);
7024 if (PVT == MVT::i64) {
7025 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7026 .addImm(LabelOffset)
7029 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7030 .addImm(LabelOffset)
7033 MIB.setMemRefs(MMOBegin, MMOEnd);
7036 if (PVT == MVT::i64) {
7037 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7041 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7045 MIB.setMemRefs(MMOBegin, MMOEnd);
7048 if (PVT == MVT::i64) {
7049 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7053 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7057 MIB.setMemRefs(MMOBegin, MMOEnd);
7060 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7061 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7065 MIB.setMemRefs(MMOBegin, MMOEnd);
7069 BuildMI(*MBB, MI, DL,
7070 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7071 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7073 MI->eraseFromParent();
7078 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7079 MachineBasicBlock *BB) const {
7080 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7081 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7082 return emitEHSjLjSetJmp(MI, BB);
7083 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7084 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7085 return emitEHSjLjLongJmp(MI, BB);
7088 const TargetInstrInfo *TII =
7089 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7091 // To "insert" these instructions we actually have to insert their
7092 // control-flow patterns.
7093 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7094 MachineFunction::iterator It = BB;
7097 MachineFunction *F = BB->getParent();
7099 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7100 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7101 MI->getOpcode() == PPC::SELECT_I4 ||
7102 MI->getOpcode() == PPC::SELECT_I8)) {
7103 SmallVector<MachineOperand, 2> Cond;
7104 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7105 MI->getOpcode() == PPC::SELECT_CC_I8)
7106 Cond.push_back(MI->getOperand(4));
7108 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7109 Cond.push_back(MI->getOperand(1));
7111 DebugLoc dl = MI->getDebugLoc();
7112 const TargetInstrInfo *TII =
7113 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7114 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7115 Cond, MI->getOperand(2).getReg(),
7116 MI->getOperand(3).getReg());
7117 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7118 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7119 MI->getOpcode() == PPC::SELECT_CC_F4 ||
7120 MI->getOpcode() == PPC::SELECT_CC_F8 ||
7121 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7122 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7123 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7124 MI->getOpcode() == PPC::SELECT_I4 ||
7125 MI->getOpcode() == PPC::SELECT_I8 ||
7126 MI->getOpcode() == PPC::SELECT_F4 ||
7127 MI->getOpcode() == PPC::SELECT_F8 ||
7128 MI->getOpcode() == PPC::SELECT_VRRC ||
7129 MI->getOpcode() == PPC::SELECT_VSFRC ||
7130 MI->getOpcode() == PPC::SELECT_VSRC) {
7131 // The incoming instruction knows the destination vreg to set, the
7132 // condition code register to branch on, the true/false values to
7133 // select between, and a branch opcode to use.
7138 // cmpTY ccX, r1, r2
7140 // fallthrough --> copy0MBB
7141 MachineBasicBlock *thisMBB = BB;
7142 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7143 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7144 DebugLoc dl = MI->getDebugLoc();
7145 F->insert(It, copy0MBB);
7146 F->insert(It, sinkMBB);
7148 // Transfer the remainder of BB and its successor edges to sinkMBB.
7149 sinkMBB->splice(sinkMBB->begin(), BB,
7150 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7151 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7153 // Next, add the true and fallthrough blocks as its successors.
7154 BB->addSuccessor(copy0MBB);
7155 BB->addSuccessor(sinkMBB);
7157 if (MI->getOpcode() == PPC::SELECT_I4 ||
7158 MI->getOpcode() == PPC::SELECT_I8 ||
7159 MI->getOpcode() == PPC::SELECT_F4 ||
7160 MI->getOpcode() == PPC::SELECT_F8 ||
7161 MI->getOpcode() == PPC::SELECT_VRRC ||
7162 MI->getOpcode() == PPC::SELECT_VSFRC ||
7163 MI->getOpcode() == PPC::SELECT_VSRC) {
7164 BuildMI(BB, dl, TII->get(PPC::BC))
7165 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7167 unsigned SelectPred = MI->getOperand(4).getImm();
7168 BuildMI(BB, dl, TII->get(PPC::BCC))
7169 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7173 // %FalseValue = ...
7174 // # fallthrough to sinkMBB
7177 // Update machine-CFG edges
7178 BB->addSuccessor(sinkMBB);
7181 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7184 BuildMI(*BB, BB->begin(), dl,
7185 TII->get(PPC::PHI), MI->getOperand(0).getReg())
7186 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7187 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7188 } else if (MI->getOpcode() == PPC::ReadTB) {
7189 // To read the 64-bit time-base register on a 32-bit target, we read the
7190 // two halves. Should the counter have wrapped while it was being read, we
7191 // need to try again.
7194 // mfspr Rx,TBU # load from TBU
7195 // mfspr Ry,TB # load from TB
7196 // mfspr Rz,TBU # load from TBU
7197 // cmpw crX,Rx,Rz # check if ‘old’=’new’
7198 // bne readLoop # branch if they're not equal
7201 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7202 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7203 DebugLoc dl = MI->getDebugLoc();
7204 F->insert(It, readMBB);
7205 F->insert(It, sinkMBB);
7207 // Transfer the remainder of BB and its successor edges to sinkMBB.
7208 sinkMBB->splice(sinkMBB->begin(), BB,
7209 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7210 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7212 BB->addSuccessor(readMBB);
7215 MachineRegisterInfo &RegInfo = F->getRegInfo();
7216 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7217 unsigned LoReg = MI->getOperand(0).getReg();
7218 unsigned HiReg = MI->getOperand(1).getReg();
7220 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7221 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7222 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7224 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7226 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7227 .addReg(HiReg).addReg(ReadAgainReg);
7228 BuildMI(BB, dl, TII->get(PPC::BCC))
7229 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7231 BB->addSuccessor(readMBB);
7232 BB->addSuccessor(sinkMBB);
7234 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7235 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7236 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7237 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7238 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7239 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7240 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7241 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7243 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7244 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7245 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7246 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7247 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7248 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7249 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7250 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7252 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7253 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7254 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7255 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7256 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7257 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7258 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7259 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7261 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7262 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7263 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7264 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7265 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7266 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7267 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7268 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7270 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7271 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7272 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7273 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7274 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7275 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7276 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7277 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7279 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7280 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7281 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7282 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7283 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7284 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7285 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7286 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7288 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7289 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7290 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7291 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7292 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7293 BB = EmitAtomicBinary(MI, BB, false, 0);
7294 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7295 BB = EmitAtomicBinary(MI, BB, true, 0);
7297 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7298 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7299 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7301 unsigned dest = MI->getOperand(0).getReg();
7302 unsigned ptrA = MI->getOperand(1).getReg();
7303 unsigned ptrB = MI->getOperand(2).getReg();
7304 unsigned oldval = MI->getOperand(3).getReg();
7305 unsigned newval = MI->getOperand(4).getReg();
7306 DebugLoc dl = MI->getDebugLoc();
7308 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7309 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7310 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7311 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7312 F->insert(It, loop1MBB);
7313 F->insert(It, loop2MBB);
7314 F->insert(It, midMBB);
7315 F->insert(It, exitMBB);
7316 exitMBB->splice(exitMBB->begin(), BB,
7317 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7318 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7322 // fallthrough --> loopMBB
7323 BB->addSuccessor(loop1MBB);
7326 // l[wd]arx dest, ptr
7327 // cmp[wd] dest, oldval
7330 // st[wd]cx. newval, ptr
7334 // st[wd]cx. dest, ptr
7337 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7338 .addReg(ptrA).addReg(ptrB);
7339 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7340 .addReg(oldval).addReg(dest);
7341 BuildMI(BB, dl, TII->get(PPC::BCC))
7342 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7343 BB->addSuccessor(loop2MBB);
7344 BB->addSuccessor(midMBB);
7347 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7348 .addReg(newval).addReg(ptrA).addReg(ptrB);
7349 BuildMI(BB, dl, TII->get(PPC::BCC))
7350 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7351 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7352 BB->addSuccessor(loop1MBB);
7353 BB->addSuccessor(exitMBB);
7356 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7357 .addReg(dest).addReg(ptrA).addReg(ptrB);
7358 BB->addSuccessor(exitMBB);
7363 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7364 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7365 // We must use 64-bit registers for addresses when targeting 64-bit,
7366 // since we're actually doing arithmetic on them. Other registers
7368 bool is64bit = Subtarget.isPPC64();
7369 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7371 unsigned dest = MI->getOperand(0).getReg();
7372 unsigned ptrA = MI->getOperand(1).getReg();
7373 unsigned ptrB = MI->getOperand(2).getReg();
7374 unsigned oldval = MI->getOperand(3).getReg();
7375 unsigned newval = MI->getOperand(4).getReg();
7376 DebugLoc dl = MI->getDebugLoc();
7378 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7379 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7380 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7381 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7382 F->insert(It, loop1MBB);
7383 F->insert(It, loop2MBB);
7384 F->insert(It, midMBB);
7385 F->insert(It, exitMBB);
7386 exitMBB->splice(exitMBB->begin(), BB,
7387 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7388 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7390 MachineRegisterInfo &RegInfo = F->getRegInfo();
7391 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7392 : &PPC::GPRCRegClass;
7393 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7394 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7395 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7396 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7397 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7398 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7399 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7400 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7401 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7402 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7403 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7404 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7405 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7407 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7408 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7411 // fallthrough --> loopMBB
7412 BB->addSuccessor(loop1MBB);
7414 // The 4-byte load must be aligned, while a char or short may be
7415 // anywhere in the word. Hence all this nasty bookkeeping code.
7416 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7417 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7418 // xori shift, shift1, 24 [16]
7419 // rlwinm ptr, ptr1, 0, 0, 29
7420 // slw newval2, newval, shift
7421 // slw oldval2, oldval,shift
7422 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7423 // slw mask, mask2, shift
7424 // and newval3, newval2, mask
7425 // and oldval3, oldval2, mask
7427 // lwarx tmpDest, ptr
7428 // and tmp, tmpDest, mask
7429 // cmpw tmp, oldval3
7432 // andc tmp2, tmpDest, mask
7433 // or tmp4, tmp2, newval3
7438 // stwcx. tmpDest, ptr
7440 // srw dest, tmpDest, shift
7441 if (ptrA != ZeroReg) {
7442 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7443 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7444 .addReg(ptrA).addReg(ptrB);
7448 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7449 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7450 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7451 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7453 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7454 .addReg(Ptr1Reg).addImm(0).addImm(61);
7456 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7457 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7458 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7459 .addReg(newval).addReg(ShiftReg);
7460 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7461 .addReg(oldval).addReg(ShiftReg);
7463 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7465 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7466 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7467 .addReg(Mask3Reg).addImm(65535);
7469 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7470 .addReg(Mask2Reg).addReg(ShiftReg);
7471 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7472 .addReg(NewVal2Reg).addReg(MaskReg);
7473 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7474 .addReg(OldVal2Reg).addReg(MaskReg);
7477 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7478 .addReg(ZeroReg).addReg(PtrReg);
7479 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7480 .addReg(TmpDestReg).addReg(MaskReg);
7481 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7482 .addReg(TmpReg).addReg(OldVal3Reg);
7483 BuildMI(BB, dl, TII->get(PPC::BCC))
7484 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7485 BB->addSuccessor(loop2MBB);
7486 BB->addSuccessor(midMBB);
7489 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7490 .addReg(TmpDestReg).addReg(MaskReg);
7491 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7492 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7493 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7494 .addReg(ZeroReg).addReg(PtrReg);
7495 BuildMI(BB, dl, TII->get(PPC::BCC))
7496 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7497 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7498 BB->addSuccessor(loop1MBB);
7499 BB->addSuccessor(exitMBB);
7502 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7503 .addReg(ZeroReg).addReg(PtrReg);
7504 BB->addSuccessor(exitMBB);
7509 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7511 } else if (MI->getOpcode() == PPC::FADDrtz) {
7512 // This pseudo performs an FADD with rounding mode temporarily forced
7513 // to round-to-zero. We emit this via custom inserter since the FPSCR
7514 // is not modeled at the SelectionDAG level.
7515 unsigned Dest = MI->getOperand(0).getReg();
7516 unsigned Src1 = MI->getOperand(1).getReg();
7517 unsigned Src2 = MI->getOperand(2).getReg();
7518 DebugLoc dl = MI->getDebugLoc();
7520 MachineRegisterInfo &RegInfo = F->getRegInfo();
7521 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7523 // Save FPSCR value.
7524 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7526 // Set rounding mode to round-to-zero.
7527 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7528 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7530 // Perform addition.
7531 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7533 // Restore FPSCR value.
7534 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7535 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7536 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7537 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7538 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7539 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7540 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7541 PPC::ANDIo8 : PPC::ANDIo;
7542 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7543 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7545 MachineRegisterInfo &RegInfo = F->getRegInfo();
7546 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7547 &PPC::GPRCRegClass :
7548 &PPC::G8RCRegClass);
7550 DebugLoc dl = MI->getDebugLoc();
7551 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7552 .addReg(MI->getOperand(1).getReg()).addImm(1);
7553 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7554 MI->getOperand(0).getReg())
7555 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7557 llvm_unreachable("Unexpected instr type to insert");
7560 MI->eraseFromParent(); // The pseudo instruction is gone now.
7564 //===----------------------------------------------------------------------===//
7565 // Target Optimization Hooks
7566 //===----------------------------------------------------------------------===//
7568 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7569 DAGCombinerInfo &DCI,
7570 unsigned &RefinementSteps,
7571 bool &UseOneConstNR) const {
7572 EVT VT = Operand.getValueType();
7573 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7574 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7575 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7576 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7577 // Convergence is quadratic, so we essentially double the number of digits
7578 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7579 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7580 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7581 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7582 if (VT.getScalarType() == MVT::f64)
7584 UseOneConstNR = true;
7585 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7590 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7591 DAGCombinerInfo &DCI,
7592 unsigned &RefinementSteps) const {
7593 EVT VT = Operand.getValueType();
7594 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7595 (VT == MVT::f64 && Subtarget.hasFRE()) ||
7596 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7597 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7598 // Convergence is quadratic, so we essentially double the number of digits
7599 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7600 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7601 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7602 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7603 if (VT.getScalarType() == MVT::f64)
7605 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7610 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7611 // Note: This functionality is used only when unsafe-fp-math is enabled, and
7612 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7613 // enabled for division), this functionality is redundant with the default
7614 // combiner logic (once the division -> reciprocal/multiply transformation
7615 // has taken place). As a result, this matters more for older cores than for
7618 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7619 // reciprocal if there are two or more FDIVs (for embedded cores with only
7620 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7621 switch (Subtarget.getDarwinDirective()) {
7623 return NumUsers > 2;
7626 case PPC::DIR_E500mc:
7627 case PPC::DIR_E5500:
7628 return NumUsers > 1;
7632 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7633 unsigned Bytes, int Dist,
7634 SelectionDAG &DAG) {
7635 if (VT.getSizeInBits() / 8 != Bytes)
7638 SDValue BaseLoc = Base->getBasePtr();
7639 if (Loc.getOpcode() == ISD::FrameIndex) {
7640 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7642 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7643 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7644 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7645 int FS = MFI->getObjectSize(FI);
7646 int BFS = MFI->getObjectSize(BFI);
7647 if (FS != BFS || FS != (int)Bytes) return false;
7648 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7652 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7653 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7656 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7657 const GlobalValue *GV1 = nullptr;
7658 const GlobalValue *GV2 = nullptr;
7659 int64_t Offset1 = 0;
7660 int64_t Offset2 = 0;
7661 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7662 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7663 if (isGA1 && isGA2 && GV1 == GV2)
7664 return Offset1 == (Offset2 + Dist*Bytes);
7668 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7669 // not enforce equality of the chain operands.
7670 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7671 unsigned Bytes, int Dist,
7672 SelectionDAG &DAG) {
7673 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7674 EVT VT = LS->getMemoryVT();
7675 SDValue Loc = LS->getBasePtr();
7676 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7679 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7681 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7682 default: return false;
7683 case Intrinsic::ppc_altivec_lvx:
7684 case Intrinsic::ppc_altivec_lvxl:
7685 case Intrinsic::ppc_vsx_lxvw4x:
7688 case Intrinsic::ppc_vsx_lxvd2x:
7691 case Intrinsic::ppc_altivec_lvebx:
7694 case Intrinsic::ppc_altivec_lvehx:
7697 case Intrinsic::ppc_altivec_lvewx:
7702 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7705 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7707 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7708 default: return false;
7709 case Intrinsic::ppc_altivec_stvx:
7710 case Intrinsic::ppc_altivec_stvxl:
7711 case Intrinsic::ppc_vsx_stxvw4x:
7714 case Intrinsic::ppc_vsx_stxvd2x:
7717 case Intrinsic::ppc_altivec_stvebx:
7720 case Intrinsic::ppc_altivec_stvehx:
7723 case Intrinsic::ppc_altivec_stvewx:
7728 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7734 // Return true is there is a nearyby consecutive load to the one provided
7735 // (regardless of alignment). We search up and down the chain, looking though
7736 // token factors and other loads (but nothing else). As a result, a true result
7737 // indicates that it is safe to create a new consecutive load adjacent to the
7739 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7740 SDValue Chain = LD->getChain();
7741 EVT VT = LD->getMemoryVT();
7743 SmallSet<SDNode *, 16> LoadRoots;
7744 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7745 SmallSet<SDNode *, 16> Visited;
7747 // First, search up the chain, branching to follow all token-factor operands.
7748 // If we find a consecutive load, then we're done, otherwise, record all
7749 // nodes just above the top-level loads and token factors.
7750 while (!Queue.empty()) {
7751 SDNode *ChainNext = Queue.pop_back_val();
7752 if (!Visited.insert(ChainNext).second)
7755 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7756 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7759 if (!Visited.count(ChainLD->getChain().getNode()))
7760 Queue.push_back(ChainLD->getChain().getNode());
7761 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7762 for (const SDUse &O : ChainNext->ops())
7763 if (!Visited.count(O.getNode()))
7764 Queue.push_back(O.getNode());
7766 LoadRoots.insert(ChainNext);
7769 // Second, search down the chain, starting from the top-level nodes recorded
7770 // in the first phase. These top-level nodes are the nodes just above all
7771 // loads and token factors. Starting with their uses, recursively look though
7772 // all loads (just the chain uses) and token factors to find a consecutive
7777 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7778 IE = LoadRoots.end(); I != IE; ++I) {
7779 Queue.push_back(*I);
7781 while (!Queue.empty()) {
7782 SDNode *LoadRoot = Queue.pop_back_val();
7783 if (!Visited.insert(LoadRoot).second)
7786 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7787 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7790 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7791 UE = LoadRoot->use_end(); UI != UE; ++UI)
7792 if (((isa<MemSDNode>(*UI) &&
7793 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7794 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7795 Queue.push_back(*UI);
7802 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7803 DAGCombinerInfo &DCI) const {
7804 SelectionDAG &DAG = DCI.DAG;
7807 assert(Subtarget.useCRBits() &&
7808 "Expecting to be tracking CR bits");
7809 // If we're tracking CR bits, we need to be careful that we don't have:
7810 // trunc(binary-ops(zext(x), zext(y)))
7812 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7813 // such that we're unnecessarily moving things into GPRs when it would be
7814 // better to keep them in CR bits.
7816 // Note that trunc here can be an actual i1 trunc, or can be the effective
7817 // truncation that comes from a setcc or select_cc.
7818 if (N->getOpcode() == ISD::TRUNCATE &&
7819 N->getValueType(0) != MVT::i1)
7822 if (N->getOperand(0).getValueType() != MVT::i32 &&
7823 N->getOperand(0).getValueType() != MVT::i64)
7826 if (N->getOpcode() == ISD::SETCC ||
7827 N->getOpcode() == ISD::SELECT_CC) {
7828 // If we're looking at a comparison, then we need to make sure that the
7829 // high bits (all except for the first) don't matter the result.
7831 cast<CondCodeSDNode>(N->getOperand(
7832 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7833 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7835 if (ISD::isSignedIntSetCC(CC)) {
7836 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7837 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7839 } else if (ISD::isUnsignedIntSetCC(CC)) {
7840 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7841 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7842 !DAG.MaskedValueIsZero(N->getOperand(1),
7843 APInt::getHighBitsSet(OpBits, OpBits-1)))
7846 // This is neither a signed nor an unsigned comparison, just make sure
7847 // that the high bits are equal.
7848 APInt Op1Zero, Op1One;
7849 APInt Op2Zero, Op2One;
7850 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7851 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7853 // We don't really care about what is known about the first bit (if
7854 // anything), so clear it in all masks prior to comparing them.
7855 Op1Zero.clearBit(0); Op1One.clearBit(0);
7856 Op2Zero.clearBit(0); Op2One.clearBit(0);
7858 if (Op1Zero != Op2Zero || Op1One != Op2One)
7863 // We now know that the higher-order bits are irrelevant, we just need to
7864 // make sure that all of the intermediate operations are bit operations, and
7865 // all inputs are extensions.
7866 if (N->getOperand(0).getOpcode() != ISD::AND &&
7867 N->getOperand(0).getOpcode() != ISD::OR &&
7868 N->getOperand(0).getOpcode() != ISD::XOR &&
7869 N->getOperand(0).getOpcode() != ISD::SELECT &&
7870 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7871 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7872 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7873 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7874 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7877 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7878 N->getOperand(1).getOpcode() != ISD::AND &&
7879 N->getOperand(1).getOpcode() != ISD::OR &&
7880 N->getOperand(1).getOpcode() != ISD::XOR &&
7881 N->getOperand(1).getOpcode() != ISD::SELECT &&
7882 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7883 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7884 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7885 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7886 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7889 SmallVector<SDValue, 4> Inputs;
7890 SmallVector<SDValue, 8> BinOps, PromOps;
7891 SmallPtrSet<SDNode *, 16> Visited;
7893 for (unsigned i = 0; i < 2; ++i) {
7894 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7895 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7896 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7897 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7898 isa<ConstantSDNode>(N->getOperand(i)))
7899 Inputs.push_back(N->getOperand(i));
7901 BinOps.push_back(N->getOperand(i));
7903 if (N->getOpcode() == ISD::TRUNCATE)
7907 // Visit all inputs, collect all binary operations (and, or, xor and
7908 // select) that are all fed by extensions.
7909 while (!BinOps.empty()) {
7910 SDValue BinOp = BinOps.back();
7913 if (!Visited.insert(BinOp.getNode()).second)
7916 PromOps.push_back(BinOp);
7918 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7919 // The condition of the select is not promoted.
7920 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7922 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7925 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7926 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7927 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7928 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7929 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7930 Inputs.push_back(BinOp.getOperand(i));
7931 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7932 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7933 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7934 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7935 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7936 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7937 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7938 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7939 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7940 BinOps.push_back(BinOp.getOperand(i));
7942 // We have an input that is not an extension or another binary
7943 // operation; we'll abort this transformation.
7949 // Make sure that this is a self-contained cluster of operations (which
7950 // is not quite the same thing as saying that everything has only one
7952 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7953 if (isa<ConstantSDNode>(Inputs[i]))
7956 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7957 UE = Inputs[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) == Inputs[i])
7971 } else if (User->getOpcode() == ISD::SELECT_CC) {
7972 if (User->getOperand(0) == Inputs[i] ||
7973 User->getOperand(1) == Inputs[i])
7979 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7980 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7981 UE = PromOps[i].getNode()->use_end();
7984 if (User != N && !Visited.count(User))
7987 // Make sure that we're not going to promote the non-output-value
7988 // operand(s) or SELECT or SELECT_CC.
7989 // FIXME: Although we could sometimes handle this, and it does occur in
7990 // practice that one of the condition inputs to the select is also one of
7991 // the outputs, we currently can't deal with this.
7992 if (User->getOpcode() == ISD::SELECT) {
7993 if (User->getOperand(0) == PromOps[i])
7995 } else if (User->getOpcode() == ISD::SELECT_CC) {
7996 if (User->getOperand(0) == PromOps[i] ||
7997 User->getOperand(1) == PromOps[i])
8003 // Replace all inputs with the extension operand.
8004 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8005 // Constants may have users outside the cluster of to-be-promoted nodes,
8006 // and so we need to replace those as we do the promotions.
8007 if (isa<ConstantSDNode>(Inputs[i]))
8010 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
8013 // Replace all operations (these are all the same, but have a different
8014 // (i1) return type). DAG.getNode will validate that the types of
8015 // a binary operator match, so go through the list in reverse so that
8016 // we've likely promoted both operands first. Any intermediate truncations or
8017 // extensions disappear.
8018 while (!PromOps.empty()) {
8019 SDValue PromOp = PromOps.back();
8022 if (PromOp.getOpcode() == ISD::TRUNCATE ||
8023 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8024 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8025 PromOp.getOpcode() == ISD::ANY_EXTEND) {
8026 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8027 PromOp.getOperand(0).getValueType() != MVT::i1) {
8028 // The operand is not yet ready (see comment below).
8029 PromOps.insert(PromOps.begin(), PromOp);
8033 SDValue RepValue = PromOp.getOperand(0);
8034 if (isa<ConstantSDNode>(RepValue))
8035 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8037 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8042 switch (PromOp.getOpcode()) {
8043 default: C = 0; break;
8044 case ISD::SELECT: C = 1; break;
8045 case ISD::SELECT_CC: C = 2; break;
8048 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8049 PromOp.getOperand(C).getValueType() != MVT::i1) ||
8050 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8051 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8052 // The to-be-promoted operands of this node have not yet been
8053 // promoted (this should be rare because we're going through the
8054 // list backward, but if one of the operands has several users in
8055 // this cluster of to-be-promoted nodes, it is possible).
8056 PromOps.insert(PromOps.begin(), PromOp);
8060 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8061 PromOp.getNode()->op_end());
8063 // If there are any constant inputs, make sure they're replaced now.
8064 for (unsigned i = 0; i < 2; ++i)
8065 if (isa<ConstantSDNode>(Ops[C+i]))
8066 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8068 DAG.ReplaceAllUsesOfValueWith(PromOp,
8069 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8072 // Now we're left with the initial truncation itself.
8073 if (N->getOpcode() == ISD::TRUNCATE)
8074 return N->getOperand(0);
8076 // Otherwise, this is a comparison. The operands to be compared have just
8077 // changed type (to i1), but everything else is the same.
8078 return SDValue(N, 0);
8081 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8082 DAGCombinerInfo &DCI) const {
8083 SelectionDAG &DAG = DCI.DAG;
8086 // If we're tracking CR bits, we need to be careful that we don't have:
8087 // zext(binary-ops(trunc(x), trunc(y)))
8089 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8090 // such that we're unnecessarily moving things into CR bits that can more
8091 // efficiently stay in GPRs. Note that if we're not certain that the high
8092 // bits are set as required by the final extension, we still may need to do
8093 // some masking to get the proper behavior.
8095 // This same functionality is important on PPC64 when dealing with
8096 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8097 // the return values of functions. Because it is so similar, it is handled
8100 if (N->getValueType(0) != MVT::i32 &&
8101 N->getValueType(0) != MVT::i64)
8104 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8105 Subtarget.useCRBits()) ||
8106 (N->getOperand(0).getValueType() == MVT::i32 &&
8107 Subtarget.isPPC64())))
8110 if (N->getOperand(0).getOpcode() != ISD::AND &&
8111 N->getOperand(0).getOpcode() != ISD::OR &&
8112 N->getOperand(0).getOpcode() != ISD::XOR &&
8113 N->getOperand(0).getOpcode() != ISD::SELECT &&
8114 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8117 SmallVector<SDValue, 4> Inputs;
8118 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8119 SmallPtrSet<SDNode *, 16> Visited;
8121 // Visit all inputs, collect all binary operations (and, or, xor and
8122 // select) that are all fed by truncations.
8123 while (!BinOps.empty()) {
8124 SDValue BinOp = BinOps.back();
8127 if (!Visited.insert(BinOp.getNode()).second)
8130 PromOps.push_back(BinOp);
8132 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8133 // The condition of the select is not promoted.
8134 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8136 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8139 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8140 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8141 Inputs.push_back(BinOp.getOperand(i));
8142 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8143 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8144 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8145 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8146 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8147 BinOps.push_back(BinOp.getOperand(i));
8149 // We have an input that is not a truncation or another binary
8150 // operation; we'll abort this transformation.
8156 // The operands of a select that must be truncated when the select is
8157 // promoted because the operand is actually part of the to-be-promoted set.
8158 DenseMap<SDNode *, EVT> SelectTruncOp[2];
8160 // Make sure that this is a self-contained cluster of operations (which
8161 // is not quite the same thing as saying that everything has only one
8163 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8164 if (isa<ConstantSDNode>(Inputs[i]))
8167 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8168 UE = Inputs[i].getNode()->use_end();
8171 if (User != N && !Visited.count(User))
8174 // If we're going to promote the non-output-value operand(s) or SELECT or
8175 // SELECT_CC, record them for truncation.
8176 if (User->getOpcode() == ISD::SELECT) {
8177 if (User->getOperand(0) == Inputs[i])
8178 SelectTruncOp[0].insert(std::make_pair(User,
8179 User->getOperand(0).getValueType()));
8180 } else if (User->getOpcode() == ISD::SELECT_CC) {
8181 if (User->getOperand(0) == Inputs[i])
8182 SelectTruncOp[0].insert(std::make_pair(User,
8183 User->getOperand(0).getValueType()));
8184 if (User->getOperand(1) == Inputs[i])
8185 SelectTruncOp[1].insert(std::make_pair(User,
8186 User->getOperand(1).getValueType()));
8191 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8192 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8193 UE = PromOps[i].getNode()->use_end();
8196 if (User != N && !Visited.count(User))
8199 // If we're going to promote the non-output-value operand(s) or SELECT or
8200 // SELECT_CC, record them for truncation.
8201 if (User->getOpcode() == ISD::SELECT) {
8202 if (User->getOperand(0) == PromOps[i])
8203 SelectTruncOp[0].insert(std::make_pair(User,
8204 User->getOperand(0).getValueType()));
8205 } else if (User->getOpcode() == ISD::SELECT_CC) {
8206 if (User->getOperand(0) == PromOps[i])
8207 SelectTruncOp[0].insert(std::make_pair(User,
8208 User->getOperand(0).getValueType()));
8209 if (User->getOperand(1) == PromOps[i])
8210 SelectTruncOp[1].insert(std::make_pair(User,
8211 User->getOperand(1).getValueType()));
8216 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8217 bool ReallyNeedsExt = false;
8218 if (N->getOpcode() != ISD::ANY_EXTEND) {
8219 // If all of the inputs are not already sign/zero extended, then
8220 // we'll still need to do that at the end.
8221 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8222 if (isa<ConstantSDNode>(Inputs[i]))
8226 Inputs[i].getOperand(0).getValueSizeInBits();
8227 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8229 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8230 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8231 APInt::getHighBitsSet(OpBits,
8232 OpBits-PromBits))) ||
8233 (N->getOpcode() == ISD::SIGN_EXTEND &&
8234 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8235 (OpBits-(PromBits-1)))) {
8236 ReallyNeedsExt = true;
8242 // Replace all inputs, either with the truncation operand, or a
8243 // truncation or extension to the final output type.
8244 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8245 // Constant inputs need to be replaced with the to-be-promoted nodes that
8246 // use them because they might have users outside of the cluster of
8248 if (isa<ConstantSDNode>(Inputs[i]))
8251 SDValue InSrc = Inputs[i].getOperand(0);
8252 if (Inputs[i].getValueType() == N->getValueType(0))
8253 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8254 else if (N->getOpcode() == ISD::SIGN_EXTEND)
8255 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8256 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8257 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8258 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8259 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8261 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8262 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8265 // Replace all operations (these are all the same, but have a different
8266 // (promoted) return type). DAG.getNode will validate that the types of
8267 // a binary operator match, so go through the list in reverse so that
8268 // we've likely promoted both operands first.
8269 while (!PromOps.empty()) {
8270 SDValue PromOp = PromOps.back();
8274 switch (PromOp.getOpcode()) {
8275 default: C = 0; break;
8276 case ISD::SELECT: C = 1; break;
8277 case ISD::SELECT_CC: C = 2; break;
8280 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8281 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8282 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8283 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8284 // The to-be-promoted operands of this node have not yet been
8285 // promoted (this should be rare because we're going through the
8286 // list backward, but if one of the operands has several users in
8287 // this cluster of to-be-promoted nodes, it is possible).
8288 PromOps.insert(PromOps.begin(), PromOp);
8292 // For SELECT and SELECT_CC nodes, we do a similar check for any
8293 // to-be-promoted comparison inputs.
8294 if (PromOp.getOpcode() == ISD::SELECT ||
8295 PromOp.getOpcode() == ISD::SELECT_CC) {
8296 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8297 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8298 (SelectTruncOp[1].count(PromOp.getNode()) &&
8299 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8300 PromOps.insert(PromOps.begin(), PromOp);
8305 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8306 PromOp.getNode()->op_end());
8308 // If this node has constant inputs, then they'll need to be promoted here.
8309 for (unsigned i = 0; i < 2; ++i) {
8310 if (!isa<ConstantSDNode>(Ops[C+i]))
8312 if (Ops[C+i].getValueType() == N->getValueType(0))
8315 if (N->getOpcode() == ISD::SIGN_EXTEND)
8316 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8317 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8318 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8320 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8323 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8324 // truncate them again to the original value type.
8325 if (PromOp.getOpcode() == ISD::SELECT ||
8326 PromOp.getOpcode() == ISD::SELECT_CC) {
8327 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8328 if (SI0 != SelectTruncOp[0].end())
8329 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8330 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8331 if (SI1 != SelectTruncOp[1].end())
8332 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8335 DAG.ReplaceAllUsesOfValueWith(PromOp,
8336 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8339 // Now we're left with the initial extension itself.
8340 if (!ReallyNeedsExt)
8341 return N->getOperand(0);
8343 // To zero extend, just mask off everything except for the first bit (in the
8345 if (N->getOpcode() == ISD::ZERO_EXTEND)
8346 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8347 DAG.getConstant(APInt::getLowBitsSet(
8348 N->getValueSizeInBits(0), PromBits),
8349 N->getValueType(0)));
8351 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8352 "Invalid extension type");
8353 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8355 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8356 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
8357 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8358 N->getOperand(0), ShiftCst), ShiftCst);
8361 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
8362 DAGCombinerInfo &DCI) const {
8363 assert((N->getOpcode() == ISD::SINT_TO_FP ||
8364 N->getOpcode() == ISD::UINT_TO_FP) &&
8365 "Need an int -> FP conversion node here");
8367 if (!Subtarget.has64BitSupport())
8370 SelectionDAG &DAG = DCI.DAG;
8374 // Don't handle ppc_fp128 here or i1 conversions.
8375 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8377 if (Op.getOperand(0).getValueType() == MVT::i1)
8380 // For i32 intermediate values, unfortunately, the conversion functions
8381 // leave the upper 32 bits of the value are undefined. Within the set of
8382 // scalar instructions, we have no method for zero- or sign-extending the
8383 // value. Thus, we cannot handle i32 intermediate values here.
8384 if (Op.getOperand(0).getValueType() == MVT::i32)
8387 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8388 "UINT_TO_FP is supported only with FPCVT");
8390 // If we have FCFIDS, then use it when converting to single-precision.
8391 // Otherwise, convert to double-precision and then round.
8392 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
8393 (Op.getOpcode() == ISD::UINT_TO_FP ?
8394 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
8395 (Op.getOpcode() == ISD::UINT_TO_FP ?
8396 PPCISD::FCFIDU : PPCISD::FCFID);
8397 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
8398 MVT::f32 : MVT::f64;
8400 // If we're converting from a float, to an int, and back to a float again,
8401 // then we don't need the store/load pair at all.
8402 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
8403 Subtarget.hasFPCVT()) ||
8404 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
8405 SDValue Src = Op.getOperand(0).getOperand(0);
8406 if (Src.getValueType() == MVT::f32) {
8407 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8408 DCI.AddToWorklist(Src.getNode());
8412 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8415 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
8416 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
8418 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8419 FP = DAG.getNode(ISD::FP_ROUND, dl,
8420 MVT::f32, FP, DAG.getIntPtrConstant(0));
8421 DCI.AddToWorklist(FP.getNode());
8430 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8431 // builtins) into loads with swaps.
8432 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8433 DAGCombinerInfo &DCI) const {
8434 SelectionDAG &DAG = DCI.DAG;
8438 MachineMemOperand *MMO;
8440 switch (N->getOpcode()) {
8442 llvm_unreachable("Unexpected opcode for little endian VSX load");
8444 LoadSDNode *LD = cast<LoadSDNode>(N);
8445 Chain = LD->getChain();
8446 Base = LD->getBasePtr();
8447 MMO = LD->getMemOperand();
8448 // If the MMO suggests this isn't a load of a full vector, leave
8449 // things alone. For a built-in, we have to make the change for
8450 // correctness, so if there is a size problem that will be a bug.
8451 if (MMO->getSize() < 16)
8455 case ISD::INTRINSIC_W_CHAIN: {
8456 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8457 Chain = Intrin->getChain();
8458 Base = Intrin->getBasePtr();
8459 MMO = Intrin->getMemOperand();
8464 MVT VecTy = N->getValueType(0).getSimpleVT();
8465 SDValue LoadOps[] = { Chain, Base };
8466 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8467 DAG.getVTList(VecTy, MVT::Other),
8468 LoadOps, VecTy, MMO);
8469 DCI.AddToWorklist(Load.getNode());
8470 Chain = Load.getValue(1);
8471 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8472 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8473 DCI.AddToWorklist(Swap.getNode());
8477 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8478 // builtins) into stores with swaps.
8479 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8480 DAGCombinerInfo &DCI) const {
8481 SelectionDAG &DAG = DCI.DAG;
8486 MachineMemOperand *MMO;
8488 switch (N->getOpcode()) {
8490 llvm_unreachable("Unexpected opcode for little endian VSX store");
8492 StoreSDNode *ST = cast<StoreSDNode>(N);
8493 Chain = ST->getChain();
8494 Base = ST->getBasePtr();
8495 MMO = ST->getMemOperand();
8497 // If the MMO suggests this isn't a store of a full vector, leave
8498 // things alone. For a built-in, we have to make the change for
8499 // correctness, so if there is a size problem that will be a bug.
8500 if (MMO->getSize() < 16)
8504 case ISD::INTRINSIC_VOID: {
8505 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8506 Chain = Intrin->getChain();
8507 // Intrin->getBasePtr() oddly does not get what we want.
8508 Base = Intrin->getOperand(3);
8509 MMO = Intrin->getMemOperand();
8515 SDValue Src = N->getOperand(SrcOpnd);
8516 MVT VecTy = Src.getValueType().getSimpleVT();
8517 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8518 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8519 DCI.AddToWorklist(Swap.getNode());
8520 Chain = Swap.getValue(1);
8521 SDValue StoreOps[] = { Chain, Swap, Base };
8522 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8523 DAG.getVTList(MVT::Other),
8524 StoreOps, VecTy, MMO);
8525 DCI.AddToWorklist(Store.getNode());
8529 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8530 DAGCombinerInfo &DCI) const {
8531 const TargetMachine &TM = getTargetMachine();
8532 SelectionDAG &DAG = DCI.DAG;
8534 switch (N->getOpcode()) {
8537 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8538 if (C->isNullValue()) // 0 << V -> 0.
8539 return N->getOperand(0);
8543 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8544 if (C->isNullValue()) // 0 >>u V -> 0.
8545 return N->getOperand(0);
8549 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8550 if (C->isNullValue() || // 0 >>s V -> 0.
8551 C->isAllOnesValue()) // -1 >>s V -> -1.
8552 return N->getOperand(0);
8555 case ISD::SIGN_EXTEND:
8556 case ISD::ZERO_EXTEND:
8557 case ISD::ANY_EXTEND:
8558 return DAGCombineExtBoolTrunc(N, DCI);
8561 case ISD::SELECT_CC:
8562 return DAGCombineTruncBoolExt(N, DCI);
8563 case ISD::SINT_TO_FP:
8564 case ISD::UINT_TO_FP:
8565 return combineFPToIntToFP(N, DCI);
8567 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8568 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8569 !cast<StoreSDNode>(N)->isTruncatingStore() &&
8570 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8571 N->getOperand(1).getValueType() == MVT::i32 &&
8572 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8573 SDValue Val = N->getOperand(1).getOperand(0);
8574 if (Val.getValueType() == MVT::f32) {
8575 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8576 DCI.AddToWorklist(Val.getNode());
8578 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8579 DCI.AddToWorklist(Val.getNode());
8582 N->getOperand(0), Val, N->getOperand(2),
8583 DAG.getValueType(N->getOperand(1).getValueType())
8586 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8587 DAG.getVTList(MVT::Other), Ops,
8588 cast<StoreSDNode>(N)->getMemoryVT(),
8589 cast<StoreSDNode>(N)->getMemOperand());
8590 DCI.AddToWorklist(Val.getNode());
8594 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8595 if (cast<StoreSDNode>(N)->isUnindexed() &&
8596 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8597 N->getOperand(1).getNode()->hasOneUse() &&
8598 (N->getOperand(1).getValueType() == MVT::i32 ||
8599 N->getOperand(1).getValueType() == MVT::i16 ||
8600 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8601 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8602 N->getOperand(1).getValueType() == MVT::i64))) {
8603 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8604 // Do an any-extend to 32-bits if this is a half-word input.
8605 if (BSwapOp.getValueType() == MVT::i16)
8606 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8609 N->getOperand(0), BSwapOp, N->getOperand(2),
8610 DAG.getValueType(N->getOperand(1).getValueType())
8613 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8614 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8615 cast<StoreSDNode>(N)->getMemOperand());
8618 // For little endian, VSX stores require generating xxswapd/lxvd2x.
8619 EVT VT = N->getOperand(1).getValueType();
8620 if (VT.isSimple()) {
8621 MVT StoreVT = VT.getSimpleVT();
8622 if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8623 TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8624 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8625 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8626 return expandVSXStoreForLE(N, DCI);
8631 LoadSDNode *LD = cast<LoadSDNode>(N);
8632 EVT VT = LD->getValueType(0);
8634 // For little endian, VSX loads require generating lxvd2x/xxswapd.
8635 if (VT.isSimple()) {
8636 MVT LoadVT = VT.getSimpleVT();
8637 if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8638 TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8639 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8640 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8641 return expandVSXLoadForLE(N, DCI);
8644 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8645 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8646 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8647 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8648 // P8 and later hardware should just use LOAD.
8649 !TM.getSubtarget<PPCSubtarget>().hasP8Vector() &&
8650 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8651 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8652 LD->getAlignment() < ABIAlignment) {
8653 // This is a type-legal unaligned Altivec load.
8654 SDValue Chain = LD->getChain();
8655 SDValue Ptr = LD->getBasePtr();
8656 bool isLittleEndian = Subtarget.isLittleEndian();
8658 // This implements the loading of unaligned vectors as described in
8659 // the venerable Apple Velocity Engine overview. Specifically:
8660 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8661 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8663 // The general idea is to expand a sequence of one or more unaligned
8664 // loads into an alignment-based permutation-control instruction (lvsl
8665 // or lvsr), a series of regular vector loads (which always truncate
8666 // their input address to an aligned address), and a series of
8667 // permutations. The results of these permutations are the requested
8668 // loaded values. The trick is that the last "extra" load is not taken
8669 // from the address you might suspect (sizeof(vector) bytes after the
8670 // last requested load), but rather sizeof(vector) - 1 bytes after the
8671 // last requested vector. The point of this is to avoid a page fault if
8672 // the base address happened to be aligned. This works because if the
8673 // base address is aligned, then adding less than a full vector length
8674 // will cause the last vector in the sequence to be (re)loaded.
8675 // Otherwise, the next vector will be fetched as you might suspect was
8678 // We might be able to reuse the permutation generation from
8679 // a different base address offset from this one by an aligned amount.
8680 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8681 // optimization later.
8682 Intrinsic::ID Intr = (isLittleEndian ?
8683 Intrinsic::ppc_altivec_lvsr :
8684 Intrinsic::ppc_altivec_lvsl);
8685 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8687 // Create the new MMO for the new base load. It is like the original MMO,
8688 // but represents an area in memory almost twice the vector size centered
8689 // on the original address. If the address is unaligned, we might start
8690 // reading up to (sizeof(vector)-1) bytes below the address of the
8691 // original unaligned load.
8692 MachineFunction &MF = DAG.getMachineFunction();
8693 MachineMemOperand *BaseMMO =
8694 MF.getMachineMemOperand(LD->getMemOperand(),
8695 -LD->getMemoryVT().getStoreSize()+1,
8696 2*LD->getMemoryVT().getStoreSize()-1);
8698 // Create the new base load.
8699 SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8701 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8703 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8704 DAG.getVTList(MVT::v4i32, MVT::Other),
8705 BaseLoadOps, MVT::v4i32, BaseMMO);
8707 // Note that the value of IncOffset (which is provided to the next
8708 // load's pointer info offset value, and thus used to calculate the
8709 // alignment), and the value of IncValue (which is actually used to
8710 // increment the pointer value) are different! This is because we
8711 // require the next load to appear to be aligned, even though it
8712 // is actually offset from the base pointer by a lesser amount.
8713 int IncOffset = VT.getSizeInBits() / 8;
8714 int IncValue = IncOffset;
8716 // Walk (both up and down) the chain looking for another load at the real
8717 // (aligned) offset (the alignment of the other load does not matter in
8718 // this case). If found, then do not use the offset reduction trick, as
8719 // that will prevent the loads from being later combined (as they would
8720 // otherwise be duplicates).
8721 if (!findConsecutiveLoad(LD, DAG))
8724 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8725 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8727 MachineMemOperand *ExtraMMO =
8728 MF.getMachineMemOperand(LD->getMemOperand(),
8729 1, 2*LD->getMemoryVT().getStoreSize()-1);
8730 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8732 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8733 DAG.getVTList(MVT::v4i32, MVT::Other),
8734 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8736 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8737 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8739 // Because vperm has a big-endian bias, we must reverse the order
8740 // of the input vectors and complement the permute control vector
8741 // when generating little endian code. We have already handled the
8742 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8743 // and ExtraLoad here.
8746 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8747 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8749 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8750 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8752 if (VT != MVT::v4i32)
8753 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8755 // The output of the permutation is our loaded result, the TokenFactor is
8757 DCI.CombineTo(N, Perm, TF);
8758 return SDValue(N, 0);
8762 case ISD::INTRINSIC_WO_CHAIN: {
8763 bool isLittleEndian = Subtarget.isLittleEndian();
8764 Intrinsic::ID Intr = (isLittleEndian ?
8765 Intrinsic::ppc_altivec_lvsr :
8766 Intrinsic::ppc_altivec_lvsl);
8767 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8768 N->getOperand(1)->getOpcode() == ISD::ADD) {
8769 SDValue Add = N->getOperand(1);
8771 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8772 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8773 Add.getValueType().getScalarType().getSizeInBits()))) {
8774 SDNode *BasePtr = Add->getOperand(0).getNode();
8775 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8776 UE = BasePtr->use_end(); UI != UE; ++UI) {
8777 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8778 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8780 // We've found another LVSL/LVSR, and this address is an aligned
8781 // multiple of that one. The results will be the same, so use the
8782 // one we've just found instead.
8784 return SDValue(*UI, 0);
8792 case ISD::INTRINSIC_W_CHAIN: {
8793 // For little endian, VSX loads require generating lxvd2x/xxswapd.
8794 if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8795 TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8796 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8799 case Intrinsic::ppc_vsx_lxvw4x:
8800 case Intrinsic::ppc_vsx_lxvd2x:
8801 return expandVSXLoadForLE(N, DCI);
8806 case ISD::INTRINSIC_VOID: {
8807 // For little endian, VSX stores require generating xxswapd/stxvd2x.
8808 if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8809 TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8810 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8813 case Intrinsic::ppc_vsx_stxvw4x:
8814 case Intrinsic::ppc_vsx_stxvd2x:
8815 return expandVSXStoreForLE(N, DCI);
8821 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8822 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8823 N->getOperand(0).hasOneUse() &&
8824 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8825 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8826 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8827 N->getValueType(0) == MVT::i64))) {
8828 SDValue Load = N->getOperand(0);
8829 LoadSDNode *LD = cast<LoadSDNode>(Load);
8830 // Create the byte-swapping load.
8832 LD->getChain(), // Chain
8833 LD->getBasePtr(), // Ptr
8834 DAG.getValueType(N->getValueType(0)) // VT
8837 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8838 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8839 MVT::i64 : MVT::i32, MVT::Other),
8840 Ops, LD->getMemoryVT(), LD->getMemOperand());
8842 // If this is an i16 load, insert the truncate.
8843 SDValue ResVal = BSLoad;
8844 if (N->getValueType(0) == MVT::i16)
8845 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8847 // First, combine the bswap away. This makes the value produced by the
8849 DCI.CombineTo(N, ResVal);
8851 // Next, combine the load away, we give it a bogus result value but a real
8852 // chain result. The result value is dead because the bswap is dead.
8853 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8855 // Return N so it doesn't get rechecked!
8856 return SDValue(N, 0);
8860 case PPCISD::VCMP: {
8861 // If a VCMPo node already exists with exactly the same operands as this
8862 // node, use its result instead of this node (VCMPo computes both a CR6 and
8863 // a normal output).
8865 if (!N->getOperand(0).hasOneUse() &&
8866 !N->getOperand(1).hasOneUse() &&
8867 !N->getOperand(2).hasOneUse()) {
8869 // Scan all of the users of the LHS, looking for VCMPo's that match.
8870 SDNode *VCMPoNode = nullptr;
8872 SDNode *LHSN = N->getOperand(0).getNode();
8873 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8875 if (UI->getOpcode() == PPCISD::VCMPo &&
8876 UI->getOperand(1) == N->getOperand(1) &&
8877 UI->getOperand(2) == N->getOperand(2) &&
8878 UI->getOperand(0) == N->getOperand(0)) {
8883 // If there is no VCMPo node, or if the flag value has a single use, don't
8885 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8888 // Look at the (necessarily single) use of the flag value. If it has a
8889 // chain, this transformation is more complex. Note that multiple things
8890 // could use the value result, which we should ignore.
8891 SDNode *FlagUser = nullptr;
8892 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8893 FlagUser == nullptr; ++UI) {
8894 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8896 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8897 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8904 // If the user is a MFOCRF instruction, we know this is safe.
8905 // Otherwise we give up for right now.
8906 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8907 return SDValue(VCMPoNode, 0);
8912 SDValue Cond = N->getOperand(1);
8913 SDValue Target = N->getOperand(2);
8915 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8916 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8917 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8919 // We now need to make the intrinsic dead (it cannot be instruction
8921 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8922 assert(Cond.getNode()->hasOneUse() &&
8923 "Counter decrement has more than one use");
8925 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8926 N->getOperand(0), Target);
8931 // If this is a branch on an altivec predicate comparison, lower this so
8932 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8933 // lowering is done pre-legalize, because the legalizer lowers the predicate
8934 // compare down to code that is difficult to reassemble.
8935 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8936 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8938 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8939 // value. If so, pass-through the AND to get to the intrinsic.
8940 if (LHS.getOpcode() == ISD::AND &&
8941 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8942 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8943 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8944 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8945 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8947 LHS = LHS.getOperand(0);
8949 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8950 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8951 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8952 isa<ConstantSDNode>(RHS)) {
8953 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8954 "Counter decrement comparison is not EQ or NE");
8956 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8957 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8958 (CC == ISD::SETNE && !Val);
8960 // We now need to make the intrinsic dead (it cannot be instruction
8962 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8963 assert(LHS.getNode()->hasOneUse() &&
8964 "Counter decrement has more than one use");
8966 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8967 N->getOperand(0), N->getOperand(4));
8973 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8974 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8975 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8976 assert(isDot && "Can't compare against a vector result!");
8978 // If this is a comparison against something other than 0/1, then we know
8979 // that the condition is never/always true.
8980 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8981 if (Val != 0 && Val != 1) {
8982 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8983 return N->getOperand(0);
8984 // Always !=, turn it into an unconditional branch.
8985 return DAG.getNode(ISD::BR, dl, MVT::Other,
8986 N->getOperand(0), N->getOperand(4));
8989 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8991 // Create the PPCISD altivec 'dot' comparison node.
8993 LHS.getOperand(2), // LHS of compare
8994 LHS.getOperand(3), // RHS of compare
8995 DAG.getConstant(CompareOpc, MVT::i32)
8997 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8998 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9000 // Unpack the result based on how the target uses it.
9001 PPC::Predicate CompOpc;
9002 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
9003 default: // Can't happen, don't crash on invalid number though.
9004 case 0: // Branch on the value of the EQ bit of CR6.
9005 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
9007 case 1: // Branch on the inverted value of the EQ bit of CR6.
9008 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
9010 case 2: // Branch on the value of the LT bit of CR6.
9011 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
9013 case 3: // Branch on the inverted value of the LT bit of CR6.
9014 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
9018 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
9019 DAG.getConstant(CompOpc, MVT::i32),
9020 DAG.getRegister(PPC::CR6, MVT::i32),
9021 N->getOperand(4), CompNode.getValue(1));
9031 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9033 std::vector<SDNode *> *Created) const {
9034 // fold (sdiv X, pow2)
9035 EVT VT = N->getValueType(0);
9036 if (VT == MVT::i64 && !Subtarget.isPPC64())
9038 if ((VT != MVT::i32 && VT != MVT::i64) ||
9039 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9043 SDValue N0 = N->getOperand(0);
9045 bool IsNegPow2 = (-Divisor).isPowerOf2();
9046 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
9047 SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
9049 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9051 Created->push_back(Op.getNode());
9054 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9056 Created->push_back(Op.getNode());
9062 //===----------------------------------------------------------------------===//
9063 // Inline Assembly Support
9064 //===----------------------------------------------------------------------===//
9066 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9069 const SelectionDAG &DAG,
9070 unsigned Depth) const {
9071 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9072 switch (Op.getOpcode()) {
9074 case PPCISD::LBRX: {
9075 // lhbrx is known to have the top bits cleared out.
9076 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9077 KnownZero = 0xFFFF0000;
9080 case ISD::INTRINSIC_WO_CHAIN: {
9081 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9083 case Intrinsic::ppc_altivec_vcmpbfp_p:
9084 case Intrinsic::ppc_altivec_vcmpeqfp_p:
9085 case Intrinsic::ppc_altivec_vcmpequb_p:
9086 case Intrinsic::ppc_altivec_vcmpequh_p:
9087 case Intrinsic::ppc_altivec_vcmpequw_p:
9088 case Intrinsic::ppc_altivec_vcmpgefp_p:
9089 case Intrinsic::ppc_altivec_vcmpgtfp_p:
9090 case Intrinsic::ppc_altivec_vcmpgtsb_p:
9091 case Intrinsic::ppc_altivec_vcmpgtsh_p:
9092 case Intrinsic::ppc_altivec_vcmpgtsw_p:
9093 case Intrinsic::ppc_altivec_vcmpgtub_p:
9094 case Intrinsic::ppc_altivec_vcmpgtuh_p:
9095 case Intrinsic::ppc_altivec_vcmpgtuw_p:
9096 KnownZero = ~1U; // All bits but the low one are known to be zero.
9103 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9104 switch (Subtarget.getDarwinDirective()) {
9109 case PPC::DIR_PWR5X:
9111 case PPC::DIR_PWR6X:
9113 case PPC::DIR_PWR8: {
9117 const PPCInstrInfo *TII =
9118 static_cast<const PPCInstrInfo *>(getTargetMachine().getSubtargetImpl()->
9121 // For small loops (between 5 and 8 instructions), align to a 32-byte
9122 // boundary so that the entire loop fits in one instruction-cache line.
9123 uint64_t LoopSize = 0;
9124 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9125 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9126 LoopSize += TII->GetInstSizeInBytes(J);
9128 if (LoopSize > 16 && LoopSize <= 32)
9135 return TargetLowering::getPrefLoopAlignment(ML);
9138 /// getConstraintType - Given a constraint, return the type of
9139 /// constraint it is for this target.
9140 PPCTargetLowering::ConstraintType
9141 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9142 if (Constraint.size() == 1) {
9143 switch (Constraint[0]) {
9150 return C_RegisterClass;
9152 // FIXME: While Z does indicate a memory constraint, it specifically
9153 // indicates an r+r address (used in conjunction with the 'y' modifier
9154 // in the replacement string). Currently, we're forcing the base
9155 // register to be r0 in the asm printer (which is interpreted as zero)
9156 // and forming the complete address in the second register. This is
9160 } else if (Constraint == "wc") { // individual CR bits.
9161 return C_RegisterClass;
9162 } else if (Constraint == "wa" || Constraint == "wd" ||
9163 Constraint == "wf" || Constraint == "ws") {
9164 return C_RegisterClass; // VSX registers.
9166 return TargetLowering::getConstraintType(Constraint);
9169 /// Examine constraint type and operand type and determine a weight value.
9170 /// This object must already have been set up with the operand type
9171 /// and the current alternative constraint selected.
9172 TargetLowering::ConstraintWeight
9173 PPCTargetLowering::getSingleConstraintMatchWeight(
9174 AsmOperandInfo &info, const char *constraint) const {
9175 ConstraintWeight weight = CW_Invalid;
9176 Value *CallOperandVal = info.CallOperandVal;
9177 // If we don't have a value, we can't do a match,
9178 // but allow it at the lowest weight.
9179 if (!CallOperandVal)
9181 Type *type = CallOperandVal->getType();
9183 // Look at the constraint type.
9184 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9185 return CW_Register; // an individual CR bit.
9186 else if ((StringRef(constraint) == "wa" ||
9187 StringRef(constraint) == "wd" ||
9188 StringRef(constraint) == "wf") &&
9191 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9194 switch (*constraint) {
9196 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9199 if (type->isIntegerTy())
9200 weight = CW_Register;
9203 if (type->isFloatTy())
9204 weight = CW_Register;
9207 if (type->isDoubleTy())
9208 weight = CW_Register;
9211 if (type->isVectorTy())
9212 weight = CW_Register;
9215 weight = CW_Register;
9224 std::pair<unsigned, const TargetRegisterClass*>
9225 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9227 if (Constraint.size() == 1) {
9228 // GCC RS6000 Constraint Letters
9229 switch (Constraint[0]) {
9231 if (VT == MVT::i64 && Subtarget.isPPC64())
9232 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9233 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9235 if (VT == MVT::i64 && Subtarget.isPPC64())
9236 return std::make_pair(0U, &PPC::G8RCRegClass);
9237 return std::make_pair(0U, &PPC::GPRCRegClass);
9239 if (VT == MVT::f32 || VT == MVT::i32)
9240 return std::make_pair(0U, &PPC::F4RCRegClass);
9241 if (VT == MVT::f64 || VT == MVT::i64)
9242 return std::make_pair(0U, &PPC::F8RCRegClass);
9245 return std::make_pair(0U, &PPC::VRRCRegClass);
9247 return std::make_pair(0U, &PPC::CRRCRegClass);
9249 } else if (Constraint == "wc") { // an individual CR bit.
9250 return std::make_pair(0U, &PPC::CRBITRCRegClass);
9251 } else if (Constraint == "wa" || Constraint == "wd" ||
9252 Constraint == "wf") {
9253 return std::make_pair(0U, &PPC::VSRCRegClass);
9254 } else if (Constraint == "ws") {
9255 return std::make_pair(0U, &PPC::VSFRCRegClass);
9258 std::pair<unsigned, const TargetRegisterClass*> R =
9259 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9261 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9262 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9263 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9265 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9266 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9267 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9268 PPC::GPRCRegClass.contains(R.first)) {
9269 const TargetRegisterInfo *TRI =
9270 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
9271 return std::make_pair(TRI->getMatchingSuperReg(R.first,
9272 PPC::sub_32, &PPC::G8RCRegClass),
9273 &PPC::G8RCRegClass);
9276 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9277 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9279 R.second = &PPC::CRRCRegClass;
9286 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9287 /// vector. If it is invalid, don't add anything to Ops.
9288 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9289 std::string &Constraint,
9290 std::vector<SDValue>&Ops,
9291 SelectionDAG &DAG) const {
9294 // Only support length 1 constraints.
9295 if (Constraint.length() > 1) return;
9297 char Letter = Constraint[0];
9308 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9309 if (!CST) return; // Must be an immediate to match.
9310 int64_t Value = CST->getSExtValue();
9311 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9312 // numbers are printed as such.
9314 default: llvm_unreachable("Unknown constraint letter!");
9315 case 'I': // "I" is a signed 16-bit constant.
9316 if (isInt<16>(Value))
9317 Result = DAG.getTargetConstant(Value, TCVT);
9319 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
9320 if (isShiftedUInt<16, 16>(Value))
9321 Result = DAG.getTargetConstant(Value, TCVT);
9323 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
9324 if (isShiftedInt<16, 16>(Value))
9325 Result = DAG.getTargetConstant(Value, TCVT);
9327 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
9328 if (isUInt<16>(Value))
9329 Result = DAG.getTargetConstant(Value, TCVT);
9331 case 'M': // "M" is a constant that is greater than 31.
9333 Result = DAG.getTargetConstant(Value, TCVT);
9335 case 'N': // "N" is a positive constant that is an exact power of two.
9336 if (Value > 0 && isPowerOf2_64(Value))
9337 Result = DAG.getTargetConstant(Value, TCVT);
9339 case 'O': // "O" is the constant zero.
9341 Result = DAG.getTargetConstant(Value, TCVT);
9343 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
9344 if (isInt<16>(-Value))
9345 Result = DAG.getTargetConstant(Value, TCVT);
9352 if (Result.getNode()) {
9353 Ops.push_back(Result);
9357 // Handle standard constraint letters.
9358 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9361 // isLegalAddressingMode - Return true if the addressing mode represented
9362 // by AM is legal for this target, for a load/store of the specified type.
9363 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9365 // FIXME: PPC does not allow r+i addressing modes for vectors!
9367 // PPC allows a sign-extended 16-bit immediate field.
9368 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9371 // No global is ever allowed as a base.
9375 // PPC only support r+r,
9377 case 0: // "r+i" or just "i", depending on HasBaseReg.
9380 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
9382 // Otherwise we have r+r or r+i.
9385 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
9387 // Allow 2*r as r+r.
9390 // No other scales are supported.
9397 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9398 SelectionDAG &DAG) const {
9399 MachineFunction &MF = DAG.getMachineFunction();
9400 MachineFrameInfo *MFI = MF.getFrameInfo();
9401 MFI->setReturnAddressIsTaken(true);
9403 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9407 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9409 // Make sure the function does not optimize away the store of the RA to
9411 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9412 FuncInfo->setLRStoreRequired();
9413 bool isPPC64 = Subtarget.isPPC64();
9414 bool isDarwinABI = Subtarget.isDarwinABI();
9417 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9420 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9421 isPPC64? MVT::i64 : MVT::i32);
9422 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9423 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9425 MachinePointerInfo(), false, false, false, 0);
9428 // Just load the return address off the stack.
9429 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9430 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9431 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9434 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9435 SelectionDAG &DAG) const {
9437 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9439 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9440 bool isPPC64 = PtrVT == MVT::i64;
9442 MachineFunction &MF = DAG.getMachineFunction();
9443 MachineFrameInfo *MFI = MF.getFrameInfo();
9444 MFI->setFrameAddressIsTaken(true);
9446 // Naked functions never have a frame pointer, and so we use r1. For all
9447 // other functions, this decision must be delayed until during PEI.
9449 if (MF.getFunction()->getAttributes().hasAttribute(
9450 AttributeSet::FunctionIndex, Attribute::Naked))
9451 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9453 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9455 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9458 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9459 FrameAddr, MachinePointerInfo(), false, false,
9464 // FIXME? Maybe this could be a TableGen attribute on some registers and
9465 // this table could be generated automatically from RegInfo.
9466 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9468 bool isPPC64 = Subtarget.isPPC64();
9469 bool isDarwinABI = Subtarget.isDarwinABI();
9471 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9472 (!isPPC64 && VT != MVT::i32))
9473 report_fatal_error("Invalid register global variable type");
9475 bool is64Bit = isPPC64 && VT == MVT::i64;
9476 unsigned Reg = StringSwitch<unsigned>(RegName)
9477 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9478 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9479 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9480 (is64Bit ? PPC::X13 : PPC::R13))
9485 report_fatal_error("Invalid register name global variable");
9489 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9490 // The PowerPC target isn't yet aware of offsets.
9494 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9496 unsigned Intrinsic) const {
9498 switch (Intrinsic) {
9499 case Intrinsic::ppc_altivec_lvx:
9500 case Intrinsic::ppc_altivec_lvxl:
9501 case Intrinsic::ppc_altivec_lvebx:
9502 case Intrinsic::ppc_altivec_lvehx:
9503 case Intrinsic::ppc_altivec_lvewx:
9504 case Intrinsic::ppc_vsx_lxvd2x:
9505 case Intrinsic::ppc_vsx_lxvw4x: {
9507 switch (Intrinsic) {
9508 case Intrinsic::ppc_altivec_lvebx:
9511 case Intrinsic::ppc_altivec_lvehx:
9514 case Intrinsic::ppc_altivec_lvewx:
9517 case Intrinsic::ppc_vsx_lxvd2x:
9525 Info.opc = ISD::INTRINSIC_W_CHAIN;
9527 Info.ptrVal = I.getArgOperand(0);
9528 Info.offset = -VT.getStoreSize()+1;
9529 Info.size = 2*VT.getStoreSize()-1;
9532 Info.readMem = true;
9533 Info.writeMem = false;
9536 case Intrinsic::ppc_altivec_stvx:
9537 case Intrinsic::ppc_altivec_stvxl:
9538 case Intrinsic::ppc_altivec_stvebx:
9539 case Intrinsic::ppc_altivec_stvehx:
9540 case Intrinsic::ppc_altivec_stvewx:
9541 case Intrinsic::ppc_vsx_stxvd2x:
9542 case Intrinsic::ppc_vsx_stxvw4x: {
9544 switch (Intrinsic) {
9545 case Intrinsic::ppc_altivec_stvebx:
9548 case Intrinsic::ppc_altivec_stvehx:
9551 case Intrinsic::ppc_altivec_stvewx:
9554 case Intrinsic::ppc_vsx_stxvd2x:
9562 Info.opc = ISD::INTRINSIC_VOID;
9564 Info.ptrVal = I.getArgOperand(1);
9565 Info.offset = -VT.getStoreSize()+1;
9566 Info.size = 2*VT.getStoreSize()-1;
9569 Info.readMem = false;
9570 Info.writeMem = true;
9580 /// getOptimalMemOpType - Returns the target specific optimal type for load
9581 /// and store operations as a result of memset, memcpy, and memmove
9582 /// lowering. If DstAlign is zero that means it's safe to destination
9583 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9584 /// means there isn't a need to check it against alignment requirement,
9585 /// probably because the source does not need to be loaded. If 'IsMemset' is
9586 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9587 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9588 /// source is constant so it does not need to be loaded.
9589 /// It returns EVT::Other if the type should be determined using generic
9590 /// target-independent logic.
9591 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9592 unsigned DstAlign, unsigned SrcAlign,
9593 bool IsMemset, bool ZeroMemset,
9595 MachineFunction &MF) const {
9596 if (Subtarget.isPPC64()) {
9603 /// \brief Returns true if it is beneficial to convert a load of a constant
9604 /// to just the constant itself.
9605 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9607 assert(Ty->isIntegerTy());
9609 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9610 if (BitSize == 0 || BitSize > 64)
9615 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9616 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9618 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9619 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9620 return NumBits1 == 64 && NumBits2 == 32;
9623 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9624 if (!VT1.isInteger() || !VT2.isInteger())
9626 unsigned NumBits1 = VT1.getSizeInBits();
9627 unsigned NumBits2 = VT2.getSizeInBits();
9628 return NumBits1 == 64 && NumBits2 == 32;
9631 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9632 return isInt<16>(Imm) || isUInt<16>(Imm);
9635 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9636 return isInt<16>(Imm) || isUInt<16>(Imm);
9639 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9643 if (DisablePPCUnaligned)
9646 // PowerPC supports unaligned memory access for simple non-vector types.
9647 // Although accessing unaligned addresses is not as efficient as accessing
9648 // aligned addresses, it is generally more efficient than manual expansion,
9649 // and generally only traps for software emulation when crossing page
9655 if (VT.getSimpleVT().isVector()) {
9656 if (Subtarget.hasVSX()) {
9657 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9658 VT != MVT::v4f32 && VT != MVT::v4i32)
9665 if (VT == MVT::ppcf128)
9674 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9675 VT = VT.getScalarType();
9680 switch (VT.getSimpleVT().SimpleTy) {
9692 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9693 EVT VT , unsigned DefinedValues) const {
9694 if (VT == MVT::v2i64)
9697 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9700 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9701 if (DisableILPPref || Subtarget.enableMachineScheduler())
9702 return TargetLowering::getSchedulingPreference(N);
9707 // Create a fast isel object.
9709 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9710 const TargetLibraryInfo *LibInfo) const {
9711 return PPC::createFastISel(FuncInfo, LibInfo);