1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
42 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
43 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
45 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
46 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
48 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
49 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
51 // FIXME: Remove this once the bug has been fixed!
52 extern cl::opt<bool> ANDIGlueBug;
54 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
55 // If it isn't a Mach-O file then it's going to be a linux ELF
58 return new TargetLoweringObjectFileMachO();
60 return new PPC64LinuxTargetObjectFile();
63 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
64 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))),
65 PPCSubTarget(*TM.getSubtargetImpl()) {
66 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
70 // Use _setjmp/_longjmp instead of setjmp/longjmp.
71 setUseUnderscoreSetJmp(true);
72 setUseUnderscoreLongJmp(true);
74 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
75 // arguments are at least 4/8 bytes aligned.
76 bool isPPC64 = Subtarget->isPPC64();
77 setMinStackArgumentAlignment(isPPC64 ? 8:4);
79 // Set up the register classes.
80 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
81 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
82 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
84 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
85 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
86 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
88 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
90 // PowerPC has pre-inc load and store's.
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
93 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
94 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
95 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
100 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
102 if (Subtarget->useCRBits()) {
103 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
105 if (isPPC64 || Subtarget->hasFPCVT()) {
106 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
107 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
108 isPPC64 ? MVT::i64 : MVT::i32);
109 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
110 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
111 isPPC64 ? MVT::i64 : MVT::i32);
113 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
114 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
117 // PowerPC does not support direct load / store of condition registers
118 setOperationAction(ISD::LOAD, MVT::i1, Custom);
119 setOperationAction(ISD::STORE, MVT::i1, Custom);
121 // FIXME: Remove this once the ANDI glue bug is fixed:
123 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
125 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
126 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
127 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
128 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
129 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
130 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
132 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
135 // This is used in the ppcf128->int sequence. Note it has different semantics
136 // from FP_ROUND: that rounds to nearest, this rounds to zero.
137 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
139 // We do not currently implement these libm ops for PowerPC.
140 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
144 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
145 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
147 // PowerPC has no SREM/UREM instructions
148 setOperationAction(ISD::SREM, MVT::i32, Expand);
149 setOperationAction(ISD::UREM, MVT::i32, Expand);
150 setOperationAction(ISD::SREM, MVT::i64, Expand);
151 setOperationAction(ISD::UREM, MVT::i64, Expand);
153 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
154 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
155 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
156 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
157 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
158 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
160 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
161 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
163 // We don't support sin/cos/sqrt/fmod/pow
164 setOperationAction(ISD::FSIN , MVT::f64, Expand);
165 setOperationAction(ISD::FCOS , MVT::f64, Expand);
166 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
167 setOperationAction(ISD::FREM , MVT::f64, Expand);
168 setOperationAction(ISD::FPOW , MVT::f64, Expand);
169 setOperationAction(ISD::FMA , MVT::f64, Legal);
170 setOperationAction(ISD::FSIN , MVT::f32, Expand);
171 setOperationAction(ISD::FCOS , MVT::f32, Expand);
172 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
173 setOperationAction(ISD::FREM , MVT::f32, Expand);
174 setOperationAction(ISD::FPOW , MVT::f32, Expand);
175 setOperationAction(ISD::FMA , MVT::f32, Legal);
177 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
179 // If we're enabling GP optimizations, use hardware square root
180 if (!Subtarget->hasFSQRT() &&
181 !(TM.Options.UnsafeFPMath &&
182 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
183 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
185 if (!Subtarget->hasFSQRT() &&
186 !(TM.Options.UnsafeFPMath &&
187 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
188 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
190 if (Subtarget->hasFCPSGN()) {
191 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
192 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
194 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
195 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
198 if (Subtarget->hasFPRND()) {
199 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
200 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
201 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
202 setOperationAction(ISD::FROUND, MVT::f64, Legal);
204 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
205 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
206 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
207 setOperationAction(ISD::FROUND, MVT::f32, Legal);
210 // PowerPC does not have BSWAP, CTPOP or CTTZ
211 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
212 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
213 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
214 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
215 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
216 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
217 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
218 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
220 if (Subtarget->hasPOPCNTD()) {
221 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
222 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
224 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
225 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
228 // PowerPC does not have ROTR
229 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
230 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
232 if (!Subtarget->useCRBits()) {
233 // PowerPC does not have Select
234 setOperationAction(ISD::SELECT, MVT::i32, Expand);
235 setOperationAction(ISD::SELECT, MVT::i64, Expand);
236 setOperationAction(ISD::SELECT, MVT::f32, Expand);
237 setOperationAction(ISD::SELECT, MVT::f64, Expand);
240 // PowerPC wants to turn select_cc of FP into fsel when possible.
241 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
242 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
244 // PowerPC wants to optimize integer setcc a bit
245 if (!Subtarget->useCRBits())
246 setOperationAction(ISD::SETCC, MVT::i32, Custom);
248 // PowerPC does not have BRCOND which requires SetCC
249 if (!Subtarget->useCRBits())
250 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
252 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
254 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
255 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
257 // PowerPC does not have [U|S]INT_TO_FP
258 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
259 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
262 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
263 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
264 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
266 // We cannot sextinreg(i1). Expand to shifts.
267 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
269 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
270 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
271 // support continuation, user-level threading, and etc.. As a result, no
272 // other SjLj exception interfaces are implemented and please don't build
273 // your own exception handling based on them.
274 // LLVM/Clang supports zero-cost DWARF exception handling.
275 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
276 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
278 // We want to legalize GlobalAddress and ConstantPool nodes into the
279 // appropriate instructions to materialize the address.
280 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
281 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
282 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
283 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
284 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
285 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
286 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
287 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
288 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
289 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
292 setOperationAction(ISD::TRAP, MVT::Other, Legal);
294 // TRAMPOLINE is custom lowered.
295 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
296 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
298 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
299 setOperationAction(ISD::VASTART , MVT::Other, Custom);
301 if (Subtarget->isSVR4ABI()) {
303 // VAARG always uses double-word chunks, so promote anything smaller.
304 setOperationAction(ISD::VAARG, MVT::i1, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i8, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i16, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::i32, Promote);
311 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
312 setOperationAction(ISD::VAARG, MVT::Other, Expand);
314 // VAARG is custom lowered with the 32-bit SVR4 ABI.
315 setOperationAction(ISD::VAARG, MVT::Other, Custom);
316 setOperationAction(ISD::VAARG, MVT::i64, Custom);
319 setOperationAction(ISD::VAARG, MVT::Other, Expand);
321 if (Subtarget->isSVR4ABI() && !isPPC64)
322 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
323 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
325 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
327 // Use the default implementation.
328 setOperationAction(ISD::VAEND , MVT::Other, Expand);
329 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
330 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
331 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
332 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
334 // We want to custom lower some of our intrinsics.
335 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
337 // To handle counter-based loop conditions.
338 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
340 // Comparisons that require checking two conditions.
341 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
351 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
352 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
354 if (Subtarget->has64BitSupport()) {
355 // They also have instructions for converting between i64 and fp.
356 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
357 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
358 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
359 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
360 // This is just the low 32 bits of a (signed) fp->i64 conversion.
361 // We cannot do this with Promote because i64 is not a legal type.
362 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
364 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
365 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
367 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
368 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
371 // With the instructions enabled under FPCVT, we can do everything.
372 if (PPCSubTarget.hasFPCVT()) {
373 if (Subtarget->has64BitSupport()) {
374 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
375 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
376 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
377 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
380 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
381 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
382 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
383 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
386 if (Subtarget->use64BitRegs()) {
387 // 64-bit PowerPC implementations can support i64 types directly
388 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
389 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
390 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
391 // 64-bit PowerPC wants to expand i128 shifts itself.
392 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
393 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
394 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
396 // 32-bit PowerPC wants to expand i64 shifts itself.
397 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
398 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
399 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
402 if (Subtarget->hasAltivec()) {
403 // First set operation action for all vector types to expand. Then we
404 // will selectively turn on ones that can be effectively codegen'd.
405 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
406 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
407 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
409 // add/sub are legal for all supported vector VT's.
410 setOperationAction(ISD::ADD , VT, Legal);
411 setOperationAction(ISD::SUB , VT, Legal);
413 // We promote all shuffles to v16i8.
414 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
415 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
417 // We promote all non-typed operations to v4i32.
418 setOperationAction(ISD::AND , VT, Promote);
419 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
420 setOperationAction(ISD::OR , VT, Promote);
421 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
422 setOperationAction(ISD::XOR , VT, Promote);
423 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
424 setOperationAction(ISD::LOAD , VT, Promote);
425 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
426 setOperationAction(ISD::SELECT, VT, Promote);
427 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
428 setOperationAction(ISD::STORE, VT, Promote);
429 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
431 // No other operations are legal.
432 setOperationAction(ISD::MUL , VT, Expand);
433 setOperationAction(ISD::SDIV, VT, Expand);
434 setOperationAction(ISD::SREM, VT, Expand);
435 setOperationAction(ISD::UDIV, VT, Expand);
436 setOperationAction(ISD::UREM, VT, Expand);
437 setOperationAction(ISD::FDIV, VT, Expand);
438 setOperationAction(ISD::FREM, VT, Expand);
439 setOperationAction(ISD::FNEG, VT, Expand);
440 setOperationAction(ISD::FSQRT, VT, Expand);
441 setOperationAction(ISD::FLOG, VT, Expand);
442 setOperationAction(ISD::FLOG10, VT, Expand);
443 setOperationAction(ISD::FLOG2, VT, Expand);
444 setOperationAction(ISD::FEXP, VT, Expand);
445 setOperationAction(ISD::FEXP2, VT, Expand);
446 setOperationAction(ISD::FSIN, VT, Expand);
447 setOperationAction(ISD::FCOS, VT, Expand);
448 setOperationAction(ISD::FABS, VT, Expand);
449 setOperationAction(ISD::FPOWI, VT, Expand);
450 setOperationAction(ISD::FFLOOR, VT, Expand);
451 setOperationAction(ISD::FCEIL, VT, Expand);
452 setOperationAction(ISD::FTRUNC, VT, Expand);
453 setOperationAction(ISD::FRINT, VT, Expand);
454 setOperationAction(ISD::FNEARBYINT, VT, Expand);
455 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
456 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
457 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
458 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
459 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
460 setOperationAction(ISD::UDIVREM, VT, Expand);
461 setOperationAction(ISD::SDIVREM, VT, Expand);
462 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
463 setOperationAction(ISD::FPOW, VT, Expand);
464 setOperationAction(ISD::BSWAP, VT, Expand);
465 setOperationAction(ISD::CTPOP, VT, Expand);
466 setOperationAction(ISD::CTLZ, VT, Expand);
467 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
468 setOperationAction(ISD::CTTZ, VT, Expand);
469 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
470 setOperationAction(ISD::VSELECT, VT, Expand);
471 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
473 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
474 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
475 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
476 setTruncStoreAction(VT, InnerVT, Expand);
478 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
479 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
480 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
483 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
484 // with merges, splats, etc.
485 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
487 setOperationAction(ISD::AND , MVT::v4i32, Legal);
488 setOperationAction(ISD::OR , MVT::v4i32, Legal);
489 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
490 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
491 setOperationAction(ISD::SELECT, MVT::v4i32,
492 Subtarget->useCRBits() ? Legal : Expand);
493 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
494 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
495 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
496 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
497 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
498 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
499 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
500 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
501 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
503 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
504 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
505 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
506 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
508 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
509 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
511 if (TM.Options.UnsafeFPMath || Subtarget->hasVSX()) {
512 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
513 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
516 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
517 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
518 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
520 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
521 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
523 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
524 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
525 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
526 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
528 // Altivec does not contain unordered floating-point compare instructions
529 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
530 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
531 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
532 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
533 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
534 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
536 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
537 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
539 if (Subtarget->hasVSX()) {
540 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
541 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
543 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
544 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
545 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
546 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
547 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
549 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
551 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
552 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
554 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
555 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
558 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
559 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
560 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
561 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
563 // Share the Altivec comparison restrictions.
564 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
566 setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
567 setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
568 setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
569 setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
571 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
572 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
574 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
575 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
577 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
579 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
581 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
582 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
584 // VSX v2i64 only supports non-arithmetic operations.
585 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
586 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
588 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
589 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
590 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
592 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
594 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
595 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
596 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
597 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
599 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
601 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
602 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
603 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
604 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
606 // Vector operation legalization checks the result type of
607 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
608 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
609 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
610 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
611 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
613 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
617 if (Subtarget->has64BitSupport()) {
618 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
619 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
622 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
623 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
624 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
625 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
627 setBooleanContents(ZeroOrOneBooleanContent);
628 // Altivec instructions set fields to all zeros or all ones.
629 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
632 setStackPointerRegisterToSaveRestore(PPC::X1);
633 setExceptionPointerRegister(PPC::X3);
634 setExceptionSelectorRegister(PPC::X4);
636 setStackPointerRegisterToSaveRestore(PPC::R1);
637 setExceptionPointerRegister(PPC::R3);
638 setExceptionSelectorRegister(PPC::R4);
641 // We have target-specific dag combine patterns for the following nodes:
642 setTargetDAGCombine(ISD::SINT_TO_FP);
643 setTargetDAGCombine(ISD::LOAD);
644 setTargetDAGCombine(ISD::STORE);
645 setTargetDAGCombine(ISD::BR_CC);
646 if (Subtarget->useCRBits())
647 setTargetDAGCombine(ISD::BRCOND);
648 setTargetDAGCombine(ISD::BSWAP);
649 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
651 setTargetDAGCombine(ISD::SIGN_EXTEND);
652 setTargetDAGCombine(ISD::ZERO_EXTEND);
653 setTargetDAGCombine(ISD::ANY_EXTEND);
655 if (Subtarget->useCRBits()) {
656 setTargetDAGCombine(ISD::TRUNCATE);
657 setTargetDAGCombine(ISD::SETCC);
658 setTargetDAGCombine(ISD::SELECT_CC);
661 // Use reciprocal estimates.
662 if (TM.Options.UnsafeFPMath) {
663 setTargetDAGCombine(ISD::FDIV);
664 setTargetDAGCombine(ISD::FSQRT);
667 // Darwin long double math library functions have $LDBL128 appended.
668 if (Subtarget->isDarwin()) {
669 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
670 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
671 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
672 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
673 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
674 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
675 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
676 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
677 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
678 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
681 // With 32 condition bits, we don't need to sink (and duplicate) compares
682 // aggressively in CodeGenPrep.
683 if (Subtarget->useCRBits())
684 setHasMultipleConditionRegisters();
686 setMinFunctionAlignment(2);
687 if (PPCSubTarget.isDarwin())
688 setPrefFunctionAlignment(4);
690 if (isPPC64 && Subtarget->isJITCodeModel())
691 // Temporary workaround for the inability of PPC64 JIT to handle jump
693 setSupportJumpTables(false);
695 setInsertFencesForAtomic(true);
697 if (Subtarget->enableMachineScheduler())
698 setSchedulingPreference(Sched::Source);
700 setSchedulingPreference(Sched::Hybrid);
702 computeRegisterProperties();
704 // The Freescale cores does better with aggressive inlining of memcpy and
705 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
706 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
707 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
708 MaxStoresPerMemset = 32;
709 MaxStoresPerMemsetOptSize = 16;
710 MaxStoresPerMemcpy = 32;
711 MaxStoresPerMemcpyOptSize = 8;
712 MaxStoresPerMemmove = 32;
713 MaxStoresPerMemmoveOptSize = 8;
715 setPrefFunctionAlignment(4);
719 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
720 /// the desired ByVal argument alignment.
721 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
722 unsigned MaxMaxAlign) {
723 if (MaxAlign == MaxMaxAlign)
725 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
726 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
728 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
730 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
731 unsigned EltAlign = 0;
732 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
733 if (EltAlign > MaxAlign)
735 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
736 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
737 unsigned EltAlign = 0;
738 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
739 if (EltAlign > MaxAlign)
741 if (MaxAlign == MaxMaxAlign)
747 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
748 /// function arguments in the caller parameter area.
749 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
750 // Darwin passes everything on 4 byte boundary.
751 if (PPCSubTarget.isDarwin())
754 // 16byte and wider vectors are passed on 16byte boundary.
755 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
756 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
757 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
758 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
762 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
764 default: return nullptr;
765 case PPCISD::FSEL: return "PPCISD::FSEL";
766 case PPCISD::FCFID: return "PPCISD::FCFID";
767 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
768 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
769 case PPCISD::FRE: return "PPCISD::FRE";
770 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
771 case PPCISD::STFIWX: return "PPCISD::STFIWX";
772 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
773 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
774 case PPCISD::VPERM: return "PPCISD::VPERM";
775 case PPCISD::Hi: return "PPCISD::Hi";
776 case PPCISD::Lo: return "PPCISD::Lo";
777 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
778 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
779 case PPCISD::LOAD: return "PPCISD::LOAD";
780 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
781 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
782 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
783 case PPCISD::SRL: return "PPCISD::SRL";
784 case PPCISD::SRA: return "PPCISD::SRA";
785 case PPCISD::SHL: return "PPCISD::SHL";
786 case PPCISD::CALL: return "PPCISD::CALL";
787 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
788 case PPCISD::MTCTR: return "PPCISD::MTCTR";
789 case PPCISD::BCTRL: return "PPCISD::BCTRL";
790 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
791 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
792 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
793 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
794 case PPCISD::VCMP: return "PPCISD::VCMP";
795 case PPCISD::VCMPo: return "PPCISD::VCMPo";
796 case PPCISD::LBRX: return "PPCISD::LBRX";
797 case PPCISD::STBRX: return "PPCISD::STBRX";
798 case PPCISD::LARX: return "PPCISD::LARX";
799 case PPCISD::STCX: return "PPCISD::STCX";
800 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
801 case PPCISD::BDNZ: return "PPCISD::BDNZ";
802 case PPCISD::BDZ: return "PPCISD::BDZ";
803 case PPCISD::MFFS: return "PPCISD::MFFS";
804 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
805 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
806 case PPCISD::CR6SET: return "PPCISD::CR6SET";
807 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
808 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
809 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
810 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
811 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
812 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
813 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
814 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
815 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
816 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
817 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
818 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
819 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
820 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
821 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
822 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
823 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
824 case PPCISD::SC: return "PPCISD::SC";
828 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
830 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
831 return VT.changeVectorElementTypeToInteger();
834 //===----------------------------------------------------------------------===//
835 // Node matching predicates, for use by the tblgen matching code.
836 //===----------------------------------------------------------------------===//
838 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
839 static bool isFloatingPointZero(SDValue Op) {
840 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
841 return CFP->getValueAPF().isZero();
842 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
843 // Maybe this has already been legalized into the constant pool?
844 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
845 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
846 return CFP->getValueAPF().isZero();
851 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
852 /// true if Op is undef or if it matches the specified value.
853 static bool isConstantOrUndef(int Op, int Val) {
854 return Op < 0 || Op == Val;
857 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
858 /// VPKUHUM instruction.
859 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
861 for (unsigned i = 0; i != 16; ++i)
862 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
865 for (unsigned i = 0; i != 8; ++i)
866 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
867 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
873 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
874 /// VPKUWUM instruction.
875 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
877 for (unsigned i = 0; i != 16; i += 2)
878 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
879 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
882 for (unsigned i = 0; i != 8; i += 2)
883 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
884 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
885 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
886 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
892 /// isVMerge - Common function, used to match vmrg* shuffles.
894 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
895 unsigned LHSStart, unsigned RHSStart) {
896 if (N->getValueType(0) != MVT::v16i8)
898 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
899 "Unsupported merge size!");
901 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
902 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
903 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
904 LHSStart+j+i*UnitSize) ||
905 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
906 RHSStart+j+i*UnitSize))
912 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
913 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
914 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
917 return isVMerge(N, UnitSize, 8, 24);
918 return isVMerge(N, UnitSize, 8, 8);
921 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
922 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
923 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
926 return isVMerge(N, UnitSize, 0, 16);
927 return isVMerge(N, UnitSize, 0, 0);
931 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
932 /// amount, otherwise return -1.
933 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
934 if (N->getValueType(0) != MVT::v16i8)
937 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
939 // Find the first non-undef value in the shuffle mask.
941 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
944 if (i == 16) return -1; // all undef.
946 // Otherwise, check to see if the rest of the elements are consecutively
947 // numbered from this value.
948 unsigned ShiftAmt = SVOp->getMaskElt(i);
949 if (ShiftAmt < i) return -1;
953 // Check the rest of the elements to see if they are consecutive.
954 for (++i; i != 16; ++i)
955 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
958 // Check the rest of the elements to see if they are consecutive.
959 for (++i; i != 16; ++i)
960 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
966 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
967 /// specifies a splat of a single element that is suitable for input to
968 /// VSPLTB/VSPLTH/VSPLTW.
969 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
970 assert(N->getValueType(0) == MVT::v16i8 &&
971 (EltSize == 1 || EltSize == 2 || EltSize == 4));
973 // This is a splat operation if each element of the permute is the same, and
974 // if the value doesn't reference the second vector.
975 unsigned ElementBase = N->getMaskElt(0);
977 // FIXME: Handle UNDEF elements too!
978 if (ElementBase >= 16)
981 // Check that the indices are consecutive, in the case of a multi-byte element
982 // splatted with a v16i8 mask.
983 for (unsigned i = 1; i != EltSize; ++i)
984 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
987 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
988 if (N->getMaskElt(i) < 0) continue;
989 for (unsigned j = 0; j != EltSize; ++j)
990 if (N->getMaskElt(i+j) != N->getMaskElt(j))
996 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
998 bool PPC::isAllNegativeZeroVector(SDNode *N) {
999 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1001 APInt APVal, APUndef;
1005 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1006 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1007 return CFP->getValueAPF().isNegZero();
1012 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1013 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1014 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
1015 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1016 assert(isSplatShuffleMask(SVOp, EltSize));
1017 return SVOp->getMaskElt(0) / EltSize;
1020 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1021 /// by using a vspltis[bhw] instruction of the specified element size, return
1022 /// the constant being splatted. The ByteSize field indicates the number of
1023 /// bytes of each element [124] -> [bhw].
1024 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1025 SDValue OpVal(nullptr, 0);
1027 // If ByteSize of the splat is bigger than the element size of the
1028 // build_vector, then we have a case where we are checking for a splat where
1029 // multiple elements of the buildvector are folded together into a single
1030 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1031 unsigned EltSize = 16/N->getNumOperands();
1032 if (EltSize < ByteSize) {
1033 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1034 SDValue UniquedVals[4];
1035 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1037 // See if all of the elements in the buildvector agree across.
1038 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1039 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1040 // If the element isn't a constant, bail fully out.
1041 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1044 if (!UniquedVals[i&(Multiple-1)].getNode())
1045 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1046 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1047 return SDValue(); // no match.
1050 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1051 // either constant or undef values that are identical for each chunk. See
1052 // if these chunks can form into a larger vspltis*.
1054 // Check to see if all of the leading entries are either 0 or -1. If
1055 // neither, then this won't fit into the immediate field.
1056 bool LeadingZero = true;
1057 bool LeadingOnes = true;
1058 for (unsigned i = 0; i != Multiple-1; ++i) {
1059 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1061 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1062 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1064 // Finally, check the least significant entry.
1066 if (!UniquedVals[Multiple-1].getNode())
1067 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1068 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1070 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1073 if (!UniquedVals[Multiple-1].getNode())
1074 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1075 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1076 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1077 return DAG.getTargetConstant(Val, MVT::i32);
1083 // Check to see if this buildvec has a single non-undef value in its elements.
1084 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1085 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1086 if (!OpVal.getNode())
1087 OpVal = N->getOperand(i);
1088 else if (OpVal != N->getOperand(i))
1092 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1094 unsigned ValSizeInBytes = EltSize;
1096 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1097 Value = CN->getZExtValue();
1098 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1099 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1100 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1103 // If the splat value is larger than the element value, then we can never do
1104 // this splat. The only case that we could fit the replicated bits into our
1105 // immediate field for would be zero, and we prefer to use vxor for it.
1106 if (ValSizeInBytes < ByteSize) return SDValue();
1108 // If the element value is larger than the splat value, cut it in half and
1109 // check to see if the two halves are equal. Continue doing this until we
1110 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1111 while (ValSizeInBytes > ByteSize) {
1112 ValSizeInBytes >>= 1;
1114 // If the top half equals the bottom half, we're still ok.
1115 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1116 (Value & ((1 << (8*ValSizeInBytes))-1)))
1120 // Properly sign extend the value.
1121 int MaskVal = SignExtend32(Value, ByteSize * 8);
1123 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1124 if (MaskVal == 0) return SDValue();
1126 // Finally, if this value fits in a 5 bit sext field, return it
1127 if (SignExtend32<5>(MaskVal) == MaskVal)
1128 return DAG.getTargetConstant(MaskVal, MVT::i32);
1132 //===----------------------------------------------------------------------===//
1133 // Addressing Mode Selection
1134 //===----------------------------------------------------------------------===//
1136 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1137 /// or 64-bit immediate, and if the value can be accurately represented as a
1138 /// sign extension from a 16-bit value. If so, this returns true and the
1140 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1141 if (!isa<ConstantSDNode>(N))
1144 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1145 if (N->getValueType(0) == MVT::i32)
1146 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1148 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1150 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1151 return isIntS16Immediate(Op.getNode(), Imm);
1155 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1156 /// can be represented as an indexed [r+r] operation. Returns false if it
1157 /// can be more efficiently represented with [r+imm].
1158 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1160 SelectionDAG &DAG) const {
1162 if (N.getOpcode() == ISD::ADD) {
1163 if (isIntS16Immediate(N.getOperand(1), imm))
1164 return false; // r+i
1165 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1166 return false; // r+i
1168 Base = N.getOperand(0);
1169 Index = N.getOperand(1);
1171 } else if (N.getOpcode() == ISD::OR) {
1172 if (isIntS16Immediate(N.getOperand(1), imm))
1173 return false; // r+i can fold it if we can.
1175 // If this is an or of disjoint bitfields, we can codegen this as an add
1176 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1178 APInt LHSKnownZero, LHSKnownOne;
1179 APInt RHSKnownZero, RHSKnownOne;
1180 DAG.computeKnownBits(N.getOperand(0),
1181 LHSKnownZero, LHSKnownOne);
1183 if (LHSKnownZero.getBoolValue()) {
1184 DAG.computeKnownBits(N.getOperand(1),
1185 RHSKnownZero, RHSKnownOne);
1186 // If all of the bits are known zero on the LHS or RHS, the add won't
1188 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1189 Base = N.getOperand(0);
1190 Index = N.getOperand(1);
1199 // If we happen to be doing an i64 load or store into a stack slot that has
1200 // less than a 4-byte alignment, then the frame-index elimination may need to
1201 // use an indexed load or store instruction (because the offset may not be a
1202 // multiple of 4). The extra register needed to hold the offset comes from the
1203 // register scavenger, and it is possible that the scavenger will need to use
1204 // an emergency spill slot. As a result, we need to make sure that a spill slot
1205 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1207 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1208 // FIXME: This does not handle the LWA case.
1212 // NOTE: We'll exclude negative FIs here, which come from argument
1213 // lowering, because there are no known test cases triggering this problem
1214 // using packed structures (or similar). We can remove this exclusion if
1215 // we find such a test case. The reason why this is so test-case driven is
1216 // because this entire 'fixup' is only to prevent crashes (from the
1217 // register scavenger) on not-really-valid inputs. For example, if we have:
1219 // %b = bitcast i1* %a to i64*
1220 // store i64* a, i64 b
1221 // then the store should really be marked as 'align 1', but is not. If it
1222 // were marked as 'align 1' then the indexed form would have been
1223 // instruction-selected initially, and the problem this 'fixup' is preventing
1224 // won't happen regardless.
1228 MachineFunction &MF = DAG.getMachineFunction();
1229 MachineFrameInfo *MFI = MF.getFrameInfo();
1231 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1235 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1236 FuncInfo->setHasNonRISpills();
1239 /// Returns true if the address N can be represented by a base register plus
1240 /// a signed 16-bit displacement [r+imm], and if it is not better
1241 /// represented as reg+reg. If Aligned is true, only accept displacements
1242 /// suitable for STD and friends, i.e. multiples of 4.
1243 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1246 bool Aligned) const {
1247 // FIXME dl should come from parent load or store, not from address
1249 // If this can be more profitably realized as r+r, fail.
1250 if (SelectAddressRegReg(N, Disp, Base, DAG))
1253 if (N.getOpcode() == ISD::ADD) {
1255 if (isIntS16Immediate(N.getOperand(1), imm) &&
1256 (!Aligned || (imm & 3) == 0)) {
1257 Disp = DAG.getTargetConstant(imm, N.getValueType());
1258 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1259 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1260 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1262 Base = N.getOperand(0);
1264 return true; // [r+i]
1265 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1266 // Match LOAD (ADD (X, Lo(G))).
1267 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1268 && "Cannot handle constant offsets yet!");
1269 Disp = N.getOperand(1).getOperand(0); // The global address.
1270 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1271 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1272 Disp.getOpcode() == ISD::TargetConstantPool ||
1273 Disp.getOpcode() == ISD::TargetJumpTable);
1274 Base = N.getOperand(0);
1275 return true; // [&g+r]
1277 } else if (N.getOpcode() == ISD::OR) {
1279 if (isIntS16Immediate(N.getOperand(1), imm) &&
1280 (!Aligned || (imm & 3) == 0)) {
1281 // If this is an or of disjoint bitfields, we can codegen this as an add
1282 // (for better address arithmetic) if the LHS and RHS of the OR are
1283 // provably disjoint.
1284 APInt LHSKnownZero, LHSKnownOne;
1285 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1287 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1288 // If all of the bits are known zero on the LHS or RHS, the add won't
1290 Base = N.getOperand(0);
1291 Disp = DAG.getTargetConstant(imm, N.getValueType());
1295 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1296 // Loading from a constant address.
1298 // If this address fits entirely in a 16-bit sext immediate field, codegen
1301 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1302 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1303 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1304 CN->getValueType(0));
1308 // Handle 32-bit sext immediates with LIS + addr mode.
1309 if ((CN->getValueType(0) == MVT::i32 ||
1310 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1311 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1312 int Addr = (int)CN->getZExtValue();
1314 // Otherwise, break this down into an LIS + disp.
1315 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1317 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1318 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1319 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1324 Disp = DAG.getTargetConstant(0, getPointerTy());
1325 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1326 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1327 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1330 return true; // [r+0]
1333 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1334 /// represented as an indexed [r+r] operation.
1335 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1337 SelectionDAG &DAG) const {
1338 // Check to see if we can easily represent this as an [r+r] address. This
1339 // will fail if it thinks that the address is more profitably represented as
1340 // reg+imm, e.g. where imm = 0.
1341 if (SelectAddressRegReg(N, Base, Index, DAG))
1344 // If the operand is an addition, always emit this as [r+r], since this is
1345 // better (for code size, and execution, as the memop does the add for free)
1346 // than emitting an explicit add.
1347 if (N.getOpcode() == ISD::ADD) {
1348 Base = N.getOperand(0);
1349 Index = N.getOperand(1);
1353 // Otherwise, do it the hard way, using R0 as the base register.
1354 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1360 /// getPreIndexedAddressParts - returns true by value, base pointer and
1361 /// offset pointer and addressing mode by reference if the node's address
1362 /// can be legally represented as pre-indexed load / store address.
1363 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1365 ISD::MemIndexedMode &AM,
1366 SelectionDAG &DAG) const {
1367 if (DisablePPCPreinc) return false;
1373 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1374 Ptr = LD->getBasePtr();
1375 VT = LD->getMemoryVT();
1376 Alignment = LD->getAlignment();
1377 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1378 Ptr = ST->getBasePtr();
1379 VT = ST->getMemoryVT();
1380 Alignment = ST->getAlignment();
1385 // PowerPC doesn't have preinc load/store instructions for vectors.
1389 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1391 // Common code will reject creating a pre-inc form if the base pointer
1392 // is a frame index, or if N is a store and the base pointer is either
1393 // the same as or a predecessor of the value being stored. Check for
1394 // those situations here, and try with swapped Base/Offset instead.
1397 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1400 SDValue Val = cast<StoreSDNode>(N)->getValue();
1401 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1406 std::swap(Base, Offset);
1412 // LDU/STU can only handle immediates that are a multiple of 4.
1413 if (VT != MVT::i64) {
1414 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1417 // LDU/STU need an address with at least 4-byte alignment.
1421 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1425 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1426 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1427 // sext i32 to i64 when addr mode is r+i.
1428 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1429 LD->getExtensionType() == ISD::SEXTLOAD &&
1430 isa<ConstantSDNode>(Offset))
1438 //===----------------------------------------------------------------------===//
1439 // LowerOperation implementation
1440 //===----------------------------------------------------------------------===//
1442 /// GetLabelAccessInfo - Return true if we should reference labels using a
1443 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1444 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1445 unsigned &LoOpFlags,
1446 const GlobalValue *GV = nullptr) {
1447 HiOpFlags = PPCII::MO_HA;
1448 LoOpFlags = PPCII::MO_LO;
1450 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1451 // non-darwin platform. We don't support PIC on other platforms yet.
1452 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1453 TM.getSubtarget<PPCSubtarget>().isDarwin();
1455 HiOpFlags |= PPCII::MO_PIC_FLAG;
1456 LoOpFlags |= PPCII::MO_PIC_FLAG;
1459 // If this is a reference to a global value that requires a non-lazy-ptr, make
1460 // sure that instruction lowering adds it.
1461 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1462 HiOpFlags |= PPCII::MO_NLP_FLAG;
1463 LoOpFlags |= PPCII::MO_NLP_FLAG;
1465 if (GV->hasHiddenVisibility()) {
1466 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1467 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1474 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1475 SelectionDAG &DAG) {
1476 EVT PtrVT = HiPart.getValueType();
1477 SDValue Zero = DAG.getConstant(0, PtrVT);
1480 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1481 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1483 // With PIC, the first instruction is actually "GR+hi(&G)".
1485 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1486 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1488 // Generate non-pic code that has direct accesses to the constant pool.
1489 // The address of the global is just (hi(&g)+lo(&g)).
1490 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1493 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1494 SelectionDAG &DAG) const {
1495 EVT PtrVT = Op.getValueType();
1496 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1497 const Constant *C = CP->getConstVal();
1499 // 64-bit SVR4 ABI code is always position-independent.
1500 // The actual address of the GlobalValue is stored in the TOC.
1501 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1502 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1503 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1504 DAG.getRegister(PPC::X2, MVT::i64));
1507 unsigned MOHiFlag, MOLoFlag;
1508 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1510 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1512 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1513 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1516 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1517 EVT PtrVT = Op.getValueType();
1518 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1520 // 64-bit SVR4 ABI code is always position-independent.
1521 // The actual address of the GlobalValue is stored in the TOC.
1522 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1523 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1524 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1525 DAG.getRegister(PPC::X2, MVT::i64));
1528 unsigned MOHiFlag, MOLoFlag;
1529 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1530 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1531 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1532 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1535 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1536 SelectionDAG &DAG) const {
1537 EVT PtrVT = Op.getValueType();
1539 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1541 unsigned MOHiFlag, MOLoFlag;
1542 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1543 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1544 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1545 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1548 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1549 SelectionDAG &DAG) const {
1551 // FIXME: TLS addresses currently use medium model code sequences,
1552 // which is the most useful form. Eventually support for small and
1553 // large models could be added if users need it, at the cost of
1554 // additional complexity.
1555 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1557 const GlobalValue *GV = GA->getGlobal();
1558 EVT PtrVT = getPointerTy();
1559 bool is64bit = PPCSubTarget.isPPC64();
1561 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1563 if (Model == TLSModel::LocalExec) {
1564 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1565 PPCII::MO_TPREL_HA);
1566 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1567 PPCII::MO_TPREL_LO);
1568 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1569 is64bit ? MVT::i64 : MVT::i32);
1570 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1571 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1574 if (Model == TLSModel::InitialExec) {
1575 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1576 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1580 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1581 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1582 PtrVT, GOTReg, TGA);
1584 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1585 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1586 PtrVT, TGA, GOTPtr);
1587 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1590 if (Model == TLSModel::GeneralDynamic) {
1591 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1592 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1593 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1595 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1598 // We need a chain node, and don't have one handy. The underlying
1599 // call has no side effects, so using the function entry node
1601 SDValue Chain = DAG.getEntryNode();
1602 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1603 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1604 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1605 PtrVT, ParmReg, TGA);
1606 // The return value from GET_TLS_ADDR really is in X3 already, but
1607 // some hacks are needed here to tie everything together. The extra
1608 // copies dissolve during subsequent transforms.
1609 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1610 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1613 if (Model == TLSModel::LocalDynamic) {
1614 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1615 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1616 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1618 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1621 // We need a chain node, and don't have one handy. The underlying
1622 // call has no side effects, so using the function entry node
1624 SDValue Chain = DAG.getEntryNode();
1625 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1626 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1627 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1628 PtrVT, ParmReg, TGA);
1629 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1630 // some hacks are needed here to tie everything together. The extra
1631 // copies dissolve during subsequent transforms.
1632 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1633 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1634 Chain, ParmReg, TGA);
1635 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1638 llvm_unreachable("Unknown TLS model!");
1641 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1642 SelectionDAG &DAG) const {
1643 EVT PtrVT = Op.getValueType();
1644 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1646 const GlobalValue *GV = GSDN->getGlobal();
1648 // 64-bit SVR4 ABI code is always position-independent.
1649 // The actual address of the GlobalValue is stored in the TOC.
1650 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1651 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1652 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1653 DAG.getRegister(PPC::X2, MVT::i64));
1656 unsigned MOHiFlag, MOLoFlag;
1657 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1660 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1662 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1664 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1666 // If the global reference is actually to a non-lazy-pointer, we have to do an
1667 // extra load to get the address of the global.
1668 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1669 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1670 false, false, false, 0);
1674 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1675 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1678 if (Op.getValueType() == MVT::v2i64) {
1679 // When the operands themselves are v2i64 values, we need to do something
1680 // special because VSX has no underlying comparison operations for these.
1681 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1682 // Equality can be handled by casting to the legal type for Altivec
1683 // comparisons, everything else needs to be expanded.
1684 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1685 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1686 DAG.getSetCC(dl, MVT::v4i32,
1687 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1688 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1695 // We handle most of these in the usual way.
1699 // If we're comparing for equality to zero, expose the fact that this is
1700 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1701 // fold the new nodes.
1702 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1703 if (C->isNullValue() && CC == ISD::SETEQ) {
1704 EVT VT = Op.getOperand(0).getValueType();
1705 SDValue Zext = Op.getOperand(0);
1706 if (VT.bitsLT(MVT::i32)) {
1708 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1710 unsigned Log2b = Log2_32(VT.getSizeInBits());
1711 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1712 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1713 DAG.getConstant(Log2b, MVT::i32));
1714 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1716 // Leave comparisons against 0 and -1 alone for now, since they're usually
1717 // optimized. FIXME: revisit this when we can custom lower all setcc
1719 if (C->isAllOnesValue() || C->isNullValue())
1723 // If we have an integer seteq/setne, turn it into a compare against zero
1724 // by xor'ing the rhs with the lhs, which is faster than setting a
1725 // condition register, reading it back out, and masking the correct bit. The
1726 // normal approach here uses sub to do this instead of xor. Using xor exposes
1727 // the result to other bit-twiddling opportunities.
1728 EVT LHSVT = Op.getOperand(0).getValueType();
1729 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1730 EVT VT = Op.getValueType();
1731 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1733 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1738 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1739 const PPCSubtarget &Subtarget) const {
1740 SDNode *Node = Op.getNode();
1741 EVT VT = Node->getValueType(0);
1742 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1743 SDValue InChain = Node->getOperand(0);
1744 SDValue VAListPtr = Node->getOperand(1);
1745 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1748 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1751 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1752 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1754 InChain = GprIndex.getValue(1);
1756 if (VT == MVT::i64) {
1757 // Check if GprIndex is even
1758 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1759 DAG.getConstant(1, MVT::i32));
1760 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1761 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1762 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1763 DAG.getConstant(1, MVT::i32));
1764 // Align GprIndex to be even if it isn't
1765 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1769 // fpr index is 1 byte after gpr
1770 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1771 DAG.getConstant(1, MVT::i32));
1774 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1775 FprPtr, MachinePointerInfo(SV), MVT::i8,
1777 InChain = FprIndex.getValue(1);
1779 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1780 DAG.getConstant(8, MVT::i32));
1782 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1783 DAG.getConstant(4, MVT::i32));
1786 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1787 MachinePointerInfo(), false, false,
1789 InChain = OverflowArea.getValue(1);
1791 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1792 MachinePointerInfo(), false, false,
1794 InChain = RegSaveArea.getValue(1);
1796 // select overflow_area if index > 8
1797 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1798 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1800 // adjustment constant gpr_index * 4/8
1801 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1802 VT.isInteger() ? GprIndex : FprIndex,
1803 DAG.getConstant(VT.isInteger() ? 4 : 8,
1806 // OurReg = RegSaveArea + RegConstant
1807 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1810 // Floating types are 32 bytes into RegSaveArea
1811 if (VT.isFloatingPoint())
1812 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1813 DAG.getConstant(32, MVT::i32));
1815 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1816 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1817 VT.isInteger() ? GprIndex : FprIndex,
1818 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1821 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1822 VT.isInteger() ? VAListPtr : FprPtr,
1823 MachinePointerInfo(SV),
1824 MVT::i8, false, false, 0);
1826 // determine if we should load from reg_save_area or overflow_area
1827 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1829 // increase overflow_area by 4/8 if gpr/fpr > 8
1830 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1831 DAG.getConstant(VT.isInteger() ? 4 : 8,
1834 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1837 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1839 MachinePointerInfo(),
1840 MVT::i32, false, false, 0);
1842 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1843 false, false, false, 0);
1846 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1847 const PPCSubtarget &Subtarget) const {
1848 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1850 // We have to copy the entire va_list struct:
1851 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1852 return DAG.getMemcpy(Op.getOperand(0), Op,
1853 Op.getOperand(1), Op.getOperand(2),
1854 DAG.getConstant(12, MVT::i32), 8, false, true,
1855 MachinePointerInfo(), MachinePointerInfo());
1858 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1859 SelectionDAG &DAG) const {
1860 return Op.getOperand(0);
1863 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1864 SelectionDAG &DAG) const {
1865 SDValue Chain = Op.getOperand(0);
1866 SDValue Trmp = Op.getOperand(1); // trampoline
1867 SDValue FPtr = Op.getOperand(2); // nested function
1868 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1871 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1872 bool isPPC64 = (PtrVT == MVT::i64);
1874 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1877 TargetLowering::ArgListTy Args;
1878 TargetLowering::ArgListEntry Entry;
1880 Entry.Ty = IntPtrTy;
1881 Entry.Node = Trmp; Args.push_back(Entry);
1883 // TrampSize == (isPPC64 ? 48 : 40);
1884 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1885 isPPC64 ? MVT::i64 : MVT::i32);
1886 Args.push_back(Entry);
1888 Entry.Node = FPtr; Args.push_back(Entry);
1889 Entry.Node = Nest; Args.push_back(Entry);
1891 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1892 TargetLowering::CallLoweringInfo CLI(DAG);
1893 CLI.setDebugLoc(dl).setChain(Chain)
1894 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
1895 DAG.getExternalSymbol("__trampoline_setup", PtrVT), &Args, 0);
1897 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1898 return CallResult.second;
1901 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1902 const PPCSubtarget &Subtarget) const {
1903 MachineFunction &MF = DAG.getMachineFunction();
1904 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1908 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1909 // vastart just stores the address of the VarArgsFrameIndex slot into the
1910 // memory location argument.
1911 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1912 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1913 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1914 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1915 MachinePointerInfo(SV),
1919 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1920 // We suppose the given va_list is already allocated.
1923 // char gpr; /* index into the array of 8 GPRs
1924 // * stored in the register save area
1925 // * gpr=0 corresponds to r3,
1926 // * gpr=1 to r4, etc.
1928 // char fpr; /* index into the array of 8 FPRs
1929 // * stored in the register save area
1930 // * fpr=0 corresponds to f1,
1931 // * fpr=1 to f2, etc.
1933 // char *overflow_arg_area;
1934 // /* location on stack that holds
1935 // * the next overflow argument
1937 // char *reg_save_area;
1938 // /* where r3:r10 and f1:f8 (if saved)
1944 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1945 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1948 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1950 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1952 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1955 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1956 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1958 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1959 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1961 uint64_t FPROffset = 1;
1962 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1964 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1966 // Store first byte : number of int regs
1967 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1969 MachinePointerInfo(SV),
1970 MVT::i8, false, false, 0);
1971 uint64_t nextOffset = FPROffset;
1972 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1975 // Store second byte : number of float regs
1976 SDValue secondStore =
1977 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1978 MachinePointerInfo(SV, nextOffset), MVT::i8,
1980 nextOffset += StackOffset;
1981 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1983 // Store second word : arguments given on stack
1984 SDValue thirdStore =
1985 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1986 MachinePointerInfo(SV, nextOffset),
1988 nextOffset += FrameOffset;
1989 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1991 // Store third word : arguments given in registers
1992 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1993 MachinePointerInfo(SV, nextOffset),
1998 #include "PPCGenCallingConv.inc"
2000 // Function whose sole purpose is to kill compiler warnings
2001 // stemming from unused functions included from PPCGenCallingConv.inc.
2002 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2003 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2006 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2007 CCValAssign::LocInfo &LocInfo,
2008 ISD::ArgFlagsTy &ArgFlags,
2013 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2015 CCValAssign::LocInfo &LocInfo,
2016 ISD::ArgFlagsTy &ArgFlags,
2018 static const MCPhysReg ArgRegs[] = {
2019 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2020 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2022 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2024 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2026 // Skip one register if the first unallocated register has an even register
2027 // number and there are still argument registers available which have not been
2028 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2029 // need to skip a register if RegNum is odd.
2030 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2031 State.AllocateReg(ArgRegs[RegNum]);
2034 // Always return false here, as this function only makes sure that the first
2035 // unallocated register has an odd register number and does not actually
2036 // allocate a register for the current argument.
2040 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2042 CCValAssign::LocInfo &LocInfo,
2043 ISD::ArgFlagsTy &ArgFlags,
2045 static const MCPhysReg ArgRegs[] = {
2046 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2050 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2052 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2054 // If there is only one Floating-point register left we need to put both f64
2055 // values of a split ppc_fp128 value on the stack.
2056 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2057 State.AllocateReg(ArgRegs[RegNum]);
2060 // Always return false here, as this function only makes sure that the two f64
2061 // values a ppc_fp128 value is split into are both passed in registers or both
2062 // passed on the stack and does not actually allocate a register for the
2063 // current argument.
2067 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2069 static const MCPhysReg *GetFPR() {
2070 static const MCPhysReg FPR[] = {
2071 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2072 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2078 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2080 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2081 unsigned PtrByteSize) {
2082 unsigned ArgSize = ArgVT.getStoreSize();
2083 if (Flags.isByVal())
2084 ArgSize = Flags.getByValSize();
2085 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2091 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2092 CallingConv::ID CallConv, bool isVarArg,
2093 const SmallVectorImpl<ISD::InputArg>
2095 SDLoc dl, SelectionDAG &DAG,
2096 SmallVectorImpl<SDValue> &InVals)
2098 if (PPCSubTarget.isSVR4ABI()) {
2099 if (PPCSubTarget.isPPC64())
2100 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2103 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2106 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2112 PPCTargetLowering::LowerFormalArguments_32SVR4(
2114 CallingConv::ID CallConv, bool isVarArg,
2115 const SmallVectorImpl<ISD::InputArg>
2117 SDLoc dl, SelectionDAG &DAG,
2118 SmallVectorImpl<SDValue> &InVals) const {
2120 // 32-bit SVR4 ABI Stack Frame Layout:
2121 // +-----------------------------------+
2122 // +--> | Back chain |
2123 // | +-----------------------------------+
2124 // | | Floating-point register save area |
2125 // | +-----------------------------------+
2126 // | | General register save area |
2127 // | +-----------------------------------+
2128 // | | CR save word |
2129 // | +-----------------------------------+
2130 // | | VRSAVE save word |
2131 // | +-----------------------------------+
2132 // | | Alignment padding |
2133 // | +-----------------------------------+
2134 // | | Vector register save area |
2135 // | +-----------------------------------+
2136 // | | Local variable space |
2137 // | +-----------------------------------+
2138 // | | Parameter list area |
2139 // | +-----------------------------------+
2140 // | | LR save word |
2141 // | +-----------------------------------+
2142 // SP--> +--- | Back chain |
2143 // +-----------------------------------+
2146 // System V Application Binary Interface PowerPC Processor Supplement
2147 // AltiVec Technology Programming Interface Manual
2149 MachineFunction &MF = DAG.getMachineFunction();
2150 MachineFrameInfo *MFI = MF.getFrameInfo();
2151 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2153 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2154 // Potential tail calls could cause overwriting of argument stack slots.
2155 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2156 (CallConv == CallingConv::Fast));
2157 unsigned PtrByteSize = 4;
2159 // Assign locations to all of the incoming arguments.
2160 SmallVector<CCValAssign, 16> ArgLocs;
2161 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2162 getTargetMachine(), ArgLocs, *DAG.getContext());
2164 // Reserve space for the linkage area on the stack.
2165 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2167 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2169 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2170 CCValAssign &VA = ArgLocs[i];
2172 // Arguments stored in registers.
2173 if (VA.isRegLoc()) {
2174 const TargetRegisterClass *RC;
2175 EVT ValVT = VA.getValVT();
2177 switch (ValVT.getSimpleVT().SimpleTy) {
2179 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2182 RC = &PPC::GPRCRegClass;
2185 RC = &PPC::F4RCRegClass;
2188 if (PPCSubTarget.hasVSX())
2189 RC = &PPC::VSFRCRegClass;
2191 RC = &PPC::F8RCRegClass;
2197 RC = &PPC::VRRCRegClass;
2201 RC = &PPC::VSHRCRegClass;
2205 // Transform the arguments stored in physical registers into virtual ones.
2206 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2207 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2208 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2210 if (ValVT == MVT::i1)
2211 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2213 InVals.push_back(ArgValue);
2215 // Argument stored in memory.
2216 assert(VA.isMemLoc());
2218 unsigned ArgSize = VA.getLocVT().getStoreSize();
2219 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2222 // Create load nodes to retrieve arguments from the stack.
2223 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2224 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2225 MachinePointerInfo(),
2226 false, false, false, 0));
2230 // Assign locations to all of the incoming aggregate by value arguments.
2231 // Aggregates passed by value are stored in the local variable space of the
2232 // caller's stack frame, right above the parameter list area.
2233 SmallVector<CCValAssign, 16> ByValArgLocs;
2234 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2235 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2237 // Reserve stack space for the allocations in CCInfo.
2238 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2240 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2242 // Area that is at least reserved in the caller of this function.
2243 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2245 // Set the size that is at least reserved in caller of this function. Tail
2246 // call optimized function's reserved stack space needs to be aligned so that
2247 // taking the difference between two stack areas will result in an aligned
2249 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2252 std::max(MinReservedArea,
2253 PPCFrameLowering::getMinCallFrameSize(false, false));
2255 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2256 getStackAlignment();
2257 unsigned AlignMask = TargetAlign-1;
2258 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2260 FI->setMinReservedArea(MinReservedArea);
2262 SmallVector<SDValue, 8> MemOps;
2264 // If the function takes variable number of arguments, make a frame index for
2265 // the start of the first vararg value... for expansion of llvm.va_start.
2267 static const MCPhysReg GPArgRegs[] = {
2268 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2269 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2271 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2273 static const MCPhysReg FPArgRegs[] = {
2274 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2277 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2279 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2281 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2284 // Make room for NumGPArgRegs and NumFPArgRegs.
2285 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2286 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2288 FuncInfo->setVarArgsStackOffset(
2289 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2290 CCInfo.getNextStackOffset(), true));
2292 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2293 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2295 // The fixed integer arguments of a variadic function are stored to the
2296 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2297 // the result of va_next.
2298 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2299 // Get an existing live-in vreg, or add a new one.
2300 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2302 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2304 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2305 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2306 MachinePointerInfo(), false, false, 0);
2307 MemOps.push_back(Store);
2308 // Increment the address by four for the next argument to store
2309 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2310 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2313 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2315 // The double arguments are stored to the VarArgsFrameIndex
2317 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2318 // Get an existing live-in vreg, or add a new one.
2319 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2321 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2323 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2324 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2325 MachinePointerInfo(), false, false, 0);
2326 MemOps.push_back(Store);
2327 // Increment the address by eight for the next argument to store
2328 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2330 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2334 if (!MemOps.empty())
2335 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2340 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2341 // value to MVT::i64 and then truncate to the correct register size.
2343 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2344 SelectionDAG &DAG, SDValue ArgVal,
2347 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2348 DAG.getValueType(ObjectVT));
2349 else if (Flags.isZExt())
2350 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2351 DAG.getValueType(ObjectVT));
2353 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2356 // Set the size that is at least reserved in caller of this function. Tail
2357 // call optimized functions' reserved stack space needs to be aligned so that
2358 // taking the difference between two stack areas will result in an aligned
2361 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2362 unsigned nAltivecParamsAtEnd,
2363 unsigned MinReservedArea,
2364 bool isPPC64) const {
2365 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2366 // Add the Altivec parameters at the end, if needed.
2367 if (nAltivecParamsAtEnd) {
2368 MinReservedArea = ((MinReservedArea+15)/16)*16;
2369 MinReservedArea += 16*nAltivecParamsAtEnd;
2372 std::max(MinReservedArea,
2373 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2374 unsigned TargetAlign
2375 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2376 getStackAlignment();
2377 unsigned AlignMask = TargetAlign-1;
2378 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2379 FI->setMinReservedArea(MinReservedArea);
2383 PPCTargetLowering::LowerFormalArguments_64SVR4(
2385 CallingConv::ID CallConv, bool isVarArg,
2386 const SmallVectorImpl<ISD::InputArg>
2388 SDLoc dl, SelectionDAG &DAG,
2389 SmallVectorImpl<SDValue> &InVals) const {
2390 // TODO: add description of PPC stack frame format, or at least some docs.
2392 MachineFunction &MF = DAG.getMachineFunction();
2393 MachineFrameInfo *MFI = MF.getFrameInfo();
2394 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2396 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2397 // Potential tail calls could cause overwriting of argument stack slots.
2398 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2399 (CallConv == CallingConv::Fast));
2400 unsigned PtrByteSize = 8;
2402 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2403 // Area that is at least reserved in caller of this function.
2404 unsigned MinReservedArea = ArgOffset;
2406 static const MCPhysReg GPR[] = {
2407 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2408 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2411 static const MCPhysReg *FPR = GetFPR();
2413 static const MCPhysReg VR[] = {
2414 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2415 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2417 static const MCPhysReg VSRH[] = {
2418 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2419 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2422 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2423 const unsigned Num_FPR_Regs = 13;
2424 const unsigned Num_VR_Regs = array_lengthof(VR);
2426 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2428 // Add DAG nodes to load the arguments or copy them out of registers. On
2429 // entry to a function on PPC, the arguments start after the linkage area,
2430 // although the first ones are often in registers.
2432 SmallVector<SDValue, 8> MemOps;
2433 unsigned nAltivecParamsAtEnd = 0;
2434 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2435 unsigned CurArgIdx = 0;
2436 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2438 bool needsLoad = false;
2439 EVT ObjectVT = Ins[ArgNo].VT;
2440 unsigned ObjSize = ObjectVT.getStoreSize();
2441 unsigned ArgSize = ObjSize;
2442 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2443 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2444 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2446 unsigned CurArgOffset = ArgOffset;
2448 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2449 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2450 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8 ||
2451 ObjectVT==MVT::v2f64 || ObjectVT==MVT::v2i64) {
2453 MinReservedArea = ((MinReservedArea+15)/16)*16;
2454 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2458 nAltivecParamsAtEnd++;
2460 // Calculate min reserved area.
2461 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2465 // FIXME the codegen can be much improved in some cases.
2466 // We do not have to keep everything in memory.
2467 if (Flags.isByVal()) {
2468 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2469 ObjSize = Flags.getByValSize();
2470 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2471 // Empty aggregate parameters do not take up registers. Examples:
2475 // etc. However, we have to provide a place-holder in InVals, so
2476 // pretend we have an 8-byte item at the current address for that
2479 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2480 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2481 InVals.push_back(FIN);
2485 unsigned BVAlign = Flags.getByValAlign();
2487 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2488 CurArgOffset = ArgOffset;
2491 // All aggregates smaller than 8 bytes must be passed right-justified.
2492 if (ObjSize < PtrByteSize)
2493 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2494 // The value of the object is its address.
2495 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2496 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2497 InVals.push_back(FIN);
2500 if (GPR_idx != Num_GPR_Regs) {
2501 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2502 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2505 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2506 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2507 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2508 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2509 MachinePointerInfo(FuncArg),
2510 ObjType, false, false, 0);
2512 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2513 // store the whole register as-is to the parameter save area
2514 // slot. The address of the parameter was already calculated
2515 // above (InVals.push_back(FIN)) to be the right-justified
2516 // offset within the slot. For this store, we need a new
2517 // frame index that points at the beginning of the slot.
2518 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2519 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2520 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2521 MachinePointerInfo(FuncArg),
2525 MemOps.push_back(Store);
2528 // Whether we copied from a register or not, advance the offset
2529 // into the parameter save area by a full doubleword.
2530 ArgOffset += PtrByteSize;
2534 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2535 // Store whatever pieces of the object are in registers
2536 // to memory. ArgOffset will be the address of the beginning
2538 if (GPR_idx != Num_GPR_Regs) {
2540 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2541 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2542 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2543 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2544 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2545 MachinePointerInfo(FuncArg, j),
2547 MemOps.push_back(Store);
2549 ArgOffset += PtrByteSize;
2551 ArgOffset += ArgSize - j;
2558 switch (ObjectVT.getSimpleVT().SimpleTy) {
2559 default: llvm_unreachable("Unhandled argument type!");
2563 if (GPR_idx != Num_GPR_Regs) {
2564 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2565 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2567 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2568 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2569 // value to MVT::i64 and then truncate to the correct register size.
2570 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2575 ArgSize = PtrByteSize;
2582 // Every 8 bytes of argument space consumes one of the GPRs available for
2583 // argument passing.
2584 if (GPR_idx != Num_GPR_Regs) {
2587 if (FPR_idx != Num_FPR_Regs) {
2590 if (ObjectVT == MVT::f32)
2591 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2593 VReg = MF.addLiveIn(FPR[FPR_idx], PPCSubTarget.hasVSX() ?
2594 &PPC::VSFRCRegClass :
2595 &PPC::F8RCRegClass);
2597 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2601 ArgSize = PtrByteSize;
2612 // Note that vector arguments in registers don't reserve stack space,
2613 // except in varargs functions.
2614 if (VR_idx != Num_VR_Regs) {
2615 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2616 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2617 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2618 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2620 while ((ArgOffset % 16) != 0) {
2621 ArgOffset += PtrByteSize;
2622 if (GPR_idx != Num_GPR_Regs)
2626 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2630 // Vectors are aligned.
2631 ArgOffset = ((ArgOffset+15)/16)*16;
2632 CurArgOffset = ArgOffset;
2639 // We need to load the argument to a virtual register if we determined
2640 // above that we ran out of physical registers of the appropriate type.
2642 int FI = MFI->CreateFixedObject(ObjSize,
2643 CurArgOffset + (ArgSize - ObjSize),
2645 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2646 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2647 false, false, false, 0);
2650 InVals.push_back(ArgVal);
2653 // Set the size that is at least reserved in caller of this function. Tail
2654 // call optimized functions' reserved stack space needs to be aligned so that
2655 // taking the difference between two stack areas will result in an aligned
2657 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2659 // If the function takes variable number of arguments, make a frame index for
2660 // the start of the first vararg value... for expansion of llvm.va_start.
2662 int Depth = ArgOffset;
2664 FuncInfo->setVarArgsFrameIndex(
2665 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2666 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2668 // If this function is vararg, store any remaining integer argument regs
2669 // to their spots on the stack so that they may be loaded by deferencing the
2670 // result of va_next.
2671 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2672 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2673 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2674 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2675 MachinePointerInfo(), false, false, 0);
2676 MemOps.push_back(Store);
2677 // Increment the address by four for the next argument to store
2678 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2679 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2683 if (!MemOps.empty())
2684 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2690 PPCTargetLowering::LowerFormalArguments_Darwin(
2692 CallingConv::ID CallConv, bool isVarArg,
2693 const SmallVectorImpl<ISD::InputArg>
2695 SDLoc dl, SelectionDAG &DAG,
2696 SmallVectorImpl<SDValue> &InVals) const {
2697 // TODO: add description of PPC stack frame format, or at least some docs.
2699 MachineFunction &MF = DAG.getMachineFunction();
2700 MachineFrameInfo *MFI = MF.getFrameInfo();
2701 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2703 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2704 bool isPPC64 = PtrVT == MVT::i64;
2705 // Potential tail calls could cause overwriting of argument stack slots.
2706 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2707 (CallConv == CallingConv::Fast));
2708 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2710 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2711 // Area that is at least reserved in caller of this function.
2712 unsigned MinReservedArea = ArgOffset;
2714 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2715 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2716 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2718 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2719 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2720 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2723 static const MCPhysReg *FPR = GetFPR();
2725 static const MCPhysReg VR[] = {
2726 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2727 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2730 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2731 const unsigned Num_FPR_Regs = 13;
2732 const unsigned Num_VR_Regs = array_lengthof( VR);
2734 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2736 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2738 // In 32-bit non-varargs functions, the stack space for vectors is after the
2739 // stack space for non-vectors. We do not use this space unless we have
2740 // too many vectors to fit in registers, something that only occurs in
2741 // constructed examples:), but we have to walk the arglist to figure
2742 // that out...for the pathological case, compute VecArgOffset as the
2743 // start of the vector parameter area. Computing VecArgOffset is the
2744 // entire point of the following loop.
2745 unsigned VecArgOffset = ArgOffset;
2746 if (!isVarArg && !isPPC64) {
2747 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2749 EVT ObjectVT = Ins[ArgNo].VT;
2750 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2752 if (Flags.isByVal()) {
2753 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2754 unsigned ObjSize = Flags.getByValSize();
2756 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2757 VecArgOffset += ArgSize;
2761 switch(ObjectVT.getSimpleVT().SimpleTy) {
2762 default: llvm_unreachable("Unhandled argument type!");
2768 case MVT::i64: // PPC64
2770 // FIXME: We are guaranteed to be !isPPC64 at this point.
2771 // Does MVT::i64 apply?
2778 // Nothing to do, we're only looking at Nonvector args here.
2783 // We've found where the vector parameter area in memory is. Skip the
2784 // first 12 parameters; these don't use that memory.
2785 VecArgOffset = ((VecArgOffset+15)/16)*16;
2786 VecArgOffset += 12*16;
2788 // Add DAG nodes to load the arguments or copy them out of registers. On
2789 // entry to a function on PPC, the arguments start after the linkage area,
2790 // although the first ones are often in registers.
2792 SmallVector<SDValue, 8> MemOps;
2793 unsigned nAltivecParamsAtEnd = 0;
2794 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2795 unsigned CurArgIdx = 0;
2796 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2798 bool needsLoad = false;
2799 EVT ObjectVT = Ins[ArgNo].VT;
2800 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2801 unsigned ArgSize = ObjSize;
2802 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2803 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2804 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2806 unsigned CurArgOffset = ArgOffset;
2808 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2809 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2810 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2811 if (isVarArg || isPPC64) {
2812 MinReservedArea = ((MinReservedArea+15)/16)*16;
2813 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2816 } else nAltivecParamsAtEnd++;
2818 // Calculate min reserved area.
2819 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2823 // FIXME the codegen can be much improved in some cases.
2824 // We do not have to keep everything in memory.
2825 if (Flags.isByVal()) {
2826 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2827 ObjSize = Flags.getByValSize();
2828 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2829 // Objects of size 1 and 2 are right justified, everything else is
2830 // left justified. This means the memory address is adjusted forwards.
2831 if (ObjSize==1 || ObjSize==2) {
2832 CurArgOffset = CurArgOffset + (4 - ObjSize);
2834 // The value of the object is its address.
2835 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2836 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2837 InVals.push_back(FIN);
2838 if (ObjSize==1 || ObjSize==2) {
2839 if (GPR_idx != Num_GPR_Regs) {
2842 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2844 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2845 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2846 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2847 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2848 MachinePointerInfo(FuncArg),
2849 ObjType, false, false, 0);
2850 MemOps.push_back(Store);
2854 ArgOffset += PtrByteSize;
2858 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2859 // Store whatever pieces of the object are in registers
2860 // to memory. ArgOffset will be the address of the beginning
2862 if (GPR_idx != Num_GPR_Regs) {
2865 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2867 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2868 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2869 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2870 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2871 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2872 MachinePointerInfo(FuncArg, j),
2874 MemOps.push_back(Store);
2876 ArgOffset += PtrByteSize;
2878 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2885 switch (ObjectVT.getSimpleVT().SimpleTy) {
2886 default: llvm_unreachable("Unhandled argument type!");
2890 if (GPR_idx != Num_GPR_Regs) {
2891 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2892 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2894 if (ObjectVT == MVT::i1)
2895 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2900 ArgSize = PtrByteSize;
2902 // All int arguments reserve stack space in the Darwin ABI.
2903 ArgOffset += PtrByteSize;
2907 case MVT::i64: // PPC64
2908 if (GPR_idx != Num_GPR_Regs) {
2909 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2910 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2912 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2913 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2914 // value to MVT::i64 and then truncate to the correct register size.
2915 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2920 ArgSize = PtrByteSize;
2922 // All int arguments reserve stack space in the Darwin ABI.
2928 // Every 4 bytes of argument space consumes one of the GPRs available for
2929 // argument passing.
2930 if (GPR_idx != Num_GPR_Regs) {
2932 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2935 if (FPR_idx != Num_FPR_Regs) {
2938 if (ObjectVT == MVT::f32)
2939 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2941 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2943 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2949 // All FP arguments reserve stack space in the Darwin ABI.
2950 ArgOffset += isPPC64 ? 8 : ObjSize;
2956 // Note that vector arguments in registers don't reserve stack space,
2957 // except in varargs functions.
2958 if (VR_idx != Num_VR_Regs) {
2959 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2960 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2962 while ((ArgOffset % 16) != 0) {
2963 ArgOffset += PtrByteSize;
2964 if (GPR_idx != Num_GPR_Regs)
2968 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2972 if (!isVarArg && !isPPC64) {
2973 // Vectors go after all the nonvectors.
2974 CurArgOffset = VecArgOffset;
2977 // Vectors are aligned.
2978 ArgOffset = ((ArgOffset+15)/16)*16;
2979 CurArgOffset = ArgOffset;
2987 // We need to load the argument to a virtual register if we determined above
2988 // that we ran out of physical registers of the appropriate type.
2990 int FI = MFI->CreateFixedObject(ObjSize,
2991 CurArgOffset + (ArgSize - ObjSize),
2993 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2994 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2995 false, false, false, 0);
2998 InVals.push_back(ArgVal);
3001 // Set the size that is at least reserved in caller of this function. Tail
3002 // call optimized functions' reserved stack space needs to be aligned so that
3003 // taking the difference between two stack areas will result in an aligned
3005 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
3007 // If the function takes variable number of arguments, make a frame index for
3008 // the start of the first vararg value... for expansion of llvm.va_start.
3010 int Depth = ArgOffset;
3012 FuncInfo->setVarArgsFrameIndex(
3013 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3015 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3017 // If this function is vararg, store any remaining integer argument regs
3018 // to their spots on the stack so that they may be loaded by deferencing the
3019 // result of va_next.
3020 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3024 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3026 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3028 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3029 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3030 MachinePointerInfo(), false, false, 0);
3031 MemOps.push_back(Store);
3032 // Increment the address by four for the next argument to store
3033 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3034 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3038 if (!MemOps.empty())
3039 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3044 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
3045 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
3047 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
3051 const SmallVectorImpl<ISD::OutputArg>
3053 const SmallVectorImpl<SDValue> &OutVals,
3054 unsigned &nAltivecParamsAtEnd) {
3055 // Count how many bytes are to be pushed on the stack, including the linkage
3056 // area, and parameter passing area. We start with 24/48 bytes, which is
3057 // prereserved space for [SP][CR][LR][3 x unused].
3058 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
3059 unsigned NumOps = Outs.size();
3060 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3062 // Add up all the space actually used.
3063 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
3064 // they all go in registers, but we must reserve stack space for them for
3065 // possible use by the caller. In varargs or 64-bit calls, parameters are
3066 // assigned stack space in order, with padding so Altivec parameters are
3068 nAltivecParamsAtEnd = 0;
3069 for (unsigned i = 0; i != NumOps; ++i) {
3070 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3071 EVT ArgVT = Outs[i].VT;
3072 // Varargs Altivec parameters are padded to a 16 byte boundary.
3073 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
3074 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8 ||
3075 ArgVT==MVT::v2f64 || ArgVT==MVT::v2i64) {
3076 if (!isVarArg && !isPPC64) {
3077 // Non-varargs Altivec parameters go after all the non-Altivec
3078 // parameters; handle those later so we know how much padding we need.
3079 nAltivecParamsAtEnd++;
3082 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
3083 NumBytes = ((NumBytes+15)/16)*16;
3085 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3088 // Allow for Altivec parameters at the end, if needed.
3089 if (nAltivecParamsAtEnd) {
3090 NumBytes = ((NumBytes+15)/16)*16;
3091 NumBytes += 16*nAltivecParamsAtEnd;
3094 // The prolog code of the callee may store up to 8 GPR argument registers to
3095 // the stack, allowing va_start to index over them in memory if its varargs.
3096 // Because we cannot tell if this is needed on the caller side, we have to
3097 // conservatively assume that it is needed. As such, make sure we have at
3098 // least enough stack space for the caller to store the 8 GPRs.
3099 NumBytes = std::max(NumBytes,
3100 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
3102 // Tail call needs the stack to be aligned.
3103 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
3104 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
3105 getFrameLowering()->getStackAlignment();
3106 unsigned AlignMask = TargetAlign-1;
3107 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3113 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3114 /// adjusted to accommodate the arguments for the tailcall.
3115 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3116 unsigned ParamSize) {
3118 if (!isTailCall) return 0;
3120 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3121 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3122 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3123 // Remember only if the new adjustement is bigger.
3124 if (SPDiff < FI->getTailCallSPDelta())
3125 FI->setTailCallSPDelta(SPDiff);
3130 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3131 /// for tail call optimization. Targets which want to do tail call
3132 /// optimization should implement this function.
3134 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3135 CallingConv::ID CalleeCC,
3137 const SmallVectorImpl<ISD::InputArg> &Ins,
3138 SelectionDAG& DAG) const {
3139 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3142 // Variable argument functions are not supported.
3146 MachineFunction &MF = DAG.getMachineFunction();
3147 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3148 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3149 // Functions containing by val parameters are not supported.
3150 for (unsigned i = 0; i != Ins.size(); i++) {
3151 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3152 if (Flags.isByVal()) return false;
3155 // Non-PIC/GOT tail calls are supported.
3156 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3159 // At the moment we can only do local tail calls (in same module, hidden
3160 // or protected) if we are generating PIC.
3161 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3162 return G->getGlobal()->hasHiddenVisibility()
3163 || G->getGlobal()->hasProtectedVisibility();
3169 /// isCallCompatibleAddress - Return the immediate to use if the specified
3170 /// 32-bit value is representable in the immediate field of a BxA instruction.
3171 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3172 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3173 if (!C) return nullptr;
3175 int Addr = C->getZExtValue();
3176 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3177 SignExtend32<26>(Addr) != Addr)
3178 return nullptr; // Top 6 bits have to be sext of immediate.
3180 return DAG.getConstant((int)C->getZExtValue() >> 2,
3181 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3186 struct TailCallArgumentInfo {
3191 TailCallArgumentInfo() : FrameIdx(0) {}
3196 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3198 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3200 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3201 SmallVectorImpl<SDValue> &MemOpChains,
3203 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3204 SDValue Arg = TailCallArgs[i].Arg;
3205 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3206 int FI = TailCallArgs[i].FrameIdx;
3207 // Store relative to framepointer.
3208 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3209 MachinePointerInfo::getFixedStack(FI),
3214 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3215 /// the appropriate stack slot for the tail call optimized function call.
3216 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3217 MachineFunction &MF,
3226 // Calculate the new stack slot for the return address.
3227 int SlotSize = isPPC64 ? 8 : 4;
3228 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3230 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3231 NewRetAddrLoc, true);
3232 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3233 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3234 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3235 MachinePointerInfo::getFixedStack(NewRetAddr),
3238 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3239 // slot as the FP is never overwritten.
3242 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3243 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3245 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3246 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3247 MachinePointerInfo::getFixedStack(NewFPIdx),
3254 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3255 /// the position of the argument.
3257 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3258 SDValue Arg, int SPDiff, unsigned ArgOffset,
3259 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3260 int Offset = ArgOffset + SPDiff;
3261 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3262 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3263 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3264 SDValue FIN = DAG.getFrameIndex(FI, VT);
3265 TailCallArgumentInfo Info;
3267 Info.FrameIdxOp = FIN;
3269 TailCallArguments.push_back(Info);
3272 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3273 /// stack slot. Returns the chain as result and the loaded frame pointers in
3274 /// LROpOut/FPOpout. Used when tail calling.
3275 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3283 // Load the LR and FP stack slot for later adjusting.
3284 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3285 LROpOut = getReturnAddrFrameIndex(DAG);
3286 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3287 false, false, false, 0);
3288 Chain = SDValue(LROpOut.getNode(), 1);
3290 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3291 // slot as the FP is never overwritten.
3293 FPOpOut = getFramePointerFrameIndex(DAG);
3294 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3295 false, false, false, 0);
3296 Chain = SDValue(FPOpOut.getNode(), 1);
3302 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3303 /// by "Src" to address "Dst" of size "Size". Alignment information is
3304 /// specified by the specific parameter attribute. The copy will be passed as
3305 /// a byval function parameter.
3306 /// Sometimes what we are copying is the end of a larger object, the part that
3307 /// does not fit in registers.
3309 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3310 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3312 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3313 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3314 false, false, MachinePointerInfo(),
3315 MachinePointerInfo());
3318 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3321 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3322 SDValue Arg, SDValue PtrOff, int SPDiff,
3323 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3324 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3325 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3327 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3332 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3334 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3335 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3336 DAG.getConstant(ArgOffset, PtrVT));
3338 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3339 MachinePointerInfo(), false, false, 0));
3340 // Calculate and remember argument location.
3341 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3346 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3347 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3348 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3349 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3350 MachineFunction &MF = DAG.getMachineFunction();
3352 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3353 // might overwrite each other in case of tail call optimization.
3354 SmallVector<SDValue, 8> MemOpChains2;
3355 // Do not flag preceding copytoreg stuff together with the following stuff.
3357 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3359 if (!MemOpChains2.empty())
3360 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3362 // Store the return address to the appropriate stack slot.
3363 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3364 isPPC64, isDarwinABI, dl);
3366 // Emit callseq_end just before tailcall node.
3367 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3368 DAG.getIntPtrConstant(0, true), InFlag, dl);
3369 InFlag = Chain.getValue(1);
3373 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3374 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3375 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3376 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3377 const PPCSubtarget &PPCSubTarget) {
3379 bool isPPC64 = PPCSubTarget.isPPC64();
3380 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3382 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3383 NodeTys.push_back(MVT::Other); // Returns a chain
3384 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3386 unsigned CallOpc = PPCISD::CALL;
3388 bool needIndirectCall = true;
3389 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3390 // If this is an absolute destination address, use the munged value.
3391 Callee = SDValue(Dest, 0);
3392 needIndirectCall = false;
3395 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3396 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3397 // Use indirect calls for ALL functions calls in JIT mode, since the
3398 // far-call stubs may be outside relocation limits for a BL instruction.
3399 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3400 unsigned OpFlags = 0;
3401 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3402 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3403 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3404 (G->getGlobal()->isDeclaration() ||
3405 G->getGlobal()->isWeakForLinker())) {
3406 // PC-relative references to external symbols should go through $stub,
3407 // unless we're building with the leopard linker or later, which
3408 // automatically synthesizes these stubs.
3409 OpFlags = PPCII::MO_DARWIN_STUB;
3412 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3413 // every direct call is) turn it into a TargetGlobalAddress /
3414 // TargetExternalSymbol node so that legalize doesn't hack it.
3415 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3416 Callee.getValueType(),
3418 needIndirectCall = false;
3422 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3423 unsigned char OpFlags = 0;
3425 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3426 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3427 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3428 // PC-relative references to external symbols should go through $stub,
3429 // unless we're building with the leopard linker or later, which
3430 // automatically synthesizes these stubs.
3431 OpFlags = PPCII::MO_DARWIN_STUB;
3434 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3436 needIndirectCall = false;
3439 if (needIndirectCall) {
3440 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3441 // to do the call, we can't use PPCISD::CALL.
3442 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3444 if (isSVR4ABI && isPPC64) {
3445 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3446 // entry point, but to the function descriptor (the function entry point
3447 // address is part of the function descriptor though).
3448 // The function descriptor is a three doubleword structure with the
3449 // following fields: function entry point, TOC base address and
3450 // environment pointer.
3451 // Thus for a call through a function pointer, the following actions need
3453 // 1. Save the TOC of the caller in the TOC save area of its stack
3454 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3455 // 2. Load the address of the function entry point from the function
3457 // 3. Load the TOC of the callee from the function descriptor into r2.
3458 // 4. Load the environment pointer from the function descriptor into
3460 // 5. Branch to the function entry point address.
3461 // 6. On return of the callee, the TOC of the caller needs to be
3462 // restored (this is done in FinishCall()).
3464 // All those operations are flagged together to ensure that no other
3465 // operations can be scheduled in between. E.g. without flagging the
3466 // operations together, a TOC access in the caller could be scheduled
3467 // between the load of the callee TOC and the branch to the callee, which
3468 // results in the TOC access going through the TOC of the callee instead
3469 // of going through the TOC of the caller, which leads to incorrect code.
3471 // Load the address of the function entry point from the function
3473 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3474 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3475 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3476 Chain = LoadFuncPtr.getValue(1);
3477 InFlag = LoadFuncPtr.getValue(2);
3479 // Load environment pointer into r11.
3480 // Offset of the environment pointer within the function descriptor.
3481 SDValue PtrOff = DAG.getIntPtrConstant(16);
3483 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3484 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3486 Chain = LoadEnvPtr.getValue(1);
3487 InFlag = LoadEnvPtr.getValue(2);
3489 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3491 Chain = EnvVal.getValue(0);
3492 InFlag = EnvVal.getValue(1);
3494 // Load TOC of the callee into r2. We are using a target-specific load
3495 // with r2 hard coded, because the result of a target-independent load
3496 // would never go directly into r2, since r2 is a reserved register (which
3497 // prevents the register allocator from allocating it), resulting in an
3498 // additional register being allocated and an unnecessary move instruction
3500 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3501 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3503 Chain = LoadTOCPtr.getValue(0);
3504 InFlag = LoadTOCPtr.getValue(1);
3506 MTCTROps[0] = Chain;
3507 MTCTROps[1] = LoadFuncPtr;
3508 MTCTROps[2] = InFlag;
3511 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3512 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3513 InFlag = Chain.getValue(1);
3516 NodeTys.push_back(MVT::Other);
3517 NodeTys.push_back(MVT::Glue);
3518 Ops.push_back(Chain);
3519 CallOpc = PPCISD::BCTRL;
3520 Callee.setNode(nullptr);
3521 // Add use of X11 (holding environment pointer)
3522 if (isSVR4ABI && isPPC64)
3523 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3524 // Add CTR register as callee so a bctr can be emitted later.
3526 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3529 // If this is a direct call, pass the chain and the callee.
3530 if (Callee.getNode()) {
3531 Ops.push_back(Chain);
3532 Ops.push_back(Callee);
3534 // If this is a tail call add stack pointer delta.
3536 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3538 // Add argument registers to the end of the list so that they are known live
3540 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3541 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3542 RegsToPass[i].second.getValueType()));
3548 bool isLocalCall(const SDValue &Callee)
3550 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3551 return !G->getGlobal()->isDeclaration() &&
3552 !G->getGlobal()->isWeakForLinker();
3557 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3558 CallingConv::ID CallConv, bool isVarArg,
3559 const SmallVectorImpl<ISD::InputArg> &Ins,
3560 SDLoc dl, SelectionDAG &DAG,
3561 SmallVectorImpl<SDValue> &InVals) const {
3563 SmallVector<CCValAssign, 16> RVLocs;
3564 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3565 getTargetMachine(), RVLocs, *DAG.getContext());
3566 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3568 // Copy all of the result registers out of their specified physreg.
3569 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3570 CCValAssign &VA = RVLocs[i];
3571 assert(VA.isRegLoc() && "Can only return in registers!");
3573 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3574 VA.getLocReg(), VA.getLocVT(), InFlag);
3575 Chain = Val.getValue(1);
3576 InFlag = Val.getValue(2);
3578 switch (VA.getLocInfo()) {
3579 default: llvm_unreachable("Unknown loc info!");
3580 case CCValAssign::Full: break;
3581 case CCValAssign::AExt:
3582 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3584 case CCValAssign::ZExt:
3585 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3586 DAG.getValueType(VA.getValVT()));
3587 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3589 case CCValAssign::SExt:
3590 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3591 DAG.getValueType(VA.getValVT()));
3592 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3596 InVals.push_back(Val);
3603 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3604 bool isTailCall, bool isVarArg,
3606 SmallVector<std::pair<unsigned, SDValue>, 8>
3608 SDValue InFlag, SDValue Chain,
3610 int SPDiff, unsigned NumBytes,
3611 const SmallVectorImpl<ISD::InputArg> &Ins,
3612 SmallVectorImpl<SDValue> &InVals) const {
3613 std::vector<EVT> NodeTys;
3614 SmallVector<SDValue, 8> Ops;
3615 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3616 isTailCall, RegsToPass, Ops, NodeTys,
3619 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3620 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3621 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3623 // When performing tail call optimization the callee pops its arguments off
3624 // the stack. Account for this here so these bytes can be pushed back on in
3625 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3626 int BytesCalleePops =
3627 (CallConv == CallingConv::Fast &&
3628 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3630 // Add a register mask operand representing the call-preserved registers.
3631 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3632 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3633 assert(Mask && "Missing call preserved mask for calling convention");
3634 Ops.push_back(DAG.getRegisterMask(Mask));
3636 if (InFlag.getNode())
3637 Ops.push_back(InFlag);
3641 assert(((Callee.getOpcode() == ISD::Register &&
3642 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3643 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3644 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3645 isa<ConstantSDNode>(Callee)) &&
3646 "Expecting an global address, external symbol, absolute value or register");
3648 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3651 // Add a NOP immediately after the branch instruction when using the 64-bit
3652 // SVR4 ABI. At link time, if caller and callee are in a different module and
3653 // thus have a different TOC, the call will be replaced with a call to a stub
3654 // function which saves the current TOC, loads the TOC of the callee and
3655 // branches to the callee. The NOP will be replaced with a load instruction
3656 // which restores the TOC of the caller from the TOC save slot of the current
3657 // stack frame. If caller and callee belong to the same module (and have the
3658 // same TOC), the NOP will remain unchanged.
3660 bool needsTOCRestore = false;
3661 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3662 if (CallOpc == PPCISD::BCTRL) {
3663 // This is a call through a function pointer.
3664 // Restore the caller TOC from the save area into R2.
3665 // See PrepareCall() for more information about calls through function
3666 // pointers in the 64-bit SVR4 ABI.
3667 // We are using a target-specific load with r2 hard coded, because the
3668 // result of a target-independent load would never go directly into r2,
3669 // since r2 is a reserved register (which prevents the register allocator
3670 // from allocating it), resulting in an additional register being
3671 // allocated and an unnecessary move instruction being generated.
3672 needsTOCRestore = true;
3673 } else if ((CallOpc == PPCISD::CALL) &&
3674 (!isLocalCall(Callee) ||
3675 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3676 // Otherwise insert NOP for non-local calls.
3677 CallOpc = PPCISD::CALL_NOP;
3681 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3682 InFlag = Chain.getValue(1);
3684 if (needsTOCRestore) {
3685 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3686 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3687 InFlag = Chain.getValue(1);
3690 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3691 DAG.getIntPtrConstant(BytesCalleePops, true),
3694 InFlag = Chain.getValue(1);
3696 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3697 Ins, dl, DAG, InVals);
3701 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3702 SmallVectorImpl<SDValue> &InVals) const {
3703 SelectionDAG &DAG = CLI.DAG;
3705 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3706 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3707 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3708 SDValue Chain = CLI.Chain;
3709 SDValue Callee = CLI.Callee;
3710 bool &isTailCall = CLI.IsTailCall;
3711 CallingConv::ID CallConv = CLI.CallConv;
3712 bool isVarArg = CLI.IsVarArg;
3715 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3718 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3719 report_fatal_error("failed to perform tail call elimination on a call "
3720 "site marked musttail");
3722 if (PPCSubTarget.isSVR4ABI()) {
3723 if (PPCSubTarget.isPPC64())
3724 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3725 isTailCall, Outs, OutVals, Ins,
3728 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3729 isTailCall, Outs, OutVals, Ins,
3733 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3734 isTailCall, Outs, OutVals, Ins,
3739 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3740 CallingConv::ID CallConv, bool isVarArg,
3742 const SmallVectorImpl<ISD::OutputArg> &Outs,
3743 const SmallVectorImpl<SDValue> &OutVals,
3744 const SmallVectorImpl<ISD::InputArg> &Ins,
3745 SDLoc dl, SelectionDAG &DAG,
3746 SmallVectorImpl<SDValue> &InVals) const {
3747 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3748 // of the 32-bit SVR4 ABI stack frame layout.
3750 assert((CallConv == CallingConv::C ||
3751 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3753 unsigned PtrByteSize = 4;
3755 MachineFunction &MF = DAG.getMachineFunction();
3757 // Mark this function as potentially containing a function that contains a
3758 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3759 // and restoring the callers stack pointer in this functions epilog. This is
3760 // done because by tail calling the called function might overwrite the value
3761 // in this function's (MF) stack pointer stack slot 0(SP).
3762 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3763 CallConv == CallingConv::Fast)
3764 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3766 // Count how many bytes are to be pushed on the stack, including the linkage
3767 // area, parameter list area and the part of the local variable space which
3768 // contains copies of aggregates which are passed by value.
3770 // Assign locations to all of the outgoing arguments.
3771 SmallVector<CCValAssign, 16> ArgLocs;
3772 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3773 getTargetMachine(), ArgLocs, *DAG.getContext());
3775 // Reserve space for the linkage area on the stack.
3776 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3779 // Handle fixed and variable vector arguments differently.
3780 // Fixed vector arguments go into registers as long as registers are
3781 // available. Variable vector arguments always go into memory.
3782 unsigned NumArgs = Outs.size();
3784 for (unsigned i = 0; i != NumArgs; ++i) {
3785 MVT ArgVT = Outs[i].VT;
3786 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3789 if (Outs[i].IsFixed) {
3790 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3793 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3799 errs() << "Call operand #" << i << " has unhandled type "
3800 << EVT(ArgVT).getEVTString() << "\n";
3802 llvm_unreachable(nullptr);
3806 // All arguments are treated the same.
3807 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3810 // Assign locations to all of the outgoing aggregate by value arguments.
3811 SmallVector<CCValAssign, 16> ByValArgLocs;
3812 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3813 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3815 // Reserve stack space for the allocations in CCInfo.
3816 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3818 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3820 // Size of the linkage area, parameter list area and the part of the local
3821 // space variable where copies of aggregates which are passed by value are
3823 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3825 // Calculate by how many bytes the stack has to be adjusted in case of tail
3826 // call optimization.
3827 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3829 // Adjust the stack pointer for the new arguments...
3830 // These operations are automatically eliminated by the prolog/epilog pass
3831 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3833 SDValue CallSeqStart = Chain;
3835 // Load the return address and frame pointer so it can be moved somewhere else
3838 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3841 // Set up a copy of the stack pointer for use loading and storing any
3842 // arguments that may not fit in the registers available for argument
3844 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3846 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3847 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3848 SmallVector<SDValue, 8> MemOpChains;
3850 bool seenFloatArg = false;
3851 // Walk the register/memloc assignments, inserting copies/loads.
3852 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3855 CCValAssign &VA = ArgLocs[i];
3856 SDValue Arg = OutVals[i];
3857 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3859 if (Flags.isByVal()) {
3860 // Argument is an aggregate which is passed by value, thus we need to
3861 // create a copy of it in the local variable space of the current stack
3862 // frame (which is the stack frame of the caller) and pass the address of
3863 // this copy to the callee.
3864 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3865 CCValAssign &ByValVA = ByValArgLocs[j++];
3866 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3868 // Memory reserved in the local variable space of the callers stack frame.
3869 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3871 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3872 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3874 // Create a copy of the argument in the local area of the current
3876 SDValue MemcpyCall =
3877 CreateCopyOfByValArgument(Arg, PtrOff,
3878 CallSeqStart.getNode()->getOperand(0),
3881 // This must go outside the CALLSEQ_START..END.
3882 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3883 CallSeqStart.getNode()->getOperand(1),
3885 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3886 NewCallSeqStart.getNode());
3887 Chain = CallSeqStart = NewCallSeqStart;
3889 // Pass the address of the aggregate copy on the stack either in a
3890 // physical register or in the parameter list area of the current stack
3891 // frame to the callee.
3895 if (VA.isRegLoc()) {
3896 if (Arg.getValueType() == MVT::i1)
3897 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3899 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3900 // Put argument in a physical register.
3901 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3903 // Put argument in the parameter list area of the current stack frame.
3904 assert(VA.isMemLoc());
3905 unsigned LocMemOffset = VA.getLocMemOffset();
3908 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3909 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3911 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3912 MachinePointerInfo(),
3915 // Calculate and remember argument location.
3916 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3922 if (!MemOpChains.empty())
3923 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3925 // Build a sequence of copy-to-reg nodes chained together with token chain
3926 // and flag operands which copy the outgoing args into the appropriate regs.
3928 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3929 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3930 RegsToPass[i].second, InFlag);
3931 InFlag = Chain.getValue(1);
3934 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3937 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3938 SDValue Ops[] = { Chain, InFlag };
3940 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3941 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
3943 InFlag = Chain.getValue(1);
3947 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3948 false, TailCallArguments);
3950 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3951 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3955 // Copy an argument into memory, being careful to do this outside the
3956 // call sequence for the call to which the argument belongs.
3958 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3959 SDValue CallSeqStart,
3960 ISD::ArgFlagsTy Flags,
3963 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3964 CallSeqStart.getNode()->getOperand(0),
3966 // The MEMCPY must go outside the CALLSEQ_START..END.
3967 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3968 CallSeqStart.getNode()->getOperand(1),
3970 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3971 NewCallSeqStart.getNode());
3972 return NewCallSeqStart;
3976 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3977 CallingConv::ID CallConv, bool isVarArg,
3979 const SmallVectorImpl<ISD::OutputArg> &Outs,
3980 const SmallVectorImpl<SDValue> &OutVals,
3981 const SmallVectorImpl<ISD::InputArg> &Ins,
3982 SDLoc dl, SelectionDAG &DAG,
3983 SmallVectorImpl<SDValue> &InVals) const {
3985 unsigned NumOps = Outs.size();
3987 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3988 unsigned PtrByteSize = 8;
3990 MachineFunction &MF = DAG.getMachineFunction();
3992 // Mark this function as potentially containing a function that contains a
3993 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3994 // and restoring the callers stack pointer in this functions epilog. This is
3995 // done because by tail calling the called function might overwrite the value
3996 // in this function's (MF) stack pointer stack slot 0(SP).
3997 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3998 CallConv == CallingConv::Fast)
3999 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4001 unsigned nAltivecParamsAtEnd = 0;
4003 // Count how many bytes are to be pushed on the stack, including the linkage
4004 // area, and parameter passing area. We start with at least 48 bytes, which
4005 // is reserved space for [SP][CR][LR][3 x unused].
4006 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
4009 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
4010 Outs, OutVals, nAltivecParamsAtEnd);
4012 // Calculate by how many bytes the stack has to be adjusted in case of tail
4013 // call optimization.
4014 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4016 // To protect arguments on the stack from being clobbered in a tail call,
4017 // force all the loads to happen before doing any other lowering.
4019 Chain = DAG.getStackArgumentTokenFactor(Chain);
4021 // Adjust the stack pointer for the new arguments...
4022 // These operations are automatically eliminated by the prolog/epilog pass
4023 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4025 SDValue CallSeqStart = Chain;
4027 // Load the return address and frame pointer so it can be move somewhere else
4030 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4033 // Set up a copy of the stack pointer for use loading and storing any
4034 // arguments that may not fit in the registers available for argument
4036 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4038 // Figure out which arguments are going to go in registers, and which in
4039 // memory. Also, if this is a vararg function, floating point operations
4040 // must be stored to our stack, and loaded into integer regs as well, if
4041 // any integer regs are available for argument passing.
4042 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
4043 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4045 static const MCPhysReg GPR[] = {
4046 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4047 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4049 static const MCPhysReg *FPR = GetFPR();
4051 static const MCPhysReg VR[] = {
4052 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4053 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4055 static const MCPhysReg VSRH[] = {
4056 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4057 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4060 const unsigned NumGPRs = array_lengthof(GPR);
4061 const unsigned NumFPRs = 13;
4062 const unsigned NumVRs = array_lengthof(VR);
4064 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4065 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4067 SmallVector<SDValue, 8> MemOpChains;
4068 for (unsigned i = 0; i != NumOps; ++i) {
4069 SDValue Arg = OutVals[i];
4070 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4072 // PtrOff will be used to store the current argument to the stack if a
4073 // register cannot be found for it.
4076 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4078 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4080 // Promote integers to 64-bit values.
4081 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4082 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4083 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4084 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4087 // FIXME memcpy is used way more than necessary. Correctness first.
4088 // Note: "by value" is code for passing a structure by value, not
4090 if (Flags.isByVal()) {
4091 // Note: Size includes alignment padding, so
4092 // struct x { short a; char b; }
4093 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4094 // These are the proper values we need for right-justifying the
4095 // aggregate in a parameter register.
4096 unsigned Size = Flags.getByValSize();
4098 // An empty aggregate parameter takes up no storage and no
4103 unsigned BVAlign = Flags.getByValAlign();
4105 if (BVAlign % PtrByteSize != 0)
4107 "ByVal alignment is not a multiple of the pointer size");
4109 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
4112 // All aggregates smaller than 8 bytes must be passed right-justified.
4113 if (Size==1 || Size==2 || Size==4) {
4114 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4115 if (GPR_idx != NumGPRs) {
4116 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4117 MachinePointerInfo(), VT,
4119 MemOpChains.push_back(Load.getValue(1));
4120 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4122 ArgOffset += PtrByteSize;
4127 if (GPR_idx == NumGPRs && Size < 8) {
4128 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4129 PtrOff.getValueType());
4130 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4131 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4134 ArgOffset += PtrByteSize;
4137 // Copy entire object into memory. There are cases where gcc-generated
4138 // code assumes it is there, even if it could be put entirely into
4139 // registers. (This is not what the doc says.)
4141 // FIXME: The above statement is likely due to a misunderstanding of the
4142 // documents. All arguments must be copied into the parameter area BY
4143 // THE CALLEE in the event that the callee takes the address of any
4144 // formal argument. That has not yet been implemented. However, it is
4145 // reasonable to use the stack area as a staging area for the register
4148 // Skip this for small aggregates, as we will use the same slot for a
4149 // right-justified copy, below.
4151 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4155 // When a register is available, pass a small aggregate right-justified.
4156 if (Size < 8 && GPR_idx != NumGPRs) {
4157 // The easiest way to get this right-justified in a register
4158 // is to copy the structure into the rightmost portion of a
4159 // local variable slot, then load the whole slot into the
4161 // FIXME: The memcpy seems to produce pretty awful code for
4162 // small aggregates, particularly for packed ones.
4163 // FIXME: It would be preferable to use the slot in the
4164 // parameter save area instead of a new local variable.
4165 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4166 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4167 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4171 // Load the slot into the register.
4172 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4173 MachinePointerInfo(),
4174 false, false, false, 0);
4175 MemOpChains.push_back(Load.getValue(1));
4176 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4178 // Done with this argument.
4179 ArgOffset += PtrByteSize;
4183 // For aggregates larger than PtrByteSize, copy the pieces of the
4184 // object that fit into registers from the parameter save area.
4185 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4186 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4187 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4188 if (GPR_idx != NumGPRs) {
4189 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4190 MachinePointerInfo(),
4191 false, false, false, 0);
4192 MemOpChains.push_back(Load.getValue(1));
4193 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4194 ArgOffset += PtrByteSize;
4196 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4203 switch (Arg.getSimpleValueType().SimpleTy) {
4204 default: llvm_unreachable("Unexpected ValueType for argument!");
4208 if (GPR_idx != NumGPRs) {
4209 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4211 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4212 true, isTailCall, false, MemOpChains,
4213 TailCallArguments, dl);
4215 ArgOffset += PtrByteSize;
4219 if (FPR_idx != NumFPRs) {
4220 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4223 // A single float or an aggregate containing only a single float
4224 // must be passed right-justified in the stack doubleword, and
4225 // in the GPR, if one is available.
4227 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4228 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4229 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4233 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4234 MachinePointerInfo(), false, false, 0);
4235 MemOpChains.push_back(Store);
4237 // Float varargs are always shadowed in available integer registers
4238 if (GPR_idx != NumGPRs) {
4239 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4240 MachinePointerInfo(), false, false,
4242 MemOpChains.push_back(Load.getValue(1));
4243 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4245 } else if (GPR_idx != NumGPRs)
4246 // If we have any FPRs remaining, we may also have GPRs remaining.
4249 // Single-precision floating-point values are mapped to the
4250 // second (rightmost) word of the stack doubleword.
4251 if (Arg.getValueType() == MVT::f32) {
4252 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4253 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4256 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4257 true, isTailCall, false, MemOpChains,
4258 TailCallArguments, dl);
4269 // These go aligned on the stack, or in the corresponding R registers
4270 // when within range. The Darwin PPC ABI doc claims they also go in
4271 // V registers; in fact gcc does this only for arguments that are
4272 // prototyped, not for those that match the ... We do it for all
4273 // arguments, seems to work.
4274 while (ArgOffset % 16 !=0) {
4275 ArgOffset += PtrByteSize;
4276 if (GPR_idx != NumGPRs)
4279 // We could elide this store in the case where the object fits
4280 // entirely in R registers. Maybe later.
4281 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4282 DAG.getConstant(ArgOffset, PtrVT));
4283 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4284 MachinePointerInfo(), false, false, 0);
4285 MemOpChains.push_back(Store);
4286 if (VR_idx != NumVRs) {
4287 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4288 MachinePointerInfo(),
4289 false, false, false, 0);
4290 MemOpChains.push_back(Load.getValue(1));
4292 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4293 Arg.getSimpleValueType() == MVT::v2i64) ?
4294 VSRH[VR_idx] : VR[VR_idx];
4297 RegsToPass.push_back(std::make_pair(VReg, Load));
4300 for (unsigned i=0; i<16; i+=PtrByteSize) {
4301 if (GPR_idx == NumGPRs)
4303 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4304 DAG.getConstant(i, PtrVT));
4305 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4306 false, false, false, 0);
4307 MemOpChains.push_back(Load.getValue(1));
4308 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4313 // Non-varargs Altivec params generally go in registers, but have
4314 // stack space allocated at the end.
4315 if (VR_idx != NumVRs) {
4316 // Doesn't have GPR space allocated.
4317 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4318 Arg.getSimpleValueType() == MVT::v2i64) ?
4319 VSRH[VR_idx] : VR[VR_idx];
4322 RegsToPass.push_back(std::make_pair(VReg, Arg));
4324 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4325 true, isTailCall, true, MemOpChains,
4326 TailCallArguments, dl);
4333 if (!MemOpChains.empty())
4334 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4336 // Check if this is an indirect call (MTCTR/BCTRL).
4337 // See PrepareCall() for more information about calls through function
4338 // pointers in the 64-bit SVR4 ABI.
4340 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4341 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4342 !isBLACompatibleAddress(Callee, DAG)) {
4343 // Load r2 into a virtual register and store it to the TOC save area.
4344 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4345 // TOC save area offset.
4346 SDValue PtrOff = DAG.getIntPtrConstant(40);
4347 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4348 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4350 // R12 must contain the address of an indirect callee. This does not
4351 // mean the MTCTR instruction must use R12; it's easier to model this
4352 // as an extra parameter, so do that.
4353 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4356 // Build a sequence of copy-to-reg nodes chained together with token chain
4357 // and flag operands which copy the outgoing args into the appropriate regs.
4359 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4360 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4361 RegsToPass[i].second, InFlag);
4362 InFlag = Chain.getValue(1);
4366 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4367 FPOp, true, TailCallArguments);
4369 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4370 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4375 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4376 CallingConv::ID CallConv, bool isVarArg,
4378 const SmallVectorImpl<ISD::OutputArg> &Outs,
4379 const SmallVectorImpl<SDValue> &OutVals,
4380 const SmallVectorImpl<ISD::InputArg> &Ins,
4381 SDLoc dl, SelectionDAG &DAG,
4382 SmallVectorImpl<SDValue> &InVals) const {
4384 unsigned NumOps = Outs.size();
4386 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4387 bool isPPC64 = PtrVT == MVT::i64;
4388 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4390 MachineFunction &MF = DAG.getMachineFunction();
4392 // Mark this function as potentially containing a function that contains a
4393 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4394 // and restoring the callers stack pointer in this functions epilog. This is
4395 // done because by tail calling the called function might overwrite the value
4396 // in this function's (MF) stack pointer stack slot 0(SP).
4397 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4398 CallConv == CallingConv::Fast)
4399 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4401 unsigned nAltivecParamsAtEnd = 0;
4403 // Count how many bytes are to be pushed on the stack, including the linkage
4404 // area, and parameter passing area. We start with 24/48 bytes, which is
4405 // prereserved space for [SP][CR][LR][3 x unused].
4407 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4409 nAltivecParamsAtEnd);
4411 // Calculate by how many bytes the stack has to be adjusted in case of tail
4412 // call optimization.
4413 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4415 // To protect arguments on the stack from being clobbered in a tail call,
4416 // force all the loads to happen before doing any other lowering.
4418 Chain = DAG.getStackArgumentTokenFactor(Chain);
4420 // Adjust the stack pointer for the new arguments...
4421 // These operations are automatically eliminated by the prolog/epilog pass
4422 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4424 SDValue CallSeqStart = Chain;
4426 // Load the return address and frame pointer so it can be move somewhere else
4429 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4432 // Set up a copy of the stack pointer for use loading and storing any
4433 // arguments that may not fit in the registers available for argument
4437 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4439 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4441 // Figure out which arguments are going to go in registers, and which in
4442 // memory. Also, if this is a vararg function, floating point operations
4443 // must be stored to our stack, and loaded into integer regs as well, if
4444 // any integer regs are available for argument passing.
4445 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4446 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4448 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4449 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4450 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4452 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4453 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4454 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4456 static const MCPhysReg *FPR = GetFPR();
4458 static const MCPhysReg VR[] = {
4459 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4460 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4462 const unsigned NumGPRs = array_lengthof(GPR_32);
4463 const unsigned NumFPRs = 13;
4464 const unsigned NumVRs = array_lengthof(VR);
4466 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4468 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4469 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4471 SmallVector<SDValue, 8> MemOpChains;
4472 for (unsigned i = 0; i != NumOps; ++i) {
4473 SDValue Arg = OutVals[i];
4474 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4476 // PtrOff will be used to store the current argument to the stack if a
4477 // register cannot be found for it.
4480 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4482 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4484 // On PPC64, promote integers to 64-bit values.
4485 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4486 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4487 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4488 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4491 // FIXME memcpy is used way more than necessary. Correctness first.
4492 // Note: "by value" is code for passing a structure by value, not
4494 if (Flags.isByVal()) {
4495 unsigned Size = Flags.getByValSize();
4496 // Very small objects are passed right-justified. Everything else is
4497 // passed left-justified.
4498 if (Size==1 || Size==2) {
4499 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4500 if (GPR_idx != NumGPRs) {
4501 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4502 MachinePointerInfo(), VT,
4504 MemOpChains.push_back(Load.getValue(1));
4505 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4507 ArgOffset += PtrByteSize;
4509 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4510 PtrOff.getValueType());
4511 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4512 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4515 ArgOffset += PtrByteSize;
4519 // Copy entire object into memory. There are cases where gcc-generated
4520 // code assumes it is there, even if it could be put entirely into
4521 // registers. (This is not what the doc says.)
4522 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4526 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4527 // copy the pieces of the object that fit into registers from the
4528 // parameter save area.
4529 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4530 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4531 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4532 if (GPR_idx != NumGPRs) {
4533 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4534 MachinePointerInfo(),
4535 false, false, false, 0);
4536 MemOpChains.push_back(Load.getValue(1));
4537 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4538 ArgOffset += PtrByteSize;
4540 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4547 switch (Arg.getSimpleValueType().SimpleTy) {
4548 default: llvm_unreachable("Unexpected ValueType for argument!");
4552 if (GPR_idx != NumGPRs) {
4553 if (Arg.getValueType() == MVT::i1)
4554 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4556 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4558 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4559 isPPC64, isTailCall, false, MemOpChains,
4560 TailCallArguments, dl);
4562 ArgOffset += PtrByteSize;
4566 if (FPR_idx != NumFPRs) {
4567 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4570 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4571 MachinePointerInfo(), false, false, 0);
4572 MemOpChains.push_back(Store);
4574 // Float varargs are always shadowed in available integer registers
4575 if (GPR_idx != NumGPRs) {
4576 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4577 MachinePointerInfo(), false, false,
4579 MemOpChains.push_back(Load.getValue(1));
4580 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4582 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4583 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4584 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4585 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4586 MachinePointerInfo(),
4587 false, false, false, 0);
4588 MemOpChains.push_back(Load.getValue(1));
4589 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4592 // If we have any FPRs remaining, we may also have GPRs remaining.
4593 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4595 if (GPR_idx != NumGPRs)
4597 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4598 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4602 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4603 isPPC64, isTailCall, false, MemOpChains,
4604 TailCallArguments, dl);
4608 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4615 // These go aligned on the stack, or in the corresponding R registers
4616 // when within range. The Darwin PPC ABI doc claims they also go in
4617 // V registers; in fact gcc does this only for arguments that are
4618 // prototyped, not for those that match the ... We do it for all
4619 // arguments, seems to work.
4620 while (ArgOffset % 16 !=0) {
4621 ArgOffset += PtrByteSize;
4622 if (GPR_idx != NumGPRs)
4625 // We could elide this store in the case where the object fits
4626 // entirely in R registers. Maybe later.
4627 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4628 DAG.getConstant(ArgOffset, PtrVT));
4629 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4630 MachinePointerInfo(), false, false, 0);
4631 MemOpChains.push_back(Store);
4632 if (VR_idx != NumVRs) {
4633 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4634 MachinePointerInfo(),
4635 false, false, false, 0);
4636 MemOpChains.push_back(Load.getValue(1));
4637 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4640 for (unsigned i=0; i<16; i+=PtrByteSize) {
4641 if (GPR_idx == NumGPRs)
4643 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4644 DAG.getConstant(i, PtrVT));
4645 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4646 false, false, false, 0);
4647 MemOpChains.push_back(Load.getValue(1));
4648 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4653 // Non-varargs Altivec params generally go in registers, but have
4654 // stack space allocated at the end.
4655 if (VR_idx != NumVRs) {
4656 // Doesn't have GPR space allocated.
4657 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4658 } else if (nAltivecParamsAtEnd==0) {
4659 // We are emitting Altivec params in order.
4660 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4661 isPPC64, isTailCall, true, MemOpChains,
4662 TailCallArguments, dl);
4668 // If all Altivec parameters fit in registers, as they usually do,
4669 // they get stack space following the non-Altivec parameters. We
4670 // don't track this here because nobody below needs it.
4671 // If there are more Altivec parameters than fit in registers emit
4673 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4675 // Offset is aligned; skip 1st 12 params which go in V registers.
4676 ArgOffset = ((ArgOffset+15)/16)*16;
4678 for (unsigned i = 0; i != NumOps; ++i) {
4679 SDValue Arg = OutVals[i];
4680 EVT ArgType = Outs[i].VT;
4681 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4682 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4685 // We are emitting Altivec params in order.
4686 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4687 isPPC64, isTailCall, true, MemOpChains,
4688 TailCallArguments, dl);
4695 if (!MemOpChains.empty())
4696 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4698 // On Darwin, R12 must contain the address of an indirect callee. This does
4699 // not mean the MTCTR instruction must use R12; it's easier to model this as
4700 // an extra parameter, so do that.
4702 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4703 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4704 !isBLACompatibleAddress(Callee, DAG))
4705 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4706 PPC::R12), Callee));
4708 // Build a sequence of copy-to-reg nodes chained together with token chain
4709 // and flag operands which copy the outgoing args into the appropriate regs.
4711 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4712 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4713 RegsToPass[i].second, InFlag);
4714 InFlag = Chain.getValue(1);
4718 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4719 FPOp, true, TailCallArguments);
4721 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4722 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4727 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4728 MachineFunction &MF, bool isVarArg,
4729 const SmallVectorImpl<ISD::OutputArg> &Outs,
4730 LLVMContext &Context) const {
4731 SmallVector<CCValAssign, 16> RVLocs;
4732 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4734 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4738 PPCTargetLowering::LowerReturn(SDValue Chain,
4739 CallingConv::ID CallConv, bool isVarArg,
4740 const SmallVectorImpl<ISD::OutputArg> &Outs,
4741 const SmallVectorImpl<SDValue> &OutVals,
4742 SDLoc dl, SelectionDAG &DAG) const {
4744 SmallVector<CCValAssign, 16> RVLocs;
4745 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4746 getTargetMachine(), RVLocs, *DAG.getContext());
4747 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4750 SmallVector<SDValue, 4> RetOps(1, Chain);
4752 // Copy the result values into the output registers.
4753 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4754 CCValAssign &VA = RVLocs[i];
4755 assert(VA.isRegLoc() && "Can only return in registers!");
4757 SDValue Arg = OutVals[i];
4759 switch (VA.getLocInfo()) {
4760 default: llvm_unreachable("Unknown loc info!");
4761 case CCValAssign::Full: break;
4762 case CCValAssign::AExt:
4763 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4765 case CCValAssign::ZExt:
4766 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4768 case CCValAssign::SExt:
4769 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4773 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4774 Flag = Chain.getValue(1);
4775 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4778 RetOps[0] = Chain; // Update chain.
4780 // Add the flag if we have it.
4782 RetOps.push_back(Flag);
4784 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
4787 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4788 const PPCSubtarget &Subtarget) const {
4789 // When we pop the dynamic allocation we need to restore the SP link.
4792 // Get the corect type for pointers.
4793 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4795 // Construct the stack pointer operand.
4796 bool isPPC64 = Subtarget.isPPC64();
4797 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4798 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4800 // Get the operands for the STACKRESTORE.
4801 SDValue Chain = Op.getOperand(0);
4802 SDValue SaveSP = Op.getOperand(1);
4804 // Load the old link SP.
4805 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4806 MachinePointerInfo(),
4807 false, false, false, 0);
4809 // Restore the stack pointer.
4810 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4812 // Store the old link SP.
4813 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4820 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4821 MachineFunction &MF = DAG.getMachineFunction();
4822 bool isPPC64 = PPCSubTarget.isPPC64();
4823 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4824 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4826 // Get current frame pointer save index. The users of this index will be
4827 // primarily DYNALLOC instructions.
4828 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4829 int RASI = FI->getReturnAddrSaveIndex();
4831 // If the frame pointer save index hasn't been defined yet.
4833 // Find out what the fix offset of the frame pointer save area.
4834 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4835 // Allocate the frame index for frame pointer save area.
4836 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4838 FI->setReturnAddrSaveIndex(RASI);
4840 return DAG.getFrameIndex(RASI, PtrVT);
4844 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4845 MachineFunction &MF = DAG.getMachineFunction();
4846 bool isPPC64 = PPCSubTarget.isPPC64();
4847 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4848 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4850 // Get current frame pointer save index. The users of this index will be
4851 // primarily DYNALLOC instructions.
4852 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4853 int FPSI = FI->getFramePointerSaveIndex();
4855 // If the frame pointer save index hasn't been defined yet.
4857 // Find out what the fix offset of the frame pointer save area.
4858 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4861 // Allocate the frame index for frame pointer save area.
4862 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4864 FI->setFramePointerSaveIndex(FPSI);
4866 return DAG.getFrameIndex(FPSI, PtrVT);
4869 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4871 const PPCSubtarget &Subtarget) const {
4873 SDValue Chain = Op.getOperand(0);
4874 SDValue Size = Op.getOperand(1);
4877 // Get the corect type for pointers.
4878 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4880 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4881 DAG.getConstant(0, PtrVT), Size);
4882 // Construct a node for the frame pointer save index.
4883 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4884 // Build a DYNALLOC node.
4885 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4886 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4887 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
4890 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4891 SelectionDAG &DAG) const {
4893 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4894 DAG.getVTList(MVT::i32, MVT::Other),
4895 Op.getOperand(0), Op.getOperand(1));
4898 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4899 SelectionDAG &DAG) const {
4901 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4902 Op.getOperand(0), Op.getOperand(1));
4905 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4906 assert(Op.getValueType() == MVT::i1 &&
4907 "Custom lowering only for i1 loads");
4909 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4912 LoadSDNode *LD = cast<LoadSDNode>(Op);
4914 SDValue Chain = LD->getChain();
4915 SDValue BasePtr = LD->getBasePtr();
4916 MachineMemOperand *MMO = LD->getMemOperand();
4918 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4919 BasePtr, MVT::i8, MMO);
4920 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4922 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4923 return DAG.getMergeValues(Ops, dl);
4926 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4927 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4928 "Custom lowering only for i1 stores");
4930 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4933 StoreSDNode *ST = cast<StoreSDNode>(Op);
4935 SDValue Chain = ST->getChain();
4936 SDValue BasePtr = ST->getBasePtr();
4937 SDValue Value = ST->getValue();
4938 MachineMemOperand *MMO = ST->getMemOperand();
4940 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4941 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4944 // FIXME: Remove this once the ANDI glue bug is fixed:
4945 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4946 assert(Op.getValueType() == MVT::i1 &&
4947 "Custom lowering only for i1 results");
4950 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4954 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4956 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4957 // Not FP? Not a fsel.
4958 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4959 !Op.getOperand(2).getValueType().isFloatingPoint())
4962 // We might be able to do better than this under some circumstances, but in
4963 // general, fsel-based lowering of select is a finite-math-only optimization.
4964 // For more information, see section F.3 of the 2.06 ISA specification.
4965 if (!DAG.getTarget().Options.NoInfsFPMath ||
4966 !DAG.getTarget().Options.NoNaNsFPMath)
4969 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4971 EVT ResVT = Op.getValueType();
4972 EVT CmpVT = Op.getOperand(0).getValueType();
4973 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4974 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4977 // If the RHS of the comparison is a 0.0, we don't need to do the
4978 // subtraction at all.
4980 if (isFloatingPointZero(RHS))
4982 default: break; // SETUO etc aren't handled by fsel.
4986 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4987 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4988 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4989 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4990 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4991 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4992 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4995 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4998 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4999 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5000 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5003 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5006 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5007 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5008 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5009 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5014 default: break; // SETUO etc aren't handled by fsel.
5018 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5019 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5020 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5021 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5022 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5023 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5024 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5025 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5028 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5029 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5030 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5031 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5034 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5035 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5036 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5037 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5040 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5041 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5042 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5043 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5046 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5047 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5048 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5049 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5054 // FIXME: Split this code up when LegalizeDAGTypes lands.
5055 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5057 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5058 SDValue Src = Op.getOperand(0);
5059 if (Src.getValueType() == MVT::f32)
5060 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5063 switch (Op.getSimpleValueType().SimpleTy) {
5064 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5066 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5067 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5072 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
5073 "i64 FP_TO_UINT is supported only with FPCVT");
5074 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5080 // Convert the FP value to an int value through memory.
5081 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
5082 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
5083 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5084 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5085 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5087 // Emit a store to the stack slot.
5090 MachineFunction &MF = DAG.getMachineFunction();
5091 MachineMemOperand *MMO =
5092 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5093 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5094 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5095 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5097 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5098 MPI, false, false, 0);
5100 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5102 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5103 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5104 DAG.getConstant(4, FIPtr.getValueType()));
5105 MPI = MachinePointerInfo();
5108 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5109 false, false, false, 0);
5112 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5113 SelectionDAG &DAG) const {
5115 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5116 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5119 if (Op.getOperand(0).getValueType() == MVT::i1)
5120 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5121 DAG.getConstantFP(1.0, Op.getValueType()),
5122 DAG.getConstantFP(0.0, Op.getValueType()));
5124 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
5125 "UINT_TO_FP is supported only with FPCVT");
5127 // If we have FCFIDS, then use it when converting to single-precision.
5128 // Otherwise, convert to double-precision and then round.
5129 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5130 (Op.getOpcode() == ISD::UINT_TO_FP ?
5131 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5132 (Op.getOpcode() == ISD::UINT_TO_FP ?
5133 PPCISD::FCFIDU : PPCISD::FCFID);
5134 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5135 MVT::f32 : MVT::f64;
5137 if (Op.getOperand(0).getValueType() == MVT::i64) {
5138 SDValue SINT = Op.getOperand(0);
5139 // When converting to single-precision, we actually need to convert
5140 // to double-precision first and then round to single-precision.
5141 // To avoid double-rounding effects during that operation, we have
5142 // to prepare the input operand. Bits that might be truncated when
5143 // converting to double-precision are replaced by a bit that won't
5144 // be lost at this stage, but is below the single-precision rounding
5147 // However, if -enable-unsafe-fp-math is in effect, accept double
5148 // rounding to avoid the extra overhead.
5149 if (Op.getValueType() == MVT::f32 &&
5150 !PPCSubTarget.hasFPCVT() &&
5151 !DAG.getTarget().Options.UnsafeFPMath) {
5153 // Twiddle input to make sure the low 11 bits are zero. (If this
5154 // is the case, we are guaranteed the value will fit into the 53 bit
5155 // mantissa of an IEEE double-precision value without rounding.)
5156 // If any of those low 11 bits were not zero originally, make sure
5157 // bit 12 (value 2048) is set instead, so that the final rounding
5158 // to single-precision gets the correct result.
5159 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5160 SINT, DAG.getConstant(2047, MVT::i64));
5161 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5162 Round, DAG.getConstant(2047, MVT::i64));
5163 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5164 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5165 Round, DAG.getConstant(-2048, MVT::i64));
5167 // However, we cannot use that value unconditionally: if the magnitude
5168 // of the input value is small, the bit-twiddling we did above might
5169 // end up visibly changing the output. Fortunately, in that case, we
5170 // don't need to twiddle bits since the original input will convert
5171 // exactly to double-precision floating-point already. Therefore,
5172 // construct a conditional to use the original value if the top 11
5173 // bits are all sign-bit copies, and use the rounded value computed
5175 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5176 SINT, DAG.getConstant(53, MVT::i32));
5177 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5178 Cond, DAG.getConstant(1, MVT::i64));
5179 Cond = DAG.getSetCC(dl, MVT::i32,
5180 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5182 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5185 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5186 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5188 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5189 FP = DAG.getNode(ISD::FP_ROUND, dl,
5190 MVT::f32, FP, DAG.getIntPtrConstant(0));
5194 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5195 "Unhandled INT_TO_FP type in custom expander!");
5196 // Since we only generate this in 64-bit mode, we can take advantage of
5197 // 64-bit registers. In particular, sign extend the input value into the
5198 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5199 // then lfd it and fcfid it.
5200 MachineFunction &MF = DAG.getMachineFunction();
5201 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5202 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5205 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5206 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5207 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5209 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5210 MachinePointerInfo::getFixedStack(FrameIdx),
5213 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5214 "Expected an i32 store");
5215 MachineMemOperand *MMO =
5216 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5217 MachineMemOperand::MOLoad, 4, 4);
5218 SDValue Ops[] = { Store, FIdx };
5219 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5220 PPCISD::LFIWZX : PPCISD::LFIWAX,
5221 dl, DAG.getVTList(MVT::f64, MVT::Other),
5222 Ops, MVT::i32, MMO);
5224 assert(PPCSubTarget.isPPC64() &&
5225 "i32->FP without LFIWAX supported only on PPC64");
5227 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5228 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5230 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5233 // STD the extended value into the stack slot.
5234 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5235 MachinePointerInfo::getFixedStack(FrameIdx),
5238 // Load the value as a double.
5239 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5240 MachinePointerInfo::getFixedStack(FrameIdx),
5241 false, false, false, 0);
5244 // FCFID it and return it.
5245 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5246 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5247 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5251 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5252 SelectionDAG &DAG) const {
5255 The rounding mode is in bits 30:31 of FPSR, and has the following
5262 FLT_ROUNDS, on the other hand, expects the following:
5269 To perform the conversion, we do:
5270 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5273 MachineFunction &MF = DAG.getMachineFunction();
5274 EVT VT = Op.getValueType();
5275 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5277 // Save FP Control Word to register
5279 MVT::f64, // return register
5280 MVT::Glue // unused in this context
5282 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5284 // Save FP register to stack slot
5285 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5286 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5287 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5288 StackSlot, MachinePointerInfo(), false, false,0);
5290 // Load FP Control Word from low 32 bits of stack slot.
5291 SDValue Four = DAG.getConstant(4, PtrVT);
5292 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5293 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5294 false, false, false, 0);
5296 // Transform as necessary
5298 DAG.getNode(ISD::AND, dl, MVT::i32,
5299 CWD, DAG.getConstant(3, MVT::i32));
5301 DAG.getNode(ISD::SRL, dl, MVT::i32,
5302 DAG.getNode(ISD::AND, dl, MVT::i32,
5303 DAG.getNode(ISD::XOR, dl, MVT::i32,
5304 CWD, DAG.getConstant(3, MVT::i32)),
5305 DAG.getConstant(3, MVT::i32)),
5306 DAG.getConstant(1, MVT::i32));
5309 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5311 return DAG.getNode((VT.getSizeInBits() < 16 ?
5312 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5315 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5316 EVT VT = Op.getValueType();
5317 unsigned BitWidth = VT.getSizeInBits();
5319 assert(Op.getNumOperands() == 3 &&
5320 VT == Op.getOperand(1).getValueType() &&
5323 // Expand into a bunch of logical ops. Note that these ops
5324 // depend on the PPC behavior for oversized shift amounts.
5325 SDValue Lo = Op.getOperand(0);
5326 SDValue Hi = Op.getOperand(1);
5327 SDValue Amt = Op.getOperand(2);
5328 EVT AmtVT = Amt.getValueType();
5330 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5331 DAG.getConstant(BitWidth, AmtVT), Amt);
5332 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5333 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5334 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5335 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5336 DAG.getConstant(-BitWidth, AmtVT));
5337 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5338 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5339 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5340 SDValue OutOps[] = { OutLo, OutHi };
5341 return DAG.getMergeValues(OutOps, dl);
5344 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5345 EVT VT = Op.getValueType();
5347 unsigned BitWidth = VT.getSizeInBits();
5348 assert(Op.getNumOperands() == 3 &&
5349 VT == Op.getOperand(1).getValueType() &&
5352 // Expand into a bunch of logical ops. Note that these ops
5353 // depend on the PPC behavior for oversized shift amounts.
5354 SDValue Lo = Op.getOperand(0);
5355 SDValue Hi = Op.getOperand(1);
5356 SDValue Amt = Op.getOperand(2);
5357 EVT AmtVT = Amt.getValueType();
5359 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5360 DAG.getConstant(BitWidth, AmtVT), Amt);
5361 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5362 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5363 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5364 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5365 DAG.getConstant(-BitWidth, AmtVT));
5366 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5367 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5368 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5369 SDValue OutOps[] = { OutLo, OutHi };
5370 return DAG.getMergeValues(OutOps, dl);
5373 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5375 EVT VT = Op.getValueType();
5376 unsigned BitWidth = VT.getSizeInBits();
5377 assert(Op.getNumOperands() == 3 &&
5378 VT == Op.getOperand(1).getValueType() &&
5381 // Expand into a bunch of logical ops, followed by a select_cc.
5382 SDValue Lo = Op.getOperand(0);
5383 SDValue Hi = Op.getOperand(1);
5384 SDValue Amt = Op.getOperand(2);
5385 EVT AmtVT = Amt.getValueType();
5387 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5388 DAG.getConstant(BitWidth, AmtVT), Amt);
5389 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5390 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5391 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5392 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5393 DAG.getConstant(-BitWidth, AmtVT));
5394 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5395 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5396 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5397 Tmp4, Tmp6, ISD::SETLE);
5398 SDValue OutOps[] = { OutLo, OutHi };
5399 return DAG.getMergeValues(OutOps, dl);
5402 //===----------------------------------------------------------------------===//
5403 // Vector related lowering.
5406 /// BuildSplatI - Build a canonical splati of Val with an element size of
5407 /// SplatSize. Cast the result to VT.
5408 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5409 SelectionDAG &DAG, SDLoc dl) {
5410 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5412 static const EVT VTys[] = { // canonical VT to use for each size.
5413 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5416 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5418 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5422 EVT CanonicalVT = VTys[SplatSize-1];
5424 // Build a canonical splat for this value.
5425 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5426 SmallVector<SDValue, 8> Ops;
5427 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5428 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5429 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5432 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5433 /// specified intrinsic ID.
5434 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5435 SelectionDAG &DAG, SDLoc dl,
5436 EVT DestVT = MVT::Other) {
5437 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5438 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5439 DAG.getConstant(IID, MVT::i32), Op);
5442 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5443 /// specified intrinsic ID.
5444 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5445 SelectionDAG &DAG, SDLoc dl,
5446 EVT DestVT = MVT::Other) {
5447 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5448 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5449 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5452 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5453 /// specified intrinsic ID.
5454 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5455 SDValue Op2, SelectionDAG &DAG,
5456 SDLoc dl, EVT DestVT = MVT::Other) {
5457 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5458 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5459 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5463 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5464 /// amount. The result has the specified value type.
5465 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5466 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5467 // Force LHS/RHS to be the right type.
5468 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5469 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5472 for (unsigned i = 0; i != 16; ++i)
5474 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5475 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5478 // If this is a case we can't handle, return null and let the default
5479 // expansion code take care of it. If we CAN select this case, and if it
5480 // selects to a single instruction, return Op. Otherwise, if we can codegen
5481 // this case more efficiently than a constant pool load, lower it to the
5482 // sequence of ops that should be used.
5483 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5484 SelectionDAG &DAG) const {
5486 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5487 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5489 // Check if this is a splat of a constant value.
5490 APInt APSplatBits, APSplatUndef;
5491 unsigned SplatBitSize;
5493 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5494 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5497 unsigned SplatBits = APSplatBits.getZExtValue();
5498 unsigned SplatUndef = APSplatUndef.getZExtValue();
5499 unsigned SplatSize = SplatBitSize / 8;
5501 // First, handle single instruction cases.
5504 if (SplatBits == 0) {
5505 // Canonicalize all zero vectors to be v4i32.
5506 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5507 SDValue Z = DAG.getConstant(0, MVT::i32);
5508 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5509 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5514 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5515 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5517 if (SextVal >= -16 && SextVal <= 15)
5518 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5521 // Two instruction sequences.
5523 // If this value is in the range [-32,30] and is even, use:
5524 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5525 // If this value is in the range [17,31] and is odd, use:
5526 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5527 // If this value is in the range [-31,-17] and is odd, use:
5528 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5529 // Note the last two are three-instruction sequences.
5530 if (SextVal >= -32 && SextVal <= 31) {
5531 // To avoid having these optimizations undone by constant folding,
5532 // we convert to a pseudo that will be expanded later into one of
5534 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5535 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5536 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5537 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5538 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5539 if (VT == Op.getValueType())
5542 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5545 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5546 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5548 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5549 // Make -1 and vspltisw -1:
5550 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5552 // Make the VSLW intrinsic, computing 0x8000_0000.
5553 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5556 // xor by OnesV to invert it.
5557 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5558 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5561 // The remaining cases assume either big endian element order or
5562 // a splat-size that equates to the element size of the vector
5563 // to be built. An example that doesn't work for little endian is
5564 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5565 // and a vector element size of 16 bits. The code below will
5566 // produce the vector in big endian element order, which for little
5567 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5569 // For now, just avoid these optimizations in that case.
5570 // FIXME: Develop correct optimizations for LE with mismatched
5571 // splat and element sizes.
5573 if (PPCSubTarget.isLittleEndian() &&
5574 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5577 // Check to see if this is a wide variety of vsplti*, binop self cases.
5578 static const signed char SplatCsts[] = {
5579 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5580 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5583 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5584 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5585 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5586 int i = SplatCsts[idx];
5588 // Figure out what shift amount will be used by altivec if shifted by i in
5590 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5592 // vsplti + shl self.
5593 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5594 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5595 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5596 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5597 Intrinsic::ppc_altivec_vslw
5599 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5600 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5603 // vsplti + srl self.
5604 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5605 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5606 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5607 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5608 Intrinsic::ppc_altivec_vsrw
5610 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5611 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5614 // vsplti + sra self.
5615 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5616 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5617 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5618 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5619 Intrinsic::ppc_altivec_vsraw
5621 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5622 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5625 // vsplti + rol self.
5626 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5627 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5628 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5629 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5630 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5631 Intrinsic::ppc_altivec_vrlw
5633 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5634 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5637 // t = vsplti c, result = vsldoi t, t, 1
5638 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5639 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5640 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5642 // t = vsplti c, result = vsldoi t, t, 2
5643 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5644 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5645 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5647 // t = vsplti c, result = vsldoi t, t, 3
5648 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5649 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5650 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5657 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5658 /// the specified operations to build the shuffle.
5659 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5660 SDValue RHS, SelectionDAG &DAG,
5662 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5663 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5664 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5667 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5679 if (OpNum == OP_COPY) {
5680 if (LHSID == (1*9+2)*9+3) return LHS;
5681 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5685 SDValue OpLHS, OpRHS;
5686 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5687 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5691 default: llvm_unreachable("Unknown i32 permute!");
5693 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5694 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5695 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5696 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5699 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5700 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5701 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5702 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5705 for (unsigned i = 0; i != 16; ++i)
5706 ShufIdxs[i] = (i&3)+0;
5709 for (unsigned i = 0; i != 16; ++i)
5710 ShufIdxs[i] = (i&3)+4;
5713 for (unsigned i = 0; i != 16; ++i)
5714 ShufIdxs[i] = (i&3)+8;
5717 for (unsigned i = 0; i != 16; ++i)
5718 ShufIdxs[i] = (i&3)+12;
5721 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5723 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5725 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5727 EVT VT = OpLHS.getValueType();
5728 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5729 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5730 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5731 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5734 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5735 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5736 /// return the code it can be lowered into. Worst case, it can always be
5737 /// lowered into a vperm.
5738 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5739 SelectionDAG &DAG) const {
5741 SDValue V1 = Op.getOperand(0);
5742 SDValue V2 = Op.getOperand(1);
5743 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5744 EVT VT = Op.getValueType();
5746 // Cases that are handled by instructions that take permute immediates
5747 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5748 // selected by the instruction selector.
5749 if (V2.getOpcode() == ISD::UNDEF) {
5750 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5751 PPC::isSplatShuffleMask(SVOp, 2) ||
5752 PPC::isSplatShuffleMask(SVOp, 4) ||
5753 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5754 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5755 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5756 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5757 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5758 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5759 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5760 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5761 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5766 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5767 // and produce a fixed permutation. If any of these match, do not lower to
5769 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5770 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5771 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5772 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5773 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5774 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5775 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5776 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5777 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5780 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5781 // perfect shuffle table to emit an optimal matching sequence.
5782 ArrayRef<int> PermMask = SVOp->getMask();
5784 unsigned PFIndexes[4];
5785 bool isFourElementShuffle = true;
5786 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5787 unsigned EltNo = 8; // Start out undef.
5788 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5789 if (PermMask[i*4+j] < 0)
5790 continue; // Undef, ignore it.
5792 unsigned ByteSource = PermMask[i*4+j];
5793 if ((ByteSource & 3) != j) {
5794 isFourElementShuffle = false;
5799 EltNo = ByteSource/4;
5800 } else if (EltNo != ByteSource/4) {
5801 isFourElementShuffle = false;
5805 PFIndexes[i] = EltNo;
5808 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5809 // perfect shuffle vector to determine if it is cost effective to do this as
5810 // discrete instructions, or whether we should use a vperm.
5811 if (isFourElementShuffle) {
5812 // Compute the index in the perfect shuffle table.
5813 unsigned PFTableIndex =
5814 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5816 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5817 unsigned Cost = (PFEntry >> 30);
5819 // Determining when to avoid vperm is tricky. Many things affect the cost
5820 // of vperm, particularly how many times the perm mask needs to be computed.
5821 // For example, if the perm mask can be hoisted out of a loop or is already
5822 // used (perhaps because there are multiple permutes with the same shuffle
5823 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5824 // the loop requires an extra register.
5826 // As a compromise, we only emit discrete instructions if the shuffle can be
5827 // generated in 3 or fewer operations. When we have loop information
5828 // available, if this block is within a loop, we should avoid using vperm
5829 // for 3-operation perms and use a constant pool load instead.
5831 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5834 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5835 // vector that will get spilled to the constant pool.
5836 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5838 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5839 // that it is in input element units, not in bytes. Convert now.
5841 // For little endian, the order of the input vectors is reversed, and
5842 // the permutation mask is complemented with respect to 31. This is
5843 // necessary to produce proper semantics with the big-endian-biased vperm
5845 EVT EltVT = V1.getValueType().getVectorElementType();
5846 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5847 bool isLittleEndian = PPCSubTarget.isLittleEndian();
5849 SmallVector<SDValue, 16> ResultMask;
5850 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5851 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5853 for (unsigned j = 0; j != BytesPerElement; ++j)
5855 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
5858 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5862 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5865 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
5868 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
5872 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5873 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5874 /// information about the intrinsic.
5875 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5877 unsigned IntrinsicID =
5878 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5881 switch (IntrinsicID) {
5882 default: return false;
5883 // Comparison predicates.
5884 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5885 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5886 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5887 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5888 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5889 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5890 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5891 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5892 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5893 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5894 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5895 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5896 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5898 // Normal Comparisons.
5899 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5900 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5901 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5902 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5903 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5904 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5905 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5906 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5907 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5908 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5909 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5910 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5911 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5916 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5917 /// lower, do it, otherwise return null.
5918 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5919 SelectionDAG &DAG) const {
5920 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5921 // opcode number of the comparison.
5925 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5926 return SDValue(); // Don't custom lower most intrinsics.
5928 // If this is a non-dot comparison, make the VCMP node and we are done.
5930 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5931 Op.getOperand(1), Op.getOperand(2),
5932 DAG.getConstant(CompareOpc, MVT::i32));
5933 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5936 // Create the PPCISD altivec 'dot' comparison node.
5938 Op.getOperand(2), // LHS
5939 Op.getOperand(3), // RHS
5940 DAG.getConstant(CompareOpc, MVT::i32)
5942 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5943 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
5945 // Now that we have the comparison, emit a copy from the CR to a GPR.
5946 // This is flagged to the above dot comparison.
5947 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5948 DAG.getRegister(PPC::CR6, MVT::i32),
5949 CompNode.getValue(1));
5951 // Unpack the result based on how the target uses it.
5952 unsigned BitNo; // Bit # of CR6.
5953 bool InvertBit; // Invert result?
5954 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5955 default: // Can't happen, don't crash on invalid number though.
5956 case 0: // Return the value of the EQ bit of CR6.
5957 BitNo = 0; InvertBit = false;
5959 case 1: // Return the inverted value of the EQ bit of CR6.
5960 BitNo = 0; InvertBit = true;
5962 case 2: // Return the value of the LT bit of CR6.
5963 BitNo = 2; InvertBit = false;
5965 case 3: // Return the inverted value of the LT bit of CR6.
5966 BitNo = 2; InvertBit = true;
5970 // Shift the bit into the low position.
5971 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5972 DAG.getConstant(8-(3-BitNo), MVT::i32));
5974 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5975 DAG.getConstant(1, MVT::i32));
5977 // If we are supposed to, toggle the bit.
5979 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5980 DAG.getConstant(1, MVT::i32));
5984 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
5985 SelectionDAG &DAG) const {
5987 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
5988 // instructions), but for smaller types, we need to first extend up to v2i32
5989 // before doing going farther.
5990 if (Op.getValueType() == MVT::v2i64) {
5991 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5992 if (ExtVT != MVT::v2i32) {
5993 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
5994 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
5995 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
5996 ExtVT.getVectorElementType(), 4)));
5997 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
5998 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
5999 DAG.getValueType(MVT::v2i32));
6008 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6009 SelectionDAG &DAG) const {
6011 // Create a stack slot that is 16-byte aligned.
6012 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6013 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6014 EVT PtrVT = getPointerTy();
6015 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6017 // Store the input value into Value#0 of the stack slot.
6018 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6019 Op.getOperand(0), FIdx, MachinePointerInfo(),
6022 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6023 false, false, false, 0);
6026 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6028 if (Op.getValueType() == MVT::v4i32) {
6029 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6031 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6032 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6034 SDValue RHSSwap = // = vrlw RHS, 16
6035 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6037 // Shrinkify inputs to v8i16.
6038 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6039 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6040 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6042 // Low parts multiplied together, generating 32-bit results (we ignore the
6044 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6045 LHS, RHS, DAG, dl, MVT::v4i32);
6047 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6048 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6049 // Shift the high parts up 16 bits.
6050 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6052 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6053 } else if (Op.getValueType() == MVT::v8i16) {
6054 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6056 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6058 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6059 LHS, RHS, Zero, DAG, dl);
6060 } else if (Op.getValueType() == MVT::v16i8) {
6061 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6063 // Multiply the even 8-bit parts, producing 16-bit sums.
6064 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6065 LHS, RHS, DAG, dl, MVT::v8i16);
6066 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6068 // Multiply the odd 8-bit parts, producing 16-bit sums.
6069 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6070 LHS, RHS, DAG, dl, MVT::v8i16);
6071 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6073 // Merge the results together.
6075 for (unsigned i = 0; i != 8; ++i) {
6077 Ops[i*2+1] = 2*i+1+16;
6079 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6081 llvm_unreachable("Unknown mul to lower!");
6085 /// LowerOperation - Provide custom lowering hooks for some operations.
6087 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6088 switch (Op.getOpcode()) {
6089 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6090 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6091 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6092 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6093 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6094 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6095 case ISD::SETCC: return LowerSETCC(Op, DAG);
6096 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6097 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6099 return LowerVASTART(Op, DAG, PPCSubTarget);
6102 return LowerVAARG(Op, DAG, PPCSubTarget);
6105 return LowerVACOPY(Op, DAG, PPCSubTarget);
6107 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
6108 case ISD::DYNAMIC_STACKALLOC:
6109 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
6111 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6112 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6114 case ISD::LOAD: return LowerLOAD(Op, DAG);
6115 case ISD::STORE: return LowerSTORE(Op, DAG);
6116 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6117 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6118 case ISD::FP_TO_UINT:
6119 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6121 case ISD::UINT_TO_FP:
6122 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6123 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6125 // Lower 64-bit shifts.
6126 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6127 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6128 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6130 // Vector-related lowering.
6131 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6132 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6133 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6134 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6135 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6136 case ISD::MUL: return LowerMUL(Op, DAG);
6138 // For counter-based loop handling.
6139 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6141 // Frame & Return address.
6142 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6143 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6147 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6148 SmallVectorImpl<SDValue>&Results,
6149 SelectionDAG &DAG) const {
6150 const TargetMachine &TM = getTargetMachine();
6152 switch (N->getOpcode()) {
6154 llvm_unreachable("Do not know how to custom type legalize this operation!");
6155 case ISD::INTRINSIC_W_CHAIN: {
6156 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6157 Intrinsic::ppc_is_decremented_ctr_nonzero)
6160 assert(N->getValueType(0) == MVT::i1 &&
6161 "Unexpected result type for CTR decrement intrinsic");
6162 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6163 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6164 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6167 Results.push_back(NewInt);
6168 Results.push_back(NewInt.getValue(1));
6172 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6173 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6176 EVT VT = N->getValueType(0);
6178 if (VT == MVT::i64) {
6179 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
6181 Results.push_back(NewNode);
6182 Results.push_back(NewNode.getValue(1));
6186 case ISD::FP_ROUND_INREG: {
6187 assert(N->getValueType(0) == MVT::ppcf128);
6188 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6189 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6190 MVT::f64, N->getOperand(0),
6191 DAG.getIntPtrConstant(0));
6192 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6193 MVT::f64, N->getOperand(0),
6194 DAG.getIntPtrConstant(1));
6196 // Add the two halves of the long double in round-to-zero mode.
6197 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6199 // We know the low half is about to be thrown away, so just use something
6201 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6205 case ISD::FP_TO_SINT:
6206 // LowerFP_TO_INT() can only handle f32 and f64.
6207 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6209 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6215 //===----------------------------------------------------------------------===//
6216 // Other Lowering Code
6217 //===----------------------------------------------------------------------===//
6220 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6221 bool is64bit, unsigned BinOpcode) const {
6222 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6223 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6225 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6226 MachineFunction *F = BB->getParent();
6227 MachineFunction::iterator It = BB;
6230 unsigned dest = MI->getOperand(0).getReg();
6231 unsigned ptrA = MI->getOperand(1).getReg();
6232 unsigned ptrB = MI->getOperand(2).getReg();
6233 unsigned incr = MI->getOperand(3).getReg();
6234 DebugLoc dl = MI->getDebugLoc();
6236 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6237 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6238 F->insert(It, loopMBB);
6239 F->insert(It, exitMBB);
6240 exitMBB->splice(exitMBB->begin(), BB,
6241 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6242 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6244 MachineRegisterInfo &RegInfo = F->getRegInfo();
6245 unsigned TmpReg = (!BinOpcode) ? incr :
6246 RegInfo.createVirtualRegister(
6247 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6248 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6252 // fallthrough --> loopMBB
6253 BB->addSuccessor(loopMBB);
6256 // l[wd]arx dest, ptr
6257 // add r0, dest, incr
6258 // st[wd]cx. r0, ptr
6260 // fallthrough --> exitMBB
6262 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6263 .addReg(ptrA).addReg(ptrB);
6265 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6266 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6267 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6268 BuildMI(BB, dl, TII->get(PPC::BCC))
6269 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6270 BB->addSuccessor(loopMBB);
6271 BB->addSuccessor(exitMBB);
6280 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6281 MachineBasicBlock *BB,
6282 bool is8bit, // operation
6283 unsigned BinOpcode) const {
6284 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6285 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6286 // In 64 bit mode we have to use 64 bits for addresses, even though the
6287 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6288 // registers without caring whether they're 32 or 64, but here we're
6289 // doing actual arithmetic on the addresses.
6290 bool is64bit = PPCSubTarget.isPPC64();
6291 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6293 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6294 MachineFunction *F = BB->getParent();
6295 MachineFunction::iterator It = BB;
6298 unsigned dest = MI->getOperand(0).getReg();
6299 unsigned ptrA = MI->getOperand(1).getReg();
6300 unsigned ptrB = MI->getOperand(2).getReg();
6301 unsigned incr = MI->getOperand(3).getReg();
6302 DebugLoc dl = MI->getDebugLoc();
6304 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6305 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6306 F->insert(It, loopMBB);
6307 F->insert(It, exitMBB);
6308 exitMBB->splice(exitMBB->begin(), BB,
6309 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6310 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6312 MachineRegisterInfo &RegInfo = F->getRegInfo();
6313 const TargetRegisterClass *RC =
6314 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6315 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6316 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6317 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6318 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6319 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6320 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6321 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6322 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6323 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6324 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6325 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6326 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6328 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6332 // fallthrough --> loopMBB
6333 BB->addSuccessor(loopMBB);
6335 // The 4-byte load must be aligned, while a char or short may be
6336 // anywhere in the word. Hence all this nasty bookkeeping code.
6337 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6338 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6339 // xori shift, shift1, 24 [16]
6340 // rlwinm ptr, ptr1, 0, 0, 29
6341 // slw incr2, incr, shift
6342 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6343 // slw mask, mask2, shift
6345 // lwarx tmpDest, ptr
6346 // add tmp, tmpDest, incr2
6347 // andc tmp2, tmpDest, mask
6348 // and tmp3, tmp, mask
6349 // or tmp4, tmp3, tmp2
6352 // fallthrough --> exitMBB
6353 // srw dest, tmpDest, shift
6354 if (ptrA != ZeroReg) {
6355 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6356 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6357 .addReg(ptrA).addReg(ptrB);
6361 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6362 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6363 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6364 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6366 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6367 .addReg(Ptr1Reg).addImm(0).addImm(61);
6369 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6370 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6371 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6372 .addReg(incr).addReg(ShiftReg);
6374 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6376 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6377 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6379 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6380 .addReg(Mask2Reg).addReg(ShiftReg);
6383 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6384 .addReg(ZeroReg).addReg(PtrReg);
6386 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6387 .addReg(Incr2Reg).addReg(TmpDestReg);
6388 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6389 .addReg(TmpDestReg).addReg(MaskReg);
6390 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6391 .addReg(TmpReg).addReg(MaskReg);
6392 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6393 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6394 BuildMI(BB, dl, TII->get(PPC::STWCX))
6395 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6396 BuildMI(BB, dl, TII->get(PPC::BCC))
6397 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6398 BB->addSuccessor(loopMBB);
6399 BB->addSuccessor(exitMBB);
6404 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6409 llvm::MachineBasicBlock*
6410 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6411 MachineBasicBlock *MBB) const {
6412 DebugLoc DL = MI->getDebugLoc();
6413 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6415 MachineFunction *MF = MBB->getParent();
6416 MachineRegisterInfo &MRI = MF->getRegInfo();
6418 const BasicBlock *BB = MBB->getBasicBlock();
6419 MachineFunction::iterator I = MBB;
6423 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6424 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6426 unsigned DstReg = MI->getOperand(0).getReg();
6427 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6428 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6429 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6430 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6432 MVT PVT = getPointerTy();
6433 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6434 "Invalid Pointer Size!");
6435 // For v = setjmp(buf), we generate
6438 // SjLjSetup mainMBB
6444 // buf[LabelOffset] = LR
6448 // v = phi(main, restore)
6451 MachineBasicBlock *thisMBB = MBB;
6452 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6453 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6454 MF->insert(I, mainMBB);
6455 MF->insert(I, sinkMBB);
6457 MachineInstrBuilder MIB;
6459 // Transfer the remainder of BB and its successor edges to sinkMBB.
6460 sinkMBB->splice(sinkMBB->begin(), MBB,
6461 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6462 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6464 // Note that the structure of the jmp_buf used here is not compatible
6465 // with that used by libc, and is not designed to be. Specifically, it
6466 // stores only those 'reserved' registers that LLVM does not otherwise
6467 // understand how to spill. Also, by convention, by the time this
6468 // intrinsic is called, Clang has already stored the frame address in the
6469 // first slot of the buffer and stack address in the third. Following the
6470 // X86 target code, we'll store the jump address in the second slot. We also
6471 // need to save the TOC pointer (R2) to handle jumps between shared
6472 // libraries, and that will be stored in the fourth slot. The thread
6473 // identifier (R13) is not affected.
6476 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6477 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6478 const int64_t BPOffset = 4 * PVT.getStoreSize();
6480 // Prepare IP either in reg.
6481 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6482 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6483 unsigned BufReg = MI->getOperand(1).getReg();
6485 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6486 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6490 MIB.setMemRefs(MMOBegin, MMOEnd);
6493 // Naked functions never have a base pointer, and so we use r1. For all
6494 // other functions, this decision must be delayed until during PEI.
6496 if (MF->getFunction()->getAttributes().hasAttribute(
6497 AttributeSet::FunctionIndex, Attribute::Naked))
6498 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6500 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6502 MIB = BuildMI(*thisMBB, MI, DL,
6503 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6507 MIB.setMemRefs(MMOBegin, MMOEnd);
6510 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6511 const PPCRegisterInfo *TRI =
6512 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6513 MIB.addRegMask(TRI->getNoPreservedMask());
6515 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6517 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6519 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6521 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6522 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6526 MIB = BuildMI(mainMBB, DL,
6527 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6530 if (PPCSubTarget.isPPC64()) {
6531 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6533 .addImm(LabelOffset)
6536 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6538 .addImm(LabelOffset)
6542 MIB.setMemRefs(MMOBegin, MMOEnd);
6544 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6545 mainMBB->addSuccessor(sinkMBB);
6548 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6549 TII->get(PPC::PHI), DstReg)
6550 .addReg(mainDstReg).addMBB(mainMBB)
6551 .addReg(restoreDstReg).addMBB(thisMBB);
6553 MI->eraseFromParent();
6558 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6559 MachineBasicBlock *MBB) const {
6560 DebugLoc DL = MI->getDebugLoc();
6561 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6563 MachineFunction *MF = MBB->getParent();
6564 MachineRegisterInfo &MRI = MF->getRegInfo();
6567 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6568 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6570 MVT PVT = getPointerTy();
6571 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6572 "Invalid Pointer Size!");
6574 const TargetRegisterClass *RC =
6575 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6576 unsigned Tmp = MRI.createVirtualRegister(RC);
6577 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6578 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6579 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6580 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6582 MachineInstrBuilder MIB;
6584 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6585 const int64_t SPOffset = 2 * PVT.getStoreSize();
6586 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6587 const int64_t BPOffset = 4 * PVT.getStoreSize();
6589 unsigned BufReg = MI->getOperand(0).getReg();
6591 // Reload FP (the jumped-to function may not have had a
6592 // frame pointer, and if so, then its r31 will be restored
6594 if (PVT == MVT::i64) {
6595 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6599 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6603 MIB.setMemRefs(MMOBegin, MMOEnd);
6606 if (PVT == MVT::i64) {
6607 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6608 .addImm(LabelOffset)
6611 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6612 .addImm(LabelOffset)
6615 MIB.setMemRefs(MMOBegin, MMOEnd);
6618 if (PVT == MVT::i64) {
6619 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6623 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6627 MIB.setMemRefs(MMOBegin, MMOEnd);
6630 if (PVT == MVT::i64) {
6631 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6635 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6639 MIB.setMemRefs(MMOBegin, MMOEnd);
6642 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6643 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6647 MIB.setMemRefs(MMOBegin, MMOEnd);
6651 BuildMI(*MBB, MI, DL,
6652 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6653 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6655 MI->eraseFromParent();
6660 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6661 MachineBasicBlock *BB) const {
6662 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6663 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6664 return emitEHSjLjSetJmp(MI, BB);
6665 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6666 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6667 return emitEHSjLjLongJmp(MI, BB);
6670 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6672 // To "insert" these instructions we actually have to insert their
6673 // control-flow patterns.
6674 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6675 MachineFunction::iterator It = BB;
6678 MachineFunction *F = BB->getParent();
6680 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6681 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6682 MI->getOpcode() == PPC::SELECT_I4 ||
6683 MI->getOpcode() == PPC::SELECT_I8)) {
6684 SmallVector<MachineOperand, 2> Cond;
6685 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6686 MI->getOpcode() == PPC::SELECT_CC_I8)
6687 Cond.push_back(MI->getOperand(4));
6689 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6690 Cond.push_back(MI->getOperand(1));
6692 DebugLoc dl = MI->getDebugLoc();
6693 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6694 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6695 Cond, MI->getOperand(2).getReg(),
6696 MI->getOperand(3).getReg());
6697 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6698 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6699 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6700 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6701 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6702 MI->getOpcode() == PPC::SELECT_I4 ||
6703 MI->getOpcode() == PPC::SELECT_I8 ||
6704 MI->getOpcode() == PPC::SELECT_F4 ||
6705 MI->getOpcode() == PPC::SELECT_F8 ||
6706 MI->getOpcode() == PPC::SELECT_VRRC) {
6707 // The incoming instruction knows the destination vreg to set, the
6708 // condition code register to branch on, the true/false values to
6709 // select between, and a branch opcode to use.
6714 // cmpTY ccX, r1, r2
6716 // fallthrough --> copy0MBB
6717 MachineBasicBlock *thisMBB = BB;
6718 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6719 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6720 DebugLoc dl = MI->getDebugLoc();
6721 F->insert(It, copy0MBB);
6722 F->insert(It, sinkMBB);
6724 // Transfer the remainder of BB and its successor edges to sinkMBB.
6725 sinkMBB->splice(sinkMBB->begin(), BB,
6726 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6727 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6729 // Next, add the true and fallthrough blocks as its successors.
6730 BB->addSuccessor(copy0MBB);
6731 BB->addSuccessor(sinkMBB);
6733 if (MI->getOpcode() == PPC::SELECT_I4 ||
6734 MI->getOpcode() == PPC::SELECT_I8 ||
6735 MI->getOpcode() == PPC::SELECT_F4 ||
6736 MI->getOpcode() == PPC::SELECT_F8 ||
6737 MI->getOpcode() == PPC::SELECT_VRRC) {
6738 BuildMI(BB, dl, TII->get(PPC::BC))
6739 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6741 unsigned SelectPred = MI->getOperand(4).getImm();
6742 BuildMI(BB, dl, TII->get(PPC::BCC))
6743 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6747 // %FalseValue = ...
6748 // # fallthrough to sinkMBB
6751 // Update machine-CFG edges
6752 BB->addSuccessor(sinkMBB);
6755 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6758 BuildMI(*BB, BB->begin(), dl,
6759 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6760 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6761 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6763 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6764 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6765 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6766 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6767 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6768 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6769 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6770 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6772 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6773 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6774 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6775 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6776 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6777 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6778 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6779 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6781 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6782 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6783 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6784 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6785 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6786 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6787 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6788 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6790 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6791 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6792 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6793 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6794 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6795 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6796 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6797 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6799 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6800 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6801 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6802 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6803 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6804 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6805 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6806 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6808 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6809 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6810 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6811 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6812 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6813 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6814 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6815 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6817 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6818 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6819 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6820 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6821 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6822 BB = EmitAtomicBinary(MI, BB, false, 0);
6823 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6824 BB = EmitAtomicBinary(MI, BB, true, 0);
6826 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6827 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6828 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6830 unsigned dest = MI->getOperand(0).getReg();
6831 unsigned ptrA = MI->getOperand(1).getReg();
6832 unsigned ptrB = MI->getOperand(2).getReg();
6833 unsigned oldval = MI->getOperand(3).getReg();
6834 unsigned newval = MI->getOperand(4).getReg();
6835 DebugLoc dl = MI->getDebugLoc();
6837 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6838 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6839 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6840 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6841 F->insert(It, loop1MBB);
6842 F->insert(It, loop2MBB);
6843 F->insert(It, midMBB);
6844 F->insert(It, exitMBB);
6845 exitMBB->splice(exitMBB->begin(), BB,
6846 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6847 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6851 // fallthrough --> loopMBB
6852 BB->addSuccessor(loop1MBB);
6855 // l[wd]arx dest, ptr
6856 // cmp[wd] dest, oldval
6859 // st[wd]cx. newval, ptr
6863 // st[wd]cx. dest, ptr
6866 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6867 .addReg(ptrA).addReg(ptrB);
6868 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6869 .addReg(oldval).addReg(dest);
6870 BuildMI(BB, dl, TII->get(PPC::BCC))
6871 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6872 BB->addSuccessor(loop2MBB);
6873 BB->addSuccessor(midMBB);
6876 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6877 .addReg(newval).addReg(ptrA).addReg(ptrB);
6878 BuildMI(BB, dl, TII->get(PPC::BCC))
6879 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6880 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6881 BB->addSuccessor(loop1MBB);
6882 BB->addSuccessor(exitMBB);
6885 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6886 .addReg(dest).addReg(ptrA).addReg(ptrB);
6887 BB->addSuccessor(exitMBB);
6892 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6893 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6894 // We must use 64-bit registers for addresses when targeting 64-bit,
6895 // since we're actually doing arithmetic on them. Other registers
6897 bool is64bit = PPCSubTarget.isPPC64();
6898 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6900 unsigned dest = MI->getOperand(0).getReg();
6901 unsigned ptrA = MI->getOperand(1).getReg();
6902 unsigned ptrB = MI->getOperand(2).getReg();
6903 unsigned oldval = MI->getOperand(3).getReg();
6904 unsigned newval = MI->getOperand(4).getReg();
6905 DebugLoc dl = MI->getDebugLoc();
6907 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6908 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6909 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6910 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6911 F->insert(It, loop1MBB);
6912 F->insert(It, loop2MBB);
6913 F->insert(It, midMBB);
6914 F->insert(It, exitMBB);
6915 exitMBB->splice(exitMBB->begin(), BB,
6916 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6917 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6919 MachineRegisterInfo &RegInfo = F->getRegInfo();
6920 const TargetRegisterClass *RC =
6921 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6922 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6923 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6924 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6925 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6926 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6927 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6928 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6929 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6930 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6931 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6932 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6933 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6934 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6935 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6937 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6938 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6941 // fallthrough --> loopMBB
6942 BB->addSuccessor(loop1MBB);
6944 // The 4-byte load must be aligned, while a char or short may be
6945 // anywhere in the word. Hence all this nasty bookkeeping code.
6946 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6947 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6948 // xori shift, shift1, 24 [16]
6949 // rlwinm ptr, ptr1, 0, 0, 29
6950 // slw newval2, newval, shift
6951 // slw oldval2, oldval,shift
6952 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6953 // slw mask, mask2, shift
6954 // and newval3, newval2, mask
6955 // and oldval3, oldval2, mask
6957 // lwarx tmpDest, ptr
6958 // and tmp, tmpDest, mask
6959 // cmpw tmp, oldval3
6962 // andc tmp2, tmpDest, mask
6963 // or tmp4, tmp2, newval3
6968 // stwcx. tmpDest, ptr
6970 // srw dest, tmpDest, shift
6971 if (ptrA != ZeroReg) {
6972 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6973 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6974 .addReg(ptrA).addReg(ptrB);
6978 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6979 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6980 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6981 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6983 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6984 .addReg(Ptr1Reg).addImm(0).addImm(61);
6986 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6987 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6988 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6989 .addReg(newval).addReg(ShiftReg);
6990 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6991 .addReg(oldval).addReg(ShiftReg);
6993 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6995 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6996 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6997 .addReg(Mask3Reg).addImm(65535);
6999 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7000 .addReg(Mask2Reg).addReg(ShiftReg);
7001 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7002 .addReg(NewVal2Reg).addReg(MaskReg);
7003 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7004 .addReg(OldVal2Reg).addReg(MaskReg);
7007 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7008 .addReg(ZeroReg).addReg(PtrReg);
7009 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7010 .addReg(TmpDestReg).addReg(MaskReg);
7011 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7012 .addReg(TmpReg).addReg(OldVal3Reg);
7013 BuildMI(BB, dl, TII->get(PPC::BCC))
7014 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7015 BB->addSuccessor(loop2MBB);
7016 BB->addSuccessor(midMBB);
7019 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7020 .addReg(TmpDestReg).addReg(MaskReg);
7021 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7022 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7023 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7024 .addReg(ZeroReg).addReg(PtrReg);
7025 BuildMI(BB, dl, TII->get(PPC::BCC))
7026 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7027 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7028 BB->addSuccessor(loop1MBB);
7029 BB->addSuccessor(exitMBB);
7032 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7033 .addReg(ZeroReg).addReg(PtrReg);
7034 BB->addSuccessor(exitMBB);
7039 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7041 } else if (MI->getOpcode() == PPC::FADDrtz) {
7042 // This pseudo performs an FADD with rounding mode temporarily forced
7043 // to round-to-zero. We emit this via custom inserter since the FPSCR
7044 // is not modeled at the SelectionDAG level.
7045 unsigned Dest = MI->getOperand(0).getReg();
7046 unsigned Src1 = MI->getOperand(1).getReg();
7047 unsigned Src2 = MI->getOperand(2).getReg();
7048 DebugLoc dl = MI->getDebugLoc();
7050 MachineRegisterInfo &RegInfo = F->getRegInfo();
7051 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7053 // Save FPSCR value.
7054 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7056 // Set rounding mode to round-to-zero.
7057 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7058 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7060 // Perform addition.
7061 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7063 // Restore FPSCR value.
7064 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7065 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7066 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7067 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7068 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7069 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7070 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7071 PPC::ANDIo8 : PPC::ANDIo;
7072 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7073 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7075 MachineRegisterInfo &RegInfo = F->getRegInfo();
7076 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7077 &PPC::GPRCRegClass :
7078 &PPC::G8RCRegClass);
7080 DebugLoc dl = MI->getDebugLoc();
7081 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7082 .addReg(MI->getOperand(1).getReg()).addImm(1);
7083 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7084 MI->getOperand(0).getReg())
7085 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7087 llvm_unreachable("Unexpected instr type to insert");
7090 MI->eraseFromParent(); // The pseudo instruction is gone now.
7094 //===----------------------------------------------------------------------===//
7095 // Target Optimization Hooks
7096 //===----------------------------------------------------------------------===//
7098 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7099 DAGCombinerInfo &DCI) const {
7100 if (DCI.isAfterLegalizeVectorOps())
7103 EVT VT = Op.getValueType();
7105 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
7106 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
7107 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7108 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7110 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7111 // For the reciprocal, we need to find the zero of the function:
7112 // F(X) = A X - 1 [which has a zero at X = 1/A]
7114 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7115 // does not require additional intermediate precision]
7117 // Convergence is quadratic, so we essentially double the number of digits
7118 // correct after every iteration. The minimum architected relative
7119 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7120 // 23 digits and double has 52 digits.
7121 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7122 if (VT.getScalarType() == MVT::f64)
7125 SelectionDAG &DAG = DCI.DAG;
7129 DAG.getConstantFP(1.0, VT.getScalarType());
7130 if (VT.isVector()) {
7131 assert(VT.getVectorNumElements() == 4 &&
7132 "Unknown vector type");
7133 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7134 FPOne, FPOne, FPOne, FPOne);
7137 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7138 DCI.AddToWorklist(Est.getNode());
7140 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7141 for (int i = 0; i < Iterations; ++i) {
7142 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7143 DCI.AddToWorklist(NewEst.getNode());
7145 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7146 DCI.AddToWorklist(NewEst.getNode());
7148 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7149 DCI.AddToWorklist(NewEst.getNode());
7151 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7152 DCI.AddToWorklist(Est.getNode());
7161 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7162 DAGCombinerInfo &DCI) const {
7163 if (DCI.isAfterLegalizeVectorOps())
7166 EVT VT = Op.getValueType();
7168 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
7169 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
7170 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7171 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7173 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7174 // For the reciprocal sqrt, we need to find the zero of the function:
7175 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7177 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7178 // As a result, we precompute A/2 prior to the iteration loop.
7180 // Convergence is quadratic, so we essentially double the number of digits
7181 // correct after every iteration. The minimum architected relative
7182 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7183 // 23 digits and double has 52 digits.
7184 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7185 if (VT.getScalarType() == MVT::f64)
7188 SelectionDAG &DAG = DCI.DAG;
7191 SDValue FPThreeHalves =
7192 DAG.getConstantFP(1.5, VT.getScalarType());
7193 if (VT.isVector()) {
7194 assert(VT.getVectorNumElements() == 4 &&
7195 "Unknown vector type");
7196 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7197 FPThreeHalves, FPThreeHalves,
7198 FPThreeHalves, FPThreeHalves);
7201 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7202 DCI.AddToWorklist(Est.getNode());
7204 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7205 // this entire sequence requires only one FP constant.
7206 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7207 DCI.AddToWorklist(HalfArg.getNode());
7209 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7210 DCI.AddToWorklist(HalfArg.getNode());
7212 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7213 for (int i = 0; i < Iterations; ++i) {
7214 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7215 DCI.AddToWorklist(NewEst.getNode());
7217 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7218 DCI.AddToWorklist(NewEst.getNode());
7220 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7221 DCI.AddToWorklist(NewEst.getNode());
7223 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7224 DCI.AddToWorklist(Est.getNode());
7233 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7234 // not enforce equality of the chain operands.
7235 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7236 unsigned Bytes, int Dist,
7237 SelectionDAG &DAG) {
7238 EVT VT = LS->getMemoryVT();
7239 if (VT.getSizeInBits() / 8 != Bytes)
7242 SDValue Loc = LS->getBasePtr();
7243 SDValue BaseLoc = Base->getBasePtr();
7244 if (Loc.getOpcode() == ISD::FrameIndex) {
7245 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7247 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7248 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7249 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7250 int FS = MFI->getObjectSize(FI);
7251 int BFS = MFI->getObjectSize(BFI);
7252 if (FS != BFS || FS != (int)Bytes) return false;
7253 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7257 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7258 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7261 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7262 const GlobalValue *GV1 = nullptr;
7263 const GlobalValue *GV2 = nullptr;
7264 int64_t Offset1 = 0;
7265 int64_t Offset2 = 0;
7266 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7267 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7268 if (isGA1 && isGA2 && GV1 == GV2)
7269 return Offset1 == (Offset2 + Dist*Bytes);
7273 // Return true is there is a nearyby consecutive load to the one provided
7274 // (regardless of alignment). We search up and down the chain, looking though
7275 // token factors and other loads (but nothing else). As a result, a true
7276 // results indicates that it is safe to create a new consecutive load adjacent
7277 // to the load provided.
7278 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7279 SDValue Chain = LD->getChain();
7280 EVT VT = LD->getMemoryVT();
7282 SmallSet<SDNode *, 16> LoadRoots;
7283 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7284 SmallSet<SDNode *, 16> Visited;
7286 // First, search up the chain, branching to follow all token-factor operands.
7287 // If we find a consecutive load, then we're done, otherwise, record all
7288 // nodes just above the top-level loads and token factors.
7289 while (!Queue.empty()) {
7290 SDNode *ChainNext = Queue.pop_back_val();
7291 if (!Visited.insert(ChainNext))
7294 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7295 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7298 if (!Visited.count(ChainLD->getChain().getNode()))
7299 Queue.push_back(ChainLD->getChain().getNode());
7300 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7301 for (SDNode::op_iterator O = ChainNext->op_begin(),
7302 OE = ChainNext->op_end(); O != OE; ++O)
7303 if (!Visited.count(O->getNode()))
7304 Queue.push_back(O->getNode());
7306 LoadRoots.insert(ChainNext);
7309 // Second, search down the chain, starting from the top-level nodes recorded
7310 // in the first phase. These top-level nodes are the nodes just above all
7311 // loads and token factors. Starting with their uses, recursively look though
7312 // all loads (just the chain uses) and token factors to find a consecutive
7317 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7318 IE = LoadRoots.end(); I != IE; ++I) {
7319 Queue.push_back(*I);
7321 while (!Queue.empty()) {
7322 SDNode *LoadRoot = Queue.pop_back_val();
7323 if (!Visited.insert(LoadRoot))
7326 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7327 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7330 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7331 UE = LoadRoot->use_end(); UI != UE; ++UI)
7332 if (((isa<LoadSDNode>(*UI) &&
7333 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7334 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7335 Queue.push_back(*UI);
7342 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7343 DAGCombinerInfo &DCI) const {
7344 SelectionDAG &DAG = DCI.DAG;
7347 assert(PPCSubTarget.useCRBits() &&
7348 "Expecting to be tracking CR bits");
7349 // If we're tracking CR bits, we need to be careful that we don't have:
7350 // trunc(binary-ops(zext(x), zext(y)))
7352 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7353 // such that we're unnecessarily moving things into GPRs when it would be
7354 // better to keep them in CR bits.
7356 // Note that trunc here can be an actual i1 trunc, or can be the effective
7357 // truncation that comes from a setcc or select_cc.
7358 if (N->getOpcode() == ISD::TRUNCATE &&
7359 N->getValueType(0) != MVT::i1)
7362 if (N->getOperand(0).getValueType() != MVT::i32 &&
7363 N->getOperand(0).getValueType() != MVT::i64)
7366 if (N->getOpcode() == ISD::SETCC ||
7367 N->getOpcode() == ISD::SELECT_CC) {
7368 // If we're looking at a comparison, then we need to make sure that the
7369 // high bits (all except for the first) don't matter the result.
7371 cast<CondCodeSDNode>(N->getOperand(
7372 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7373 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7375 if (ISD::isSignedIntSetCC(CC)) {
7376 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7377 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7379 } else if (ISD::isUnsignedIntSetCC(CC)) {
7380 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7381 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7382 !DAG.MaskedValueIsZero(N->getOperand(1),
7383 APInt::getHighBitsSet(OpBits, OpBits-1)))
7386 // This is neither a signed nor an unsigned comparison, just make sure
7387 // that the high bits are equal.
7388 APInt Op1Zero, Op1One;
7389 APInt Op2Zero, Op2One;
7390 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7391 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7393 // We don't really care about what is known about the first bit (if
7394 // anything), so clear it in all masks prior to comparing them.
7395 Op1Zero.clearBit(0); Op1One.clearBit(0);
7396 Op2Zero.clearBit(0); Op2One.clearBit(0);
7398 if (Op1Zero != Op2Zero || Op1One != Op2One)
7403 // We now know that the higher-order bits are irrelevant, we just need to
7404 // make sure that all of the intermediate operations are bit operations, and
7405 // all inputs are extensions.
7406 if (N->getOperand(0).getOpcode() != ISD::AND &&
7407 N->getOperand(0).getOpcode() != ISD::OR &&
7408 N->getOperand(0).getOpcode() != ISD::XOR &&
7409 N->getOperand(0).getOpcode() != ISD::SELECT &&
7410 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7411 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7412 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7413 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7414 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7417 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7418 N->getOperand(1).getOpcode() != ISD::AND &&
7419 N->getOperand(1).getOpcode() != ISD::OR &&
7420 N->getOperand(1).getOpcode() != ISD::XOR &&
7421 N->getOperand(1).getOpcode() != ISD::SELECT &&
7422 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7423 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7424 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7425 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7426 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7429 SmallVector<SDValue, 4> Inputs;
7430 SmallVector<SDValue, 8> BinOps, PromOps;
7431 SmallPtrSet<SDNode *, 16> Visited;
7433 for (unsigned i = 0; i < 2; ++i) {
7434 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7435 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7436 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7437 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7438 isa<ConstantSDNode>(N->getOperand(i)))
7439 Inputs.push_back(N->getOperand(i));
7441 BinOps.push_back(N->getOperand(i));
7443 if (N->getOpcode() == ISD::TRUNCATE)
7447 // Visit all inputs, collect all binary operations (and, or, xor and
7448 // select) that are all fed by extensions.
7449 while (!BinOps.empty()) {
7450 SDValue BinOp = BinOps.back();
7453 if (!Visited.insert(BinOp.getNode()))
7456 PromOps.push_back(BinOp);
7458 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7459 // The condition of the select is not promoted.
7460 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7462 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7465 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7466 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7467 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7468 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7469 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7470 Inputs.push_back(BinOp.getOperand(i));
7471 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7472 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7473 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7474 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7475 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7476 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7477 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7478 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7479 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7480 BinOps.push_back(BinOp.getOperand(i));
7482 // We have an input that is not an extension or another binary
7483 // operation; we'll abort this transformation.
7489 // Make sure that this is a self-contained cluster of operations (which
7490 // is not quite the same thing as saying that everything has only one
7492 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7493 if (isa<ConstantSDNode>(Inputs[i]))
7496 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7497 UE = Inputs[i].getNode()->use_end();
7500 if (User != N && !Visited.count(User))
7503 // Make sure that we're not going to promote the non-output-value
7504 // operand(s) or SELECT or SELECT_CC.
7505 // FIXME: Although we could sometimes handle this, and it does occur in
7506 // practice that one of the condition inputs to the select is also one of
7507 // the outputs, we currently can't deal with this.
7508 if (User->getOpcode() == ISD::SELECT) {
7509 if (User->getOperand(0) == Inputs[i])
7511 } else if (User->getOpcode() == ISD::SELECT_CC) {
7512 if (User->getOperand(0) == Inputs[i] ||
7513 User->getOperand(1) == Inputs[i])
7519 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7520 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7521 UE = PromOps[i].getNode()->use_end();
7524 if (User != N && !Visited.count(User))
7527 // Make sure that we're not going to promote the non-output-value
7528 // operand(s) or SELECT or SELECT_CC.
7529 // FIXME: Although we could sometimes handle this, and it does occur in
7530 // practice that one of the condition inputs to the select is also one of
7531 // the outputs, we currently can't deal with this.
7532 if (User->getOpcode() == ISD::SELECT) {
7533 if (User->getOperand(0) == PromOps[i])
7535 } else if (User->getOpcode() == ISD::SELECT_CC) {
7536 if (User->getOperand(0) == PromOps[i] ||
7537 User->getOperand(1) == PromOps[i])
7543 // Replace all inputs with the extension operand.
7544 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7545 // Constants may have users outside the cluster of to-be-promoted nodes,
7546 // and so we need to replace those as we do the promotions.
7547 if (isa<ConstantSDNode>(Inputs[i]))
7550 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7553 // Replace all operations (these are all the same, but have a different
7554 // (i1) return type). DAG.getNode will validate that the types of
7555 // a binary operator match, so go through the list in reverse so that
7556 // we've likely promoted both operands first. Any intermediate truncations or
7557 // extensions disappear.
7558 while (!PromOps.empty()) {
7559 SDValue PromOp = PromOps.back();
7562 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7563 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7564 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7565 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7566 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7567 PromOp.getOperand(0).getValueType() != MVT::i1) {
7568 // The operand is not yet ready (see comment below).
7569 PromOps.insert(PromOps.begin(), PromOp);
7573 SDValue RepValue = PromOp.getOperand(0);
7574 if (isa<ConstantSDNode>(RepValue))
7575 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7577 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7582 switch (PromOp.getOpcode()) {
7583 default: C = 0; break;
7584 case ISD::SELECT: C = 1; break;
7585 case ISD::SELECT_CC: C = 2; break;
7588 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7589 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7590 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7591 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7592 // The to-be-promoted operands of this node have not yet been
7593 // promoted (this should be rare because we're going through the
7594 // list backward, but if one of the operands has several users in
7595 // this cluster of to-be-promoted nodes, it is possible).
7596 PromOps.insert(PromOps.begin(), PromOp);
7600 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7601 PromOp.getNode()->op_end());
7603 // If there are any constant inputs, make sure they're replaced now.
7604 for (unsigned i = 0; i < 2; ++i)
7605 if (isa<ConstantSDNode>(Ops[C+i]))
7606 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7608 DAG.ReplaceAllUsesOfValueWith(PromOp,
7609 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7612 // Now we're left with the initial truncation itself.
7613 if (N->getOpcode() == ISD::TRUNCATE)
7614 return N->getOperand(0);
7616 // Otherwise, this is a comparison. The operands to be compared have just
7617 // changed type (to i1), but everything else is the same.
7618 return SDValue(N, 0);
7621 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7622 DAGCombinerInfo &DCI) const {
7623 SelectionDAG &DAG = DCI.DAG;
7626 // If we're tracking CR bits, we need to be careful that we don't have:
7627 // zext(binary-ops(trunc(x), trunc(y)))
7629 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7630 // such that we're unnecessarily moving things into CR bits that can more
7631 // efficiently stay in GPRs. Note that if we're not certain that the high
7632 // bits are set as required by the final extension, we still may need to do
7633 // some masking to get the proper behavior.
7635 // This same functionality is important on PPC64 when dealing with
7636 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7637 // the return values of functions. Because it is so similar, it is handled
7640 if (N->getValueType(0) != MVT::i32 &&
7641 N->getValueType(0) != MVT::i64)
7644 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7645 PPCSubTarget.useCRBits()) ||
7646 (N->getOperand(0).getValueType() == MVT::i32 &&
7647 PPCSubTarget.isPPC64())))
7650 if (N->getOperand(0).getOpcode() != ISD::AND &&
7651 N->getOperand(0).getOpcode() != ISD::OR &&
7652 N->getOperand(0).getOpcode() != ISD::XOR &&
7653 N->getOperand(0).getOpcode() != ISD::SELECT &&
7654 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7657 SmallVector<SDValue, 4> Inputs;
7658 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7659 SmallPtrSet<SDNode *, 16> Visited;
7661 // Visit all inputs, collect all binary operations (and, or, xor and
7662 // select) that are all fed by truncations.
7663 while (!BinOps.empty()) {
7664 SDValue BinOp = BinOps.back();
7667 if (!Visited.insert(BinOp.getNode()))
7670 PromOps.push_back(BinOp);
7672 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7673 // The condition of the select is not promoted.
7674 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7676 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7679 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7680 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7681 Inputs.push_back(BinOp.getOperand(i));
7682 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7683 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7684 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7685 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7686 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7687 BinOps.push_back(BinOp.getOperand(i));
7689 // We have an input that is not a truncation or another binary
7690 // operation; we'll abort this transformation.
7696 // Make sure that this is a self-contained cluster of operations (which
7697 // is not quite the same thing as saying that everything has only one
7699 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7700 if (isa<ConstantSDNode>(Inputs[i]))
7703 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7704 UE = Inputs[i].getNode()->use_end();
7707 if (User != N && !Visited.count(User))
7710 // Make sure that we're not going to promote the non-output-value
7711 // operand(s) or SELECT or SELECT_CC.
7712 // FIXME: Although we could sometimes handle this, and it does occur in
7713 // practice that one of the condition inputs to the select is also one of
7714 // the outputs, we currently can't deal with this.
7715 if (User->getOpcode() == ISD::SELECT) {
7716 if (User->getOperand(0) == Inputs[i])
7718 } else if (User->getOpcode() == ISD::SELECT_CC) {
7719 if (User->getOperand(0) == Inputs[i] ||
7720 User->getOperand(1) == Inputs[i])
7726 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7727 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7728 UE = PromOps[i].getNode()->use_end();
7731 if (User != N && !Visited.count(User))
7734 // Make sure that we're not going to promote the non-output-value
7735 // operand(s) or SELECT or SELECT_CC.
7736 // FIXME: Although we could sometimes handle this, and it does occur in
7737 // practice that one of the condition inputs to the select is also one of
7738 // the outputs, we currently can't deal with this.
7739 if (User->getOpcode() == ISD::SELECT) {
7740 if (User->getOperand(0) == PromOps[i])
7742 } else if (User->getOpcode() == ISD::SELECT_CC) {
7743 if (User->getOperand(0) == PromOps[i] ||
7744 User->getOperand(1) == PromOps[i])
7750 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7751 bool ReallyNeedsExt = false;
7752 if (N->getOpcode() != ISD::ANY_EXTEND) {
7753 // If all of the inputs are not already sign/zero extended, then
7754 // we'll still need to do that at the end.
7755 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7756 if (isa<ConstantSDNode>(Inputs[i]))
7760 Inputs[i].getOperand(0).getValueSizeInBits();
7761 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7763 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7764 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7765 APInt::getHighBitsSet(OpBits,
7766 OpBits-PromBits))) ||
7767 (N->getOpcode() == ISD::SIGN_EXTEND &&
7768 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7769 (OpBits-(PromBits-1)))) {
7770 ReallyNeedsExt = true;
7776 // Replace all inputs, either with the truncation operand, or a
7777 // truncation or extension to the final output type.
7778 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7779 // Constant inputs need to be replaced with the to-be-promoted nodes that
7780 // use them because they might have users outside of the cluster of
7782 if (isa<ConstantSDNode>(Inputs[i]))
7785 SDValue InSrc = Inputs[i].getOperand(0);
7786 if (Inputs[i].getValueType() == N->getValueType(0))
7787 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7788 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7789 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7790 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7791 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7792 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7793 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7795 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7796 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7799 // Replace all operations (these are all the same, but have a different
7800 // (promoted) return type). DAG.getNode will validate that the types of
7801 // a binary operator match, so go through the list in reverse so that
7802 // we've likely promoted both operands first.
7803 while (!PromOps.empty()) {
7804 SDValue PromOp = PromOps.back();
7808 switch (PromOp.getOpcode()) {
7809 default: C = 0; break;
7810 case ISD::SELECT: C = 1; break;
7811 case ISD::SELECT_CC: C = 2; break;
7814 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7815 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7816 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7817 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7818 // The to-be-promoted operands of this node have not yet been
7819 // promoted (this should be rare because we're going through the
7820 // list backward, but if one of the operands has several users in
7821 // this cluster of to-be-promoted nodes, it is possible).
7822 PromOps.insert(PromOps.begin(), PromOp);
7826 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7827 PromOp.getNode()->op_end());
7829 // If this node has constant inputs, then they'll need to be promoted here.
7830 for (unsigned i = 0; i < 2; ++i) {
7831 if (!isa<ConstantSDNode>(Ops[C+i]))
7833 if (Ops[C+i].getValueType() == N->getValueType(0))
7836 if (N->getOpcode() == ISD::SIGN_EXTEND)
7837 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7838 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7839 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7841 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7844 DAG.ReplaceAllUsesOfValueWith(PromOp,
7845 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
7848 // Now we're left with the initial extension itself.
7849 if (!ReallyNeedsExt)
7850 return N->getOperand(0);
7852 // To zero extend, just mask off everything except for the first bit (in the
7854 if (N->getOpcode() == ISD::ZERO_EXTEND)
7855 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7856 DAG.getConstant(APInt::getLowBitsSet(
7857 N->getValueSizeInBits(0), PromBits),
7858 N->getValueType(0)));
7860 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7861 "Invalid extension type");
7862 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7864 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7865 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7866 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7867 N->getOperand(0), ShiftCst), ShiftCst);
7870 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7871 DAGCombinerInfo &DCI) const {
7872 const TargetMachine &TM = getTargetMachine();
7873 SelectionDAG &DAG = DCI.DAG;
7875 switch (N->getOpcode()) {
7878 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7879 if (C->isNullValue()) // 0 << V -> 0.
7880 return N->getOperand(0);
7884 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7885 if (C->isNullValue()) // 0 >>u V -> 0.
7886 return N->getOperand(0);
7890 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7891 if (C->isNullValue() || // 0 >>s V -> 0.
7892 C->isAllOnesValue()) // -1 >>s V -> -1.
7893 return N->getOperand(0);
7896 case ISD::SIGN_EXTEND:
7897 case ISD::ZERO_EXTEND:
7898 case ISD::ANY_EXTEND:
7899 return DAGCombineExtBoolTrunc(N, DCI);
7902 case ISD::SELECT_CC:
7903 return DAGCombineTruncBoolExt(N, DCI);
7905 assert(TM.Options.UnsafeFPMath &&
7906 "Reciprocal estimates require UnsafeFPMath");
7908 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7910 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7912 DCI.AddToWorklist(RV.getNode());
7913 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7914 N->getOperand(0), RV);
7916 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7917 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7919 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7922 DCI.AddToWorklist(RV.getNode());
7923 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7924 N->getValueType(0), RV);
7925 DCI.AddToWorklist(RV.getNode());
7926 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7927 N->getOperand(0), RV);
7929 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7930 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7932 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7935 DCI.AddToWorklist(RV.getNode());
7936 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7937 N->getValueType(0), RV,
7938 N->getOperand(1).getOperand(1));
7939 DCI.AddToWorklist(RV.getNode());
7940 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7941 N->getOperand(0), RV);
7945 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7947 DCI.AddToWorklist(RV.getNode());
7948 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7949 N->getOperand(0), RV);
7955 assert(TM.Options.UnsafeFPMath &&
7956 "Reciprocal estimates require UnsafeFPMath");
7958 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7960 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7962 DCI.AddToWorklist(RV.getNode());
7963 RV = DAGCombineFastRecip(RV, DCI);
7965 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7966 // this case and force the answer to 0.
7968 EVT VT = RV.getValueType();
7970 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7971 if (VT.isVector()) {
7972 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7973 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7977 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7978 N->getOperand(0), Zero, ISD::SETEQ);
7979 DCI.AddToWorklist(ZeroCmp.getNode());
7980 DCI.AddToWorklist(RV.getNode());
7982 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7990 case ISD::SINT_TO_FP:
7991 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7992 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7993 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7994 // We allow the src/dst to be either f32/f64, but the intermediate
7995 // type must be i64.
7996 if (N->getOperand(0).getValueType() == MVT::i64 &&
7997 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7998 SDValue Val = N->getOperand(0).getOperand(0);
7999 if (Val.getValueType() == MVT::f32) {
8000 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8001 DCI.AddToWorklist(Val.getNode());
8004 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8005 DCI.AddToWorklist(Val.getNode());
8006 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8007 DCI.AddToWorklist(Val.getNode());
8008 if (N->getValueType(0) == MVT::f32) {
8009 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8010 DAG.getIntPtrConstant(0));
8011 DCI.AddToWorklist(Val.getNode());
8014 } else if (N->getOperand(0).getValueType() == MVT::i32) {
8015 // If the intermediate type is i32, we can avoid the load/store here
8022 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8023 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8024 !cast<StoreSDNode>(N)->isTruncatingStore() &&
8025 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8026 N->getOperand(1).getValueType() == MVT::i32 &&
8027 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8028 SDValue Val = N->getOperand(1).getOperand(0);
8029 if (Val.getValueType() == MVT::f32) {
8030 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8031 DCI.AddToWorklist(Val.getNode());
8033 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8034 DCI.AddToWorklist(Val.getNode());
8037 N->getOperand(0), Val, N->getOperand(2),
8038 DAG.getValueType(N->getOperand(1).getValueType())
8041 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8042 DAG.getVTList(MVT::Other), Ops,
8043 cast<StoreSDNode>(N)->getMemoryVT(),
8044 cast<StoreSDNode>(N)->getMemOperand());
8045 DCI.AddToWorklist(Val.getNode());
8049 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8050 if (cast<StoreSDNode>(N)->isUnindexed() &&
8051 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8052 N->getOperand(1).getNode()->hasOneUse() &&
8053 (N->getOperand(1).getValueType() == MVT::i32 ||
8054 N->getOperand(1).getValueType() == MVT::i16 ||
8055 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8056 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8057 N->getOperand(1).getValueType() == MVT::i64))) {
8058 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8059 // Do an any-extend to 32-bits if this is a half-word input.
8060 if (BSwapOp.getValueType() == MVT::i16)
8061 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8064 N->getOperand(0), BSwapOp, N->getOperand(2),
8065 DAG.getValueType(N->getOperand(1).getValueType())
8068 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8069 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8070 cast<StoreSDNode>(N)->getMemOperand());
8074 LoadSDNode *LD = cast<LoadSDNode>(N);
8075 EVT VT = LD->getValueType(0);
8076 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8077 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8078 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8079 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8080 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8081 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8082 LD->getAlignment() < ABIAlignment) {
8083 // This is a type-legal unaligned Altivec load.
8084 SDValue Chain = LD->getChain();
8085 SDValue Ptr = LD->getBasePtr();
8087 // This implements the loading of unaligned vectors as described in
8088 // the venerable Apple Velocity Engine overview. Specifically:
8089 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8090 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8092 // The general idea is to expand a sequence of one or more unaligned
8093 // loads into a alignment-based permutation-control instruction (lvsl),
8094 // a series of regular vector loads (which always truncate their
8095 // input address to an aligned address), and a series of permutations.
8096 // The results of these permutations are the requested loaded values.
8097 // The trick is that the last "extra" load is not taken from the address
8098 // you might suspect (sizeof(vector) bytes after the last requested
8099 // load), but rather sizeof(vector) - 1 bytes after the last
8100 // requested vector. The point of this is to avoid a page fault if the
8101 // base address happened to be aligned. This works because if the base
8102 // address is aligned, then adding less than a full vector length will
8103 // cause the last vector in the sequence to be (re)loaded. Otherwise,
8104 // the next vector will be fetched as you might suspect was necessary.
8106 // We might be able to reuse the permutation generation from
8107 // a different base address offset from this one by an aligned amount.
8108 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8109 // optimization later.
8110 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
8111 DAG, dl, MVT::v16i8);
8113 // Refine the alignment of the original load (a "new" load created here
8114 // which was identical to the first except for the alignment would be
8115 // merged with the existing node regardless).
8116 MachineFunction &MF = DAG.getMachineFunction();
8117 MachineMemOperand *MMO =
8118 MF.getMachineMemOperand(LD->getPointerInfo(),
8119 LD->getMemOperand()->getFlags(),
8120 LD->getMemoryVT().getStoreSize(),
8122 LD->refineAlignment(MMO);
8123 SDValue BaseLoad = SDValue(LD, 0);
8125 // Note that the value of IncOffset (which is provided to the next
8126 // load's pointer info offset value, and thus used to calculate the
8127 // alignment), and the value of IncValue (which is actually used to
8128 // increment the pointer value) are different! This is because we
8129 // require the next load to appear to be aligned, even though it
8130 // is actually offset from the base pointer by a lesser amount.
8131 int IncOffset = VT.getSizeInBits() / 8;
8132 int IncValue = IncOffset;
8134 // Walk (both up and down) the chain looking for another load at the real
8135 // (aligned) offset (the alignment of the other load does not matter in
8136 // this case). If found, then do not use the offset reduction trick, as
8137 // that will prevent the loads from being later combined (as they would
8138 // otherwise be duplicates).
8139 if (!findConsecutiveLoad(LD, DAG))
8142 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8143 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8146 DAG.getLoad(VT, dl, Chain, Ptr,
8147 LD->getPointerInfo().getWithOffset(IncOffset),
8148 LD->isVolatile(), LD->isNonTemporal(),
8149 LD->isInvariant(), ABIAlignment);
8151 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8152 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8154 if (BaseLoad.getValueType() != MVT::v4i32)
8155 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8157 if (ExtraLoad.getValueType() != MVT::v4i32)
8158 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8160 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8161 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8163 if (VT != MVT::v4i32)
8164 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8166 // Now we need to be really careful about how we update the users of the
8167 // original load. We cannot just call DCI.CombineTo (or
8168 // DAG.ReplaceAllUsesWith for that matter), because the load still has
8169 // uses created here (the permutation for example) that need to stay.
8170 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8172 SDUse &Use = UI.getUse();
8174 // Note: BaseLoad is checked here because it might not be N, but a
8176 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8177 User == TF.getNode() || Use.getResNo() > 1) {
8182 SDValue To = Use.getResNo() ? TF : Perm;
8185 SmallVector<SDValue, 8> Ops;
8186 for (SDNode::op_iterator O = User->op_begin(),
8187 OE = User->op_end(); O != OE; ++O) {
8194 DAG.UpdateNodeOperands(User, Ops);
8197 return SDValue(N, 0);
8201 case ISD::INTRINSIC_WO_CHAIN:
8202 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8203 Intrinsic::ppc_altivec_lvsl &&
8204 N->getOperand(1)->getOpcode() == ISD::ADD) {
8205 SDValue Add = N->getOperand(1);
8207 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8208 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8209 Add.getValueType().getScalarType().getSizeInBits()))) {
8210 SDNode *BasePtr = Add->getOperand(0).getNode();
8211 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8212 UE = BasePtr->use_end(); UI != UE; ++UI) {
8213 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8214 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8215 Intrinsic::ppc_altivec_lvsl) {
8216 // We've found another LVSL, and this address if an aligned
8217 // multiple of that one. The results will be the same, so use the
8218 // one we've just found instead.
8220 return SDValue(*UI, 0);
8228 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8229 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8230 N->getOperand(0).hasOneUse() &&
8231 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8232 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8233 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8234 N->getValueType(0) == MVT::i64))) {
8235 SDValue Load = N->getOperand(0);
8236 LoadSDNode *LD = cast<LoadSDNode>(Load);
8237 // Create the byte-swapping load.
8239 LD->getChain(), // Chain
8240 LD->getBasePtr(), // Ptr
8241 DAG.getValueType(N->getValueType(0)) // VT
8244 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8245 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8246 MVT::i64 : MVT::i32, MVT::Other),
8247 Ops, LD->getMemoryVT(), LD->getMemOperand());
8249 // If this is an i16 load, insert the truncate.
8250 SDValue ResVal = BSLoad;
8251 if (N->getValueType(0) == MVT::i16)
8252 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8254 // First, combine the bswap away. This makes the value produced by the
8256 DCI.CombineTo(N, ResVal);
8258 // Next, combine the load away, we give it a bogus result value but a real
8259 // chain result. The result value is dead because the bswap is dead.
8260 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8262 // Return N so it doesn't get rechecked!
8263 return SDValue(N, 0);
8267 case PPCISD::VCMP: {
8268 // If a VCMPo node already exists with exactly the same operands as this
8269 // node, use its result instead of this node (VCMPo computes both a CR6 and
8270 // a normal output).
8272 if (!N->getOperand(0).hasOneUse() &&
8273 !N->getOperand(1).hasOneUse() &&
8274 !N->getOperand(2).hasOneUse()) {
8276 // Scan all of the users of the LHS, looking for VCMPo's that match.
8277 SDNode *VCMPoNode = nullptr;
8279 SDNode *LHSN = N->getOperand(0).getNode();
8280 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8282 if (UI->getOpcode() == PPCISD::VCMPo &&
8283 UI->getOperand(1) == N->getOperand(1) &&
8284 UI->getOperand(2) == N->getOperand(2) &&
8285 UI->getOperand(0) == N->getOperand(0)) {
8290 // If there is no VCMPo node, or if the flag value has a single use, don't
8292 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8295 // Look at the (necessarily single) use of the flag value. If it has a
8296 // chain, this transformation is more complex. Note that multiple things
8297 // could use the value result, which we should ignore.
8298 SDNode *FlagUser = nullptr;
8299 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8300 FlagUser == nullptr; ++UI) {
8301 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8303 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8304 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8311 // If the user is a MFOCRF instruction, we know this is safe.
8312 // Otherwise we give up for right now.
8313 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8314 return SDValue(VCMPoNode, 0);
8319 SDValue Cond = N->getOperand(1);
8320 SDValue Target = N->getOperand(2);
8322 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8323 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8324 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8326 // We now need to make the intrinsic dead (it cannot be instruction
8328 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8329 assert(Cond.getNode()->hasOneUse() &&
8330 "Counter decrement has more than one use");
8332 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8333 N->getOperand(0), Target);
8338 // If this is a branch on an altivec predicate comparison, lower this so
8339 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8340 // lowering is done pre-legalize, because the legalizer lowers the predicate
8341 // compare down to code that is difficult to reassemble.
8342 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8343 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8345 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8346 // value. If so, pass-through the AND to get to the intrinsic.
8347 if (LHS.getOpcode() == ISD::AND &&
8348 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8349 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8350 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8351 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8352 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8354 LHS = LHS.getOperand(0);
8356 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8357 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8358 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8359 isa<ConstantSDNode>(RHS)) {
8360 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8361 "Counter decrement comparison is not EQ or NE");
8363 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8364 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8365 (CC == ISD::SETNE && !Val);
8367 // We now need to make the intrinsic dead (it cannot be instruction
8369 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8370 assert(LHS.getNode()->hasOneUse() &&
8371 "Counter decrement has more than one use");
8373 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8374 N->getOperand(0), N->getOperand(4));
8380 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8381 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8382 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8383 assert(isDot && "Can't compare against a vector result!");
8385 // If this is a comparison against something other than 0/1, then we know
8386 // that the condition is never/always true.
8387 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8388 if (Val != 0 && Val != 1) {
8389 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8390 return N->getOperand(0);
8391 // Always !=, turn it into an unconditional branch.
8392 return DAG.getNode(ISD::BR, dl, MVT::Other,
8393 N->getOperand(0), N->getOperand(4));
8396 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8398 // Create the PPCISD altivec 'dot' comparison node.
8400 LHS.getOperand(2), // LHS of compare
8401 LHS.getOperand(3), // RHS of compare
8402 DAG.getConstant(CompareOpc, MVT::i32)
8404 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8405 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8407 // Unpack the result based on how the target uses it.
8408 PPC::Predicate CompOpc;
8409 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8410 default: // Can't happen, don't crash on invalid number though.
8411 case 0: // Branch on the value of the EQ bit of CR6.
8412 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8414 case 1: // Branch on the inverted value of the EQ bit of CR6.
8415 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8417 case 2: // Branch on the value of the LT bit of CR6.
8418 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8420 case 3: // Branch on the inverted value of the LT bit of CR6.
8421 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8425 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8426 DAG.getConstant(CompOpc, MVT::i32),
8427 DAG.getRegister(PPC::CR6, MVT::i32),
8428 N->getOperand(4), CompNode.getValue(1));
8437 //===----------------------------------------------------------------------===//
8438 // Inline Assembly Support
8439 //===----------------------------------------------------------------------===//
8441 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8444 const SelectionDAG &DAG,
8445 unsigned Depth) const {
8446 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8447 switch (Op.getOpcode()) {
8449 case PPCISD::LBRX: {
8450 // lhbrx is known to have the top bits cleared out.
8451 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8452 KnownZero = 0xFFFF0000;
8455 case ISD::INTRINSIC_WO_CHAIN: {
8456 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8458 case Intrinsic::ppc_altivec_vcmpbfp_p:
8459 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8460 case Intrinsic::ppc_altivec_vcmpequb_p:
8461 case Intrinsic::ppc_altivec_vcmpequh_p:
8462 case Intrinsic::ppc_altivec_vcmpequw_p:
8463 case Intrinsic::ppc_altivec_vcmpgefp_p:
8464 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8465 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8466 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8467 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8468 case Intrinsic::ppc_altivec_vcmpgtub_p:
8469 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8470 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8471 KnownZero = ~1U; // All bits but the low one are known to be zero.
8479 /// getConstraintType - Given a constraint, return the type of
8480 /// constraint it is for this target.
8481 PPCTargetLowering::ConstraintType
8482 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8483 if (Constraint.size() == 1) {
8484 switch (Constraint[0]) {
8491 return C_RegisterClass;
8493 // FIXME: While Z does indicate a memory constraint, it specifically
8494 // indicates an r+r address (used in conjunction with the 'y' modifier
8495 // in the replacement string). Currently, we're forcing the base
8496 // register to be r0 in the asm printer (which is interpreted as zero)
8497 // and forming the complete address in the second register. This is
8501 } else if (Constraint == "wc") { // individual CR bits.
8502 return C_RegisterClass;
8503 } else if (Constraint == "wa" || Constraint == "wd" ||
8504 Constraint == "wf" || Constraint == "ws") {
8505 return C_RegisterClass; // VSX registers.
8507 return TargetLowering::getConstraintType(Constraint);
8510 /// Examine constraint type and operand type and determine a weight value.
8511 /// This object must already have been set up with the operand type
8512 /// and the current alternative constraint selected.
8513 TargetLowering::ConstraintWeight
8514 PPCTargetLowering::getSingleConstraintMatchWeight(
8515 AsmOperandInfo &info, const char *constraint) const {
8516 ConstraintWeight weight = CW_Invalid;
8517 Value *CallOperandVal = info.CallOperandVal;
8518 // If we don't have a value, we can't do a match,
8519 // but allow it at the lowest weight.
8520 if (!CallOperandVal)
8522 Type *type = CallOperandVal->getType();
8524 // Look at the constraint type.
8525 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8526 return CW_Register; // an individual CR bit.
8527 else if ((StringRef(constraint) == "wa" ||
8528 StringRef(constraint) == "wd" ||
8529 StringRef(constraint) == "wf") &&
8532 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8535 switch (*constraint) {
8537 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8540 if (type->isIntegerTy())
8541 weight = CW_Register;
8544 if (type->isFloatTy())
8545 weight = CW_Register;
8548 if (type->isDoubleTy())
8549 weight = CW_Register;
8552 if (type->isVectorTy())
8553 weight = CW_Register;
8556 weight = CW_Register;
8565 std::pair<unsigned, const TargetRegisterClass*>
8566 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8568 if (Constraint.size() == 1) {
8569 // GCC RS6000 Constraint Letters
8570 switch (Constraint[0]) {
8572 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8573 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8574 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8576 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8577 return std::make_pair(0U, &PPC::G8RCRegClass);
8578 return std::make_pair(0U, &PPC::GPRCRegClass);
8580 if (VT == MVT::f32 || VT == MVT::i32)
8581 return std::make_pair(0U, &PPC::F4RCRegClass);
8582 if (VT == MVT::f64 || VT == MVT::i64)
8583 return std::make_pair(0U, &PPC::F8RCRegClass);
8586 return std::make_pair(0U, &PPC::VRRCRegClass);
8588 return std::make_pair(0U, &PPC::CRRCRegClass);
8590 } else if (Constraint == "wc") { // an individual CR bit.
8591 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8592 } else if (Constraint == "wa" || Constraint == "wd" ||
8593 Constraint == "wf") {
8594 return std::make_pair(0U, &PPC::VSRCRegClass);
8595 } else if (Constraint == "ws") {
8596 return std::make_pair(0U, &PPC::VSFRCRegClass);
8599 std::pair<unsigned, const TargetRegisterClass*> R =
8600 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8602 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8603 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8604 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8606 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8607 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8608 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8609 PPC::GPRCRegClass.contains(R.first)) {
8610 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8611 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8612 PPC::sub_32, &PPC::G8RCRegClass),
8613 &PPC::G8RCRegClass);
8620 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8621 /// vector. If it is invalid, don't add anything to Ops.
8622 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8623 std::string &Constraint,
8624 std::vector<SDValue>&Ops,
8625 SelectionDAG &DAG) const {
8628 // Only support length 1 constraints.
8629 if (Constraint.length() > 1) return;
8631 char Letter = Constraint[0];
8642 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8643 if (!CST) return; // Must be an immediate to match.
8644 unsigned Value = CST->getZExtValue();
8646 default: llvm_unreachable("Unknown constraint letter!");
8647 case 'I': // "I" is a signed 16-bit constant.
8648 if ((short)Value == (int)Value)
8649 Result = DAG.getTargetConstant(Value, Op.getValueType());
8651 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8652 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8653 if ((short)Value == 0)
8654 Result = DAG.getTargetConstant(Value, Op.getValueType());
8656 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8657 if ((Value >> 16) == 0)
8658 Result = DAG.getTargetConstant(Value, Op.getValueType());
8660 case 'M': // "M" is a constant that is greater than 31.
8662 Result = DAG.getTargetConstant(Value, Op.getValueType());
8664 case 'N': // "N" is a positive constant that is an exact power of two.
8665 if ((int)Value > 0 && isPowerOf2_32(Value))
8666 Result = DAG.getTargetConstant(Value, Op.getValueType());
8668 case 'O': // "O" is the constant zero.
8670 Result = DAG.getTargetConstant(Value, Op.getValueType());
8672 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8673 if ((short)-Value == (int)-Value)
8674 Result = DAG.getTargetConstant(Value, Op.getValueType());
8681 if (Result.getNode()) {
8682 Ops.push_back(Result);
8686 // Handle standard constraint letters.
8687 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8690 // isLegalAddressingMode - Return true if the addressing mode represented
8691 // by AM is legal for this target, for a load/store of the specified type.
8692 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8694 // FIXME: PPC does not allow r+i addressing modes for vectors!
8696 // PPC allows a sign-extended 16-bit immediate field.
8697 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8700 // No global is ever allowed as a base.
8704 // PPC only support r+r,
8706 case 0: // "r+i" or just "i", depending on HasBaseReg.
8709 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8711 // Otherwise we have r+r or r+i.
8714 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8716 // Allow 2*r as r+r.
8719 // No other scales are supported.
8726 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8727 SelectionDAG &DAG) const {
8728 MachineFunction &MF = DAG.getMachineFunction();
8729 MachineFrameInfo *MFI = MF.getFrameInfo();
8730 MFI->setReturnAddressIsTaken(true);
8732 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8736 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8738 // Make sure the function does not optimize away the store of the RA to
8740 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8741 FuncInfo->setLRStoreRequired();
8742 bool isPPC64 = PPCSubTarget.isPPC64();
8743 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8746 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8749 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8750 isPPC64? MVT::i64 : MVT::i32);
8751 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8752 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8754 MachinePointerInfo(), false, false, false, 0);
8757 // Just load the return address off the stack.
8758 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8759 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8760 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8763 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8764 SelectionDAG &DAG) const {
8766 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8768 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8769 bool isPPC64 = PtrVT == MVT::i64;
8771 MachineFunction &MF = DAG.getMachineFunction();
8772 MachineFrameInfo *MFI = MF.getFrameInfo();
8773 MFI->setFrameAddressIsTaken(true);
8775 // Naked functions never have a frame pointer, and so we use r1. For all
8776 // other functions, this decision must be delayed until during PEI.
8778 if (MF.getFunction()->getAttributes().hasAttribute(
8779 AttributeSet::FunctionIndex, Attribute::Naked))
8780 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8782 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8784 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8787 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8788 FrameAddr, MachinePointerInfo(), false, false,
8793 // FIXME? Maybe this could be a TableGen attribute on some registers and
8794 // this table could be generated automatically from RegInfo.
8795 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
8797 bool isPPC64 = PPCSubTarget.isPPC64();
8798 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8800 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
8801 (!isPPC64 && VT != MVT::i32))
8802 report_fatal_error("Invalid register global variable type");
8804 bool is64Bit = isPPC64 && VT == MVT::i64;
8805 unsigned Reg = StringSwitch<unsigned>(RegName)
8806 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
8807 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
8808 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
8809 (is64Bit ? PPC::X13 : PPC::R13))
8814 report_fatal_error("Invalid register name global variable");
8818 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8819 // The PowerPC target isn't yet aware of offsets.
8823 /// getOptimalMemOpType - Returns the target specific optimal type for load
8824 /// and store operations as a result of memset, memcpy, and memmove
8825 /// lowering. If DstAlign is zero that means it's safe to destination
8826 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8827 /// means there isn't a need to check it against alignment requirement,
8828 /// probably because the source does not need to be loaded. If 'IsMemset' is
8829 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8830 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8831 /// source is constant so it does not need to be loaded.
8832 /// It returns EVT::Other if the type should be determined using generic
8833 /// target-independent logic.
8834 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8835 unsigned DstAlign, unsigned SrcAlign,
8836 bool IsMemset, bool ZeroMemset,
8838 MachineFunction &MF) const {
8839 if (this->PPCSubTarget.isPPC64()) {
8846 /// \brief Returns true if it is beneficial to convert a load of a constant
8847 /// to just the constant itself.
8848 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8850 assert(Ty->isIntegerTy());
8852 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8853 if (BitSize == 0 || BitSize > 64)
8858 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8859 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8861 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8862 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8863 return NumBits1 == 64 && NumBits2 == 32;
8866 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8867 if (!VT1.isInteger() || !VT2.isInteger())
8869 unsigned NumBits1 = VT1.getSizeInBits();
8870 unsigned NumBits2 = VT2.getSizeInBits();
8871 return NumBits1 == 64 && NumBits2 == 32;
8874 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8875 return isInt<16>(Imm) || isUInt<16>(Imm);
8878 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8879 return isInt<16>(Imm) || isUInt<16>(Imm);
8882 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8885 if (DisablePPCUnaligned)
8888 // PowerPC supports unaligned memory access for simple non-vector types.
8889 // Although accessing unaligned addresses is not as efficient as accessing
8890 // aligned addresses, it is generally more efficient than manual expansion,
8891 // and generally only traps for software emulation when crossing page
8897 if (VT.getSimpleVT().isVector()) {
8898 if (PPCSubTarget.hasVSX()) {
8899 if (VT != MVT::v2f64 && VT != MVT::v2i64)
8906 if (VT == MVT::ppcf128)
8915 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8916 VT = VT.getScalarType();
8921 switch (VT.getSimpleVT().SimpleTy) {
8933 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
8934 EVT VT , unsigned DefinedValues) const {
8935 if (VT == MVT::v2i64)
8938 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
8941 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8942 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8943 return TargetLowering::getSchedulingPreference(N);
8948 // Create a fast isel object.
8950 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8951 const TargetLibraryInfo *LibInfo) const {
8952 return PPC::createFastISel(FuncInfo, LibInfo);