1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
42 // FIXME: Remove this once soft-float is supported.
43 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
44 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
46 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
47 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
49 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
50 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
52 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
53 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
55 // FIXME: Remove this once the bug has been fixed!
56 extern cl::opt<bool> ANDIGlueBug;
58 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
59 // If it isn't a Mach-O file then it's going to be a linux ELF
62 return new TargetLoweringObjectFileMachO();
64 return new PPC64LinuxTargetObjectFile();
67 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
68 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))),
69 Subtarget(*TM.getSubtargetImpl()) {
72 // Use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(true);
76 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
77 // arguments are at least 4/8 bytes aligned.
78 bool isPPC64 = Subtarget.isPPC64();
79 setMinStackArgumentAlignment(isPPC64 ? 8:4);
81 // Set up the register classes.
82 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
83 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
84 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
86 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
87 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
88 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
90 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
92 // PowerPC has pre-inc load and store's.
93 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
94 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
95 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
96 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
97 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
100 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
101 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
102 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
104 if (Subtarget.useCRBits()) {
105 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
107 if (isPPC64 || Subtarget.hasFPCVT()) {
108 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
109 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
110 isPPC64 ? MVT::i64 : MVT::i32);
111 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
112 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
113 isPPC64 ? MVT::i64 : MVT::i32);
115 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
116 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
119 // PowerPC does not support direct load / store of condition registers
120 setOperationAction(ISD::LOAD, MVT::i1, Custom);
121 setOperationAction(ISD::STORE, MVT::i1, Custom);
123 // FIXME: Remove this once the ANDI glue bug is fixed:
125 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
127 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
128 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
129 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
130 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
131 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
132 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
134 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
137 // This is used in the ppcf128->int sequence. Note it has different semantics
138 // from FP_ROUND: that rounds to nearest, this rounds to zero.
139 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
141 // We do not currently implement these libm ops for PowerPC.
142 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
144 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
145 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
146 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
147 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
149 // PowerPC has no SREM/UREM instructions
150 setOperationAction(ISD::SREM, MVT::i32, Expand);
151 setOperationAction(ISD::UREM, MVT::i32, Expand);
152 setOperationAction(ISD::SREM, MVT::i64, Expand);
153 setOperationAction(ISD::UREM, MVT::i64, Expand);
155 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
156 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
157 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
158 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
159 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
160 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
161 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
162 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
163 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
165 // We don't support sin/cos/sqrt/fmod/pow
166 setOperationAction(ISD::FSIN , MVT::f64, Expand);
167 setOperationAction(ISD::FCOS , MVT::f64, Expand);
168 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
169 setOperationAction(ISD::FREM , MVT::f64, Expand);
170 setOperationAction(ISD::FPOW , MVT::f64, Expand);
171 setOperationAction(ISD::FMA , MVT::f64, Legal);
172 setOperationAction(ISD::FSIN , MVT::f32, Expand);
173 setOperationAction(ISD::FCOS , MVT::f32, Expand);
174 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
175 setOperationAction(ISD::FREM , MVT::f32, Expand);
176 setOperationAction(ISD::FPOW , MVT::f32, Expand);
177 setOperationAction(ISD::FMA , MVT::f32, Legal);
179 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
181 // If we're enabling GP optimizations, use hardware square root
182 if (!Subtarget.hasFSQRT() &&
183 !(TM.Options.UnsafeFPMath &&
184 Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
185 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
187 if (!Subtarget.hasFSQRT() &&
188 !(TM.Options.UnsafeFPMath &&
189 Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
190 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
192 if (Subtarget.hasFCPSGN()) {
193 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
194 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
196 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
197 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
200 if (Subtarget.hasFPRND()) {
201 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
202 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
203 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
204 setOperationAction(ISD::FROUND, MVT::f64, Legal);
206 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
207 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
208 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
209 setOperationAction(ISD::FROUND, MVT::f32, Legal);
212 // PowerPC does not have BSWAP, CTPOP or CTTZ
213 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
217 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
218 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
219 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
220 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
222 if (Subtarget.hasPOPCNTD()) {
223 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
224 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
226 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
227 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
230 // PowerPC does not have ROTR
231 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
232 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
234 if (!Subtarget.useCRBits()) {
235 // PowerPC does not have Select
236 setOperationAction(ISD::SELECT, MVT::i32, Expand);
237 setOperationAction(ISD::SELECT, MVT::i64, Expand);
238 setOperationAction(ISD::SELECT, MVT::f32, Expand);
239 setOperationAction(ISD::SELECT, MVT::f64, Expand);
242 // PowerPC wants to turn select_cc of FP into fsel when possible.
243 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
244 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
246 // PowerPC wants to optimize integer setcc a bit
247 if (!Subtarget.useCRBits())
248 setOperationAction(ISD::SETCC, MVT::i32, Custom);
250 // PowerPC does not have BRCOND which requires SetCC
251 if (!Subtarget.useCRBits())
252 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
254 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
256 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
257 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
259 // PowerPC does not have [U|S]INT_TO_FP
260 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
261 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
263 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
264 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
265 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
266 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
268 // We cannot sextinreg(i1). Expand to shifts.
269 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
271 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
272 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
273 // support continuation, user-level threading, and etc.. As a result, no
274 // other SjLj exception interfaces are implemented and please don't build
275 // your own exception handling based on them.
276 // LLVM/Clang supports zero-cost DWARF exception handling.
277 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
278 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
280 // We want to legalize GlobalAddress and ConstantPool nodes into the
281 // appropriate instructions to materialize the address.
282 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
283 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
284 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
285 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
286 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
287 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
288 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
289 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
290 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
291 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
294 setOperationAction(ISD::TRAP, MVT::Other, Legal);
296 // TRAMPOLINE is custom lowered.
297 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
298 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
300 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
301 setOperationAction(ISD::VASTART , MVT::Other, Custom);
303 if (Subtarget.isSVR4ABI()) {
305 // VAARG always uses double-word chunks, so promote anything smaller.
306 setOperationAction(ISD::VAARG, MVT::i1, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i8, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::i16, Promote);
311 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
312 setOperationAction(ISD::VAARG, MVT::i32, Promote);
313 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
314 setOperationAction(ISD::VAARG, MVT::Other, Expand);
316 // VAARG is custom lowered with the 32-bit SVR4 ABI.
317 setOperationAction(ISD::VAARG, MVT::Other, Custom);
318 setOperationAction(ISD::VAARG, MVT::i64, Custom);
321 setOperationAction(ISD::VAARG, MVT::Other, Expand);
323 if (Subtarget.isSVR4ABI() && !isPPC64)
324 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
325 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
327 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
329 // Use the default implementation.
330 setOperationAction(ISD::VAEND , MVT::Other, Expand);
331 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
332 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
333 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
334 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
336 // We want to custom lower some of our intrinsics.
337 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
339 // To handle counter-based loop conditions.
340 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
342 // Comparisons that require checking two conditions.
343 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
351 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
352 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
353 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
354 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
356 if (Subtarget.has64BitSupport()) {
357 // They also have instructions for converting between i64 and fp.
358 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
359 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
360 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
361 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
362 // This is just the low 32 bits of a (signed) fp->i64 conversion.
363 // We cannot do this with Promote because i64 is not a legal type.
364 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
366 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
367 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
369 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
370 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
373 // With the instructions enabled under FPCVT, we can do everything.
374 if (Subtarget.hasFPCVT()) {
375 if (Subtarget.has64BitSupport()) {
376 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
377 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
378 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
379 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
382 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
383 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
384 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
385 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
388 if (Subtarget.use64BitRegs()) {
389 // 64-bit PowerPC implementations can support i64 types directly
390 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
391 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
392 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
393 // 64-bit PowerPC wants to expand i128 shifts itself.
394 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
395 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
396 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
398 // 32-bit PowerPC wants to expand i64 shifts itself.
399 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
400 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
401 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
404 if (Subtarget.hasAltivec()) {
405 // First set operation action for all vector types to expand. Then we
406 // will selectively turn on ones that can be effectively codegen'd.
407 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
408 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
409 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
411 // add/sub are legal for all supported vector VT's.
412 setOperationAction(ISD::ADD , VT, Legal);
413 setOperationAction(ISD::SUB , VT, Legal);
415 // We promote all shuffles to v16i8.
416 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
417 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
419 // We promote all non-typed operations to v4i32.
420 setOperationAction(ISD::AND , VT, Promote);
421 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
422 setOperationAction(ISD::OR , VT, Promote);
423 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
424 setOperationAction(ISD::XOR , VT, Promote);
425 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
426 setOperationAction(ISD::LOAD , VT, Promote);
427 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
428 setOperationAction(ISD::SELECT, VT, Promote);
429 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
430 setOperationAction(ISD::STORE, VT, Promote);
431 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
433 // No other operations are legal.
434 setOperationAction(ISD::MUL , VT, Expand);
435 setOperationAction(ISD::SDIV, VT, Expand);
436 setOperationAction(ISD::SREM, VT, Expand);
437 setOperationAction(ISD::UDIV, VT, Expand);
438 setOperationAction(ISD::UREM, VT, Expand);
439 setOperationAction(ISD::FDIV, VT, Expand);
440 setOperationAction(ISD::FREM, VT, Expand);
441 setOperationAction(ISD::FNEG, VT, Expand);
442 setOperationAction(ISD::FSQRT, VT, Expand);
443 setOperationAction(ISD::FLOG, VT, Expand);
444 setOperationAction(ISD::FLOG10, VT, Expand);
445 setOperationAction(ISD::FLOG2, VT, Expand);
446 setOperationAction(ISD::FEXP, VT, Expand);
447 setOperationAction(ISD::FEXP2, VT, Expand);
448 setOperationAction(ISD::FSIN, VT, Expand);
449 setOperationAction(ISD::FCOS, VT, Expand);
450 setOperationAction(ISD::FABS, VT, Expand);
451 setOperationAction(ISD::FPOWI, VT, Expand);
452 setOperationAction(ISD::FFLOOR, VT, Expand);
453 setOperationAction(ISD::FCEIL, VT, Expand);
454 setOperationAction(ISD::FTRUNC, VT, Expand);
455 setOperationAction(ISD::FRINT, VT, Expand);
456 setOperationAction(ISD::FNEARBYINT, VT, Expand);
457 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
458 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
459 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
460 setOperationAction(ISD::MULHU, VT, Expand);
461 setOperationAction(ISD::MULHS, VT, Expand);
462 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
463 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
464 setOperationAction(ISD::UDIVREM, VT, Expand);
465 setOperationAction(ISD::SDIVREM, VT, Expand);
466 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
467 setOperationAction(ISD::FPOW, VT, Expand);
468 setOperationAction(ISD::BSWAP, VT, Expand);
469 setOperationAction(ISD::CTPOP, VT, Expand);
470 setOperationAction(ISD::CTLZ, VT, Expand);
471 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
472 setOperationAction(ISD::CTTZ, VT, Expand);
473 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
474 setOperationAction(ISD::VSELECT, VT, Expand);
475 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
477 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
478 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
479 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
480 setTruncStoreAction(VT, InnerVT, Expand);
482 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
483 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
484 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
487 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
488 // with merges, splats, etc.
489 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
491 setOperationAction(ISD::AND , MVT::v4i32, Legal);
492 setOperationAction(ISD::OR , MVT::v4i32, Legal);
493 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
494 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
495 setOperationAction(ISD::SELECT, MVT::v4i32,
496 Subtarget.useCRBits() ? Legal : Expand);
497 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
498 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
499 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
500 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
501 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
502 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
503 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
504 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
505 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
507 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
508 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
509 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
510 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
512 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
513 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
515 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
516 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
517 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
520 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
521 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
524 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
525 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
527 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
528 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
529 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
530 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
532 // Altivec does not contain unordered floating-point compare instructions
533 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
534 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
535 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
536 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
538 if (Subtarget.hasVSX()) {
539 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
540 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
542 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
543 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
544 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
545 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
546 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
548 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
550 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
551 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
553 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
554 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
558 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
559 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
560 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
562 // Share the Altivec comparison restrictions.
563 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
564 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
566 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
568 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
569 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
571 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
573 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
575 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
576 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
578 // VSX v2i64 only supports non-arithmetic operations.
579 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
580 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
582 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
583 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
584 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
586 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
588 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
589 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
590 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
591 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
593 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
595 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
596 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
597 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
598 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
600 // Vector operation legalization checks the result type of
601 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
602 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
603 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
604 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
605 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
607 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
611 if (Subtarget.has64BitSupport()) {
612 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
613 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
616 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
617 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
618 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
619 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
621 setBooleanContents(ZeroOrOneBooleanContent);
622 // Altivec instructions set fields to all zeros or all ones.
623 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
626 // These libcalls are not available in 32-bit.
627 setLibcallName(RTLIB::SHL_I128, nullptr);
628 setLibcallName(RTLIB::SRL_I128, nullptr);
629 setLibcallName(RTLIB::SRA_I128, nullptr);
633 setStackPointerRegisterToSaveRestore(PPC::X1);
634 setExceptionPointerRegister(PPC::X3);
635 setExceptionSelectorRegister(PPC::X4);
637 setStackPointerRegisterToSaveRestore(PPC::R1);
638 setExceptionPointerRegister(PPC::R3);
639 setExceptionSelectorRegister(PPC::R4);
642 // We have target-specific dag combine patterns for the following nodes:
643 setTargetDAGCombine(ISD::SINT_TO_FP);
644 setTargetDAGCombine(ISD::LOAD);
645 setTargetDAGCombine(ISD::STORE);
646 setTargetDAGCombine(ISD::BR_CC);
647 if (Subtarget.useCRBits())
648 setTargetDAGCombine(ISD::BRCOND);
649 setTargetDAGCombine(ISD::BSWAP);
650 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
652 setTargetDAGCombine(ISD::SIGN_EXTEND);
653 setTargetDAGCombine(ISD::ZERO_EXTEND);
654 setTargetDAGCombine(ISD::ANY_EXTEND);
656 if (Subtarget.useCRBits()) {
657 setTargetDAGCombine(ISD::TRUNCATE);
658 setTargetDAGCombine(ISD::SETCC);
659 setTargetDAGCombine(ISD::SELECT_CC);
662 // Use reciprocal estimates.
663 if (TM.Options.UnsafeFPMath) {
664 setTargetDAGCombine(ISD::FDIV);
665 setTargetDAGCombine(ISD::FSQRT);
668 // Darwin long double math library functions have $LDBL128 appended.
669 if (Subtarget.isDarwin()) {
670 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
671 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
672 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
673 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
674 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
675 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
676 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
677 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
678 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
679 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
682 // With 32 condition bits, we don't need to sink (and duplicate) compares
683 // aggressively in CodeGenPrep.
684 if (Subtarget.useCRBits())
685 setHasMultipleConditionRegisters();
687 setMinFunctionAlignment(2);
688 if (Subtarget.isDarwin())
689 setPrefFunctionAlignment(4);
691 setInsertFencesForAtomic(true);
693 if (Subtarget.enableMachineScheduler())
694 setSchedulingPreference(Sched::Source);
696 setSchedulingPreference(Sched::Hybrid);
698 computeRegisterProperties();
700 // The Freescale cores does better with aggressive inlining of memcpy and
701 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
702 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
703 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
704 MaxStoresPerMemset = 32;
705 MaxStoresPerMemsetOptSize = 16;
706 MaxStoresPerMemcpy = 32;
707 MaxStoresPerMemcpyOptSize = 8;
708 MaxStoresPerMemmove = 32;
709 MaxStoresPerMemmoveOptSize = 8;
711 setPrefFunctionAlignment(4);
715 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
716 /// the desired ByVal argument alignment.
717 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
718 unsigned MaxMaxAlign) {
719 if (MaxAlign == MaxMaxAlign)
721 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
722 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
724 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
726 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
727 unsigned EltAlign = 0;
728 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
729 if (EltAlign > MaxAlign)
731 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
732 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
733 unsigned EltAlign = 0;
734 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
735 if (EltAlign > MaxAlign)
737 if (MaxAlign == MaxMaxAlign)
743 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
744 /// function arguments in the caller parameter area.
745 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
746 // Darwin passes everything on 4 byte boundary.
747 if (Subtarget.isDarwin())
750 // 16byte and wider vectors are passed on 16byte boundary.
751 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
752 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
753 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
754 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
758 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
760 default: return nullptr;
761 case PPCISD::FSEL: return "PPCISD::FSEL";
762 case PPCISD::FCFID: return "PPCISD::FCFID";
763 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
764 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
765 case PPCISD::FRE: return "PPCISD::FRE";
766 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
767 case PPCISD::STFIWX: return "PPCISD::STFIWX";
768 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
769 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
770 case PPCISD::VPERM: return "PPCISD::VPERM";
771 case PPCISD::Hi: return "PPCISD::Hi";
772 case PPCISD::Lo: return "PPCISD::Lo";
773 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
774 case PPCISD::LOAD: return "PPCISD::LOAD";
775 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
776 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
777 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
778 case PPCISD::SRL: return "PPCISD::SRL";
779 case PPCISD::SRA: return "PPCISD::SRA";
780 case PPCISD::SHL: return "PPCISD::SHL";
781 case PPCISD::CALL: return "PPCISD::CALL";
782 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
783 case PPCISD::MTCTR: return "PPCISD::MTCTR";
784 case PPCISD::BCTRL: return "PPCISD::BCTRL";
785 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
786 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
787 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
788 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
789 case PPCISD::VCMP: return "PPCISD::VCMP";
790 case PPCISD::VCMPo: return "PPCISD::VCMPo";
791 case PPCISD::LBRX: return "PPCISD::LBRX";
792 case PPCISD::STBRX: return "PPCISD::STBRX";
793 case PPCISD::LARX: return "PPCISD::LARX";
794 case PPCISD::STCX: return "PPCISD::STCX";
795 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
796 case PPCISD::BDNZ: return "PPCISD::BDNZ";
797 case PPCISD::BDZ: return "PPCISD::BDZ";
798 case PPCISD::MFFS: return "PPCISD::MFFS";
799 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
800 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
801 case PPCISD::CR6SET: return "PPCISD::CR6SET";
802 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
803 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
804 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
805 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
806 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
807 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
808 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
809 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
810 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
811 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
812 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
813 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
814 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
815 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
816 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
817 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
818 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
819 case PPCISD::SC: return "PPCISD::SC";
823 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
825 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
826 return VT.changeVectorElementTypeToInteger();
829 //===----------------------------------------------------------------------===//
830 // Node matching predicates, for use by the tblgen matching code.
831 //===----------------------------------------------------------------------===//
833 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
834 static bool isFloatingPointZero(SDValue Op) {
835 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
836 return CFP->getValueAPF().isZero();
837 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
838 // Maybe this has already been legalized into the constant pool?
839 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
840 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
841 return CFP->getValueAPF().isZero();
846 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
847 /// true if Op is undef or if it matches the specified value.
848 static bool isConstantOrUndef(int Op, int Val) {
849 return Op < 0 || Op == Val;
852 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
853 /// VPKUHUM instruction.
854 /// The ShuffleKind distinguishes between big-endian operations with
855 /// two different inputs (0), either-endian operations with two identical
856 /// inputs (1), and little-endian operantion with two different inputs (2).
857 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
858 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
860 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
861 if (ShuffleKind == 0) {
864 for (unsigned i = 0; i != 16; ++i)
865 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
867 } else if (ShuffleKind == 2) {
870 for (unsigned i = 0; i != 16; ++i)
871 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
873 } else if (ShuffleKind == 1) {
874 unsigned j = IsLE ? 0 : 1;
875 for (unsigned i = 0; i != 8; ++i)
876 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
877 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
883 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
884 /// VPKUWUM instruction.
885 /// The ShuffleKind distinguishes between big-endian operations with
886 /// two different inputs (0), either-endian operations with two identical
887 /// inputs (1), and little-endian operantion with two different inputs (2).
888 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
889 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
891 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
892 if (ShuffleKind == 0) {
895 for (unsigned i = 0; i != 16; i += 2)
896 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
897 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
899 } else if (ShuffleKind == 2) {
902 for (unsigned i = 0; i != 16; i += 2)
903 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
904 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
906 } else if (ShuffleKind == 1) {
907 unsigned j = IsLE ? 0 : 2;
908 for (unsigned i = 0; i != 8; i += 2)
909 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
910 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
911 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
912 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
918 /// isVMerge - Common function, used to match vmrg* shuffles.
920 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
921 unsigned LHSStart, unsigned RHSStart) {
922 if (N->getValueType(0) != MVT::v16i8)
924 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
925 "Unsupported merge size!");
927 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
928 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
929 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
930 LHSStart+j+i*UnitSize) ||
931 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
932 RHSStart+j+i*UnitSize))
938 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
939 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
940 /// The ShuffleKind distinguishes between big-endian merges with two
941 /// different inputs (0), either-endian merges with two identical inputs (1),
942 /// and little-endian merges with two different inputs (2). For the latter,
943 /// the input operands are swapped (see PPCInstrAltivec.td).
944 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
945 unsigned ShuffleKind, SelectionDAG &DAG) {
946 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
947 if (ShuffleKind == 1) // unary
948 return isVMerge(N, UnitSize, 0, 0);
949 else if (ShuffleKind == 2) // swapped
950 return isVMerge(N, UnitSize, 0, 16);
954 if (ShuffleKind == 1) // unary
955 return isVMerge(N, UnitSize, 8, 8);
956 else if (ShuffleKind == 0) // normal
957 return isVMerge(N, UnitSize, 8, 24);
963 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
964 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
965 /// The ShuffleKind distinguishes between big-endian merges with two
966 /// different inputs (0), either-endian merges with two identical inputs (1),
967 /// and little-endian merges with two different inputs (2). For the latter,
968 /// the input operands are swapped (see PPCInstrAltivec.td).
969 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
970 unsigned ShuffleKind, SelectionDAG &DAG) {
971 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
972 if (ShuffleKind == 1) // unary
973 return isVMerge(N, UnitSize, 8, 8);
974 else if (ShuffleKind == 2) // swapped
975 return isVMerge(N, UnitSize, 8, 24);
979 if (ShuffleKind == 1) // unary
980 return isVMerge(N, UnitSize, 0, 0);
981 else if (ShuffleKind == 0) // normal
982 return isVMerge(N, UnitSize, 0, 16);
989 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
990 /// amount, otherwise return -1.
991 /// The ShuffleKind distinguishes between big-endian operations with two
992 /// different inputs (0), either-endian operations with two identical inputs
993 /// (1), and little-endian operations with two different inputs (2). For the
994 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
995 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
997 if (N->getValueType(0) != MVT::v16i8)
1000 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1002 // Find the first non-undef value in the shuffle mask.
1004 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1007 if (i == 16) return -1; // all undef.
1009 // Otherwise, check to see if the rest of the elements are consecutively
1010 // numbered from this value.
1011 unsigned ShiftAmt = SVOp->getMaskElt(i);
1012 if (ShiftAmt < i) return -1;
1015 bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1018 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1019 // Check the rest of the elements to see if they are consecutive.
1020 for (++i; i != 16; ++i)
1021 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1023 } else if (ShuffleKind == 1) {
1024 // Check the rest of the elements to see if they are consecutive.
1025 for (++i; i != 16; ++i)
1026 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1031 if (ShuffleKind == 2 && isLE)
1032 ShiftAmt = 16 - ShiftAmt;
1037 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1038 /// specifies a splat of a single element that is suitable for input to
1039 /// VSPLTB/VSPLTH/VSPLTW.
1040 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1041 assert(N->getValueType(0) == MVT::v16i8 &&
1042 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1044 // This is a splat operation if each element of the permute is the same, and
1045 // if the value doesn't reference the second vector.
1046 unsigned ElementBase = N->getMaskElt(0);
1048 // FIXME: Handle UNDEF elements too!
1049 if (ElementBase >= 16)
1052 // Check that the indices are consecutive, in the case of a multi-byte element
1053 // splatted with a v16i8 mask.
1054 for (unsigned i = 1; i != EltSize; ++i)
1055 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1058 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1059 if (N->getMaskElt(i) < 0) continue;
1060 for (unsigned j = 0; j != EltSize; ++j)
1061 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1067 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1069 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1070 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1072 APInt APVal, APUndef;
1076 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1077 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1078 return CFP->getValueAPF().isNegZero();
1083 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1084 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1085 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1086 SelectionDAG &DAG) {
1087 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1088 assert(isSplatShuffleMask(SVOp, EltSize));
1089 if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1090 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1092 return SVOp->getMaskElt(0) / EltSize;
1095 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1096 /// by using a vspltis[bhw] instruction of the specified element size, return
1097 /// the constant being splatted. The ByteSize field indicates the number of
1098 /// bytes of each element [124] -> [bhw].
1099 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1100 SDValue OpVal(nullptr, 0);
1102 // If ByteSize of the splat is bigger than the element size of the
1103 // build_vector, then we have a case where we are checking for a splat where
1104 // multiple elements of the buildvector are folded together into a single
1105 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1106 unsigned EltSize = 16/N->getNumOperands();
1107 if (EltSize < ByteSize) {
1108 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1109 SDValue UniquedVals[4];
1110 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1112 // See if all of the elements in the buildvector agree across.
1113 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1114 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1115 // If the element isn't a constant, bail fully out.
1116 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1119 if (!UniquedVals[i&(Multiple-1)].getNode())
1120 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1121 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1122 return SDValue(); // no match.
1125 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1126 // either constant or undef values that are identical for each chunk. See
1127 // if these chunks can form into a larger vspltis*.
1129 // Check to see if all of the leading entries are either 0 or -1. If
1130 // neither, then this won't fit into the immediate field.
1131 bool LeadingZero = true;
1132 bool LeadingOnes = true;
1133 for (unsigned i = 0; i != Multiple-1; ++i) {
1134 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1136 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1137 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1139 // Finally, check the least significant entry.
1141 if (!UniquedVals[Multiple-1].getNode())
1142 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1143 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1145 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1148 if (!UniquedVals[Multiple-1].getNode())
1149 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1150 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1151 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1152 return DAG.getTargetConstant(Val, MVT::i32);
1158 // Check to see if this buildvec has a single non-undef value in its elements.
1159 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1160 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1161 if (!OpVal.getNode())
1162 OpVal = N->getOperand(i);
1163 else if (OpVal != N->getOperand(i))
1167 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1169 unsigned ValSizeInBytes = EltSize;
1171 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1172 Value = CN->getZExtValue();
1173 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1174 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1175 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1178 // If the splat value is larger than the element value, then we can never do
1179 // this splat. The only case that we could fit the replicated bits into our
1180 // immediate field for would be zero, and we prefer to use vxor for it.
1181 if (ValSizeInBytes < ByteSize) return SDValue();
1183 // If the element value is larger than the splat value, cut it in half and
1184 // check to see if the two halves are equal. Continue doing this until we
1185 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1186 while (ValSizeInBytes > ByteSize) {
1187 ValSizeInBytes >>= 1;
1189 // If the top half equals the bottom half, we're still ok.
1190 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1191 (Value & ((1 << (8*ValSizeInBytes))-1)))
1195 // Properly sign extend the value.
1196 int MaskVal = SignExtend32(Value, ByteSize * 8);
1198 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1199 if (MaskVal == 0) return SDValue();
1201 // Finally, if this value fits in a 5 bit sext field, return it
1202 if (SignExtend32<5>(MaskVal) == MaskVal)
1203 return DAG.getTargetConstant(MaskVal, MVT::i32);
1207 //===----------------------------------------------------------------------===//
1208 // Addressing Mode Selection
1209 //===----------------------------------------------------------------------===//
1211 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1212 /// or 64-bit immediate, and if the value can be accurately represented as a
1213 /// sign extension from a 16-bit value. If so, this returns true and the
1215 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1216 if (!isa<ConstantSDNode>(N))
1219 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1220 if (N->getValueType(0) == MVT::i32)
1221 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1223 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1225 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1226 return isIntS16Immediate(Op.getNode(), Imm);
1230 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1231 /// can be represented as an indexed [r+r] operation. Returns false if it
1232 /// can be more efficiently represented with [r+imm].
1233 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1235 SelectionDAG &DAG) const {
1237 if (N.getOpcode() == ISD::ADD) {
1238 if (isIntS16Immediate(N.getOperand(1), imm))
1239 return false; // r+i
1240 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1241 return false; // r+i
1243 Base = N.getOperand(0);
1244 Index = N.getOperand(1);
1246 } else if (N.getOpcode() == ISD::OR) {
1247 if (isIntS16Immediate(N.getOperand(1), imm))
1248 return false; // r+i can fold it if we can.
1250 // If this is an or of disjoint bitfields, we can codegen this as an add
1251 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1253 APInt LHSKnownZero, LHSKnownOne;
1254 APInt RHSKnownZero, RHSKnownOne;
1255 DAG.computeKnownBits(N.getOperand(0),
1256 LHSKnownZero, LHSKnownOne);
1258 if (LHSKnownZero.getBoolValue()) {
1259 DAG.computeKnownBits(N.getOperand(1),
1260 RHSKnownZero, RHSKnownOne);
1261 // If all of the bits are known zero on the LHS or RHS, the add won't
1263 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1264 Base = N.getOperand(0);
1265 Index = N.getOperand(1);
1274 // If we happen to be doing an i64 load or store into a stack slot that has
1275 // less than a 4-byte alignment, then the frame-index elimination may need to
1276 // use an indexed load or store instruction (because the offset may not be a
1277 // multiple of 4). The extra register needed to hold the offset comes from the
1278 // register scavenger, and it is possible that the scavenger will need to use
1279 // an emergency spill slot. As a result, we need to make sure that a spill slot
1280 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1282 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1283 // FIXME: This does not handle the LWA case.
1287 // NOTE: We'll exclude negative FIs here, which come from argument
1288 // lowering, because there are no known test cases triggering this problem
1289 // using packed structures (or similar). We can remove this exclusion if
1290 // we find such a test case. The reason why this is so test-case driven is
1291 // because this entire 'fixup' is only to prevent crashes (from the
1292 // register scavenger) on not-really-valid inputs. For example, if we have:
1294 // %b = bitcast i1* %a to i64*
1295 // store i64* a, i64 b
1296 // then the store should really be marked as 'align 1', but is not. If it
1297 // were marked as 'align 1' then the indexed form would have been
1298 // instruction-selected initially, and the problem this 'fixup' is preventing
1299 // won't happen regardless.
1303 MachineFunction &MF = DAG.getMachineFunction();
1304 MachineFrameInfo *MFI = MF.getFrameInfo();
1306 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1310 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1311 FuncInfo->setHasNonRISpills();
1314 /// Returns true if the address N can be represented by a base register plus
1315 /// a signed 16-bit displacement [r+imm], and if it is not better
1316 /// represented as reg+reg. If Aligned is true, only accept displacements
1317 /// suitable for STD and friends, i.e. multiples of 4.
1318 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1321 bool Aligned) const {
1322 // FIXME dl should come from parent load or store, not from address
1324 // If this can be more profitably realized as r+r, fail.
1325 if (SelectAddressRegReg(N, Disp, Base, DAG))
1328 if (N.getOpcode() == ISD::ADD) {
1330 if (isIntS16Immediate(N.getOperand(1), imm) &&
1331 (!Aligned || (imm & 3) == 0)) {
1332 Disp = DAG.getTargetConstant(imm, N.getValueType());
1333 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1334 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1335 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1337 Base = N.getOperand(0);
1339 return true; // [r+i]
1340 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1341 // Match LOAD (ADD (X, Lo(G))).
1342 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1343 && "Cannot handle constant offsets yet!");
1344 Disp = N.getOperand(1).getOperand(0); // The global address.
1345 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1346 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1347 Disp.getOpcode() == ISD::TargetConstantPool ||
1348 Disp.getOpcode() == ISD::TargetJumpTable);
1349 Base = N.getOperand(0);
1350 return true; // [&g+r]
1352 } else if (N.getOpcode() == ISD::OR) {
1354 if (isIntS16Immediate(N.getOperand(1), imm) &&
1355 (!Aligned || (imm & 3) == 0)) {
1356 // If this is an or of disjoint bitfields, we can codegen this as an add
1357 // (for better address arithmetic) if the LHS and RHS of the OR are
1358 // provably disjoint.
1359 APInt LHSKnownZero, LHSKnownOne;
1360 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1362 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1363 // If all of the bits are known zero on the LHS or RHS, the add won't
1365 if (FrameIndexSDNode *FI =
1366 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1367 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1368 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1370 Base = N.getOperand(0);
1372 Disp = DAG.getTargetConstant(imm, N.getValueType());
1376 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1377 // Loading from a constant address.
1379 // If this address fits entirely in a 16-bit sext immediate field, codegen
1382 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1383 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1384 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1385 CN->getValueType(0));
1389 // Handle 32-bit sext immediates with LIS + addr mode.
1390 if ((CN->getValueType(0) == MVT::i32 ||
1391 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1392 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1393 int Addr = (int)CN->getZExtValue();
1395 // Otherwise, break this down into an LIS + disp.
1396 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1398 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1399 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1400 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1405 Disp = DAG.getTargetConstant(0, getPointerTy());
1406 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1407 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1408 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1411 return true; // [r+0]
1414 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1415 /// represented as an indexed [r+r] operation.
1416 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1418 SelectionDAG &DAG) const {
1419 // Check to see if we can easily represent this as an [r+r] address. This
1420 // will fail if it thinks that the address is more profitably represented as
1421 // reg+imm, e.g. where imm = 0.
1422 if (SelectAddressRegReg(N, Base, Index, DAG))
1425 // If the operand is an addition, always emit this as [r+r], since this is
1426 // better (for code size, and execution, as the memop does the add for free)
1427 // than emitting an explicit add.
1428 if (N.getOpcode() == ISD::ADD) {
1429 Base = N.getOperand(0);
1430 Index = N.getOperand(1);
1434 // Otherwise, do it the hard way, using R0 as the base register.
1435 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1441 /// getPreIndexedAddressParts - returns true by value, base pointer and
1442 /// offset pointer and addressing mode by reference if the node's address
1443 /// can be legally represented as pre-indexed load / store address.
1444 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1446 ISD::MemIndexedMode &AM,
1447 SelectionDAG &DAG) const {
1448 if (DisablePPCPreinc) return false;
1454 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1455 Ptr = LD->getBasePtr();
1456 VT = LD->getMemoryVT();
1457 Alignment = LD->getAlignment();
1458 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1459 Ptr = ST->getBasePtr();
1460 VT = ST->getMemoryVT();
1461 Alignment = ST->getAlignment();
1466 // PowerPC doesn't have preinc load/store instructions for vectors.
1470 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1472 // Common code will reject creating a pre-inc form if the base pointer
1473 // is a frame index, or if N is a store and the base pointer is either
1474 // the same as or a predecessor of the value being stored. Check for
1475 // those situations here, and try with swapped Base/Offset instead.
1478 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1481 SDValue Val = cast<StoreSDNode>(N)->getValue();
1482 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1487 std::swap(Base, Offset);
1493 // LDU/STU can only handle immediates that are a multiple of 4.
1494 if (VT != MVT::i64) {
1495 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1498 // LDU/STU need an address with at least 4-byte alignment.
1502 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1506 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1507 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1508 // sext i32 to i64 when addr mode is r+i.
1509 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1510 LD->getExtensionType() == ISD::SEXTLOAD &&
1511 isa<ConstantSDNode>(Offset))
1519 //===----------------------------------------------------------------------===//
1520 // LowerOperation implementation
1521 //===----------------------------------------------------------------------===//
1523 /// GetLabelAccessInfo - Return true if we should reference labels using a
1524 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1525 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1526 unsigned &LoOpFlags,
1527 const GlobalValue *GV = nullptr) {
1528 HiOpFlags = PPCII::MO_HA;
1529 LoOpFlags = PPCII::MO_LO;
1531 // Don't use the pic base if not in PIC relocation model.
1532 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1535 HiOpFlags |= PPCII::MO_PIC_FLAG;
1536 LoOpFlags |= PPCII::MO_PIC_FLAG;
1539 // If this is a reference to a global value that requires a non-lazy-ptr, make
1540 // sure that instruction lowering adds it.
1541 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1542 HiOpFlags |= PPCII::MO_NLP_FLAG;
1543 LoOpFlags |= PPCII::MO_NLP_FLAG;
1545 if (GV->hasHiddenVisibility()) {
1546 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1547 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1554 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1555 SelectionDAG &DAG) {
1556 EVT PtrVT = HiPart.getValueType();
1557 SDValue Zero = DAG.getConstant(0, PtrVT);
1560 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1561 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1563 // With PIC, the first instruction is actually "GR+hi(&G)".
1565 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1566 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1568 // Generate non-pic code that has direct accesses to the constant pool.
1569 // The address of the global is just (hi(&g)+lo(&g)).
1570 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1573 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1574 SelectionDAG &DAG) const {
1575 EVT PtrVT = Op.getValueType();
1576 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1577 const Constant *C = CP->getConstVal();
1579 // 64-bit SVR4 ABI code is always position-independent.
1580 // The actual address of the GlobalValue is stored in the TOC.
1581 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1582 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1583 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1584 DAG.getRegister(PPC::X2, MVT::i64));
1587 unsigned MOHiFlag, MOLoFlag;
1588 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1590 if (isPIC && Subtarget.isSVR4ABI()) {
1591 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1592 PPCII::MO_PIC_FLAG);
1594 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1595 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1599 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1601 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1602 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1605 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1606 EVT PtrVT = Op.getValueType();
1607 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1609 // 64-bit SVR4 ABI code is always position-independent.
1610 // The actual address of the GlobalValue is stored in the TOC.
1611 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1612 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1613 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1614 DAG.getRegister(PPC::X2, MVT::i64));
1617 unsigned MOHiFlag, MOLoFlag;
1618 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1620 if (isPIC && Subtarget.isSVR4ABI()) {
1621 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1622 PPCII::MO_PIC_FLAG);
1624 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1625 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1628 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1629 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1630 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1633 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1634 SelectionDAG &DAG) const {
1635 EVT PtrVT = Op.getValueType();
1637 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1639 unsigned MOHiFlag, MOLoFlag;
1640 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1641 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1642 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1643 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1646 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1647 SelectionDAG &DAG) const {
1649 // FIXME: TLS addresses currently use medium model code sequences,
1650 // which is the most useful form. Eventually support for small and
1651 // large models could be added if users need it, at the cost of
1652 // additional complexity.
1653 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1655 const GlobalValue *GV = GA->getGlobal();
1656 EVT PtrVT = getPointerTy();
1657 bool is64bit = Subtarget.isPPC64();
1659 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1661 if (Model == TLSModel::LocalExec) {
1662 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1663 PPCII::MO_TPREL_HA);
1664 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1665 PPCII::MO_TPREL_LO);
1666 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1667 is64bit ? MVT::i64 : MVT::i32);
1668 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1669 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1672 if (Model == TLSModel::InitialExec) {
1673 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1674 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1678 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1679 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1680 PtrVT, GOTReg, TGA);
1682 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1683 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1684 PtrVT, TGA, GOTPtr);
1685 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1688 if (Model == TLSModel::GeneralDynamic) {
1689 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1692 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1693 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1696 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1698 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1701 // We need a chain node, and don't have one handy. The underlying
1702 // call has no side effects, so using the function entry node
1704 SDValue Chain = DAG.getEntryNode();
1705 Chain = DAG.getCopyToReg(Chain, dl,
1706 is64bit ? PPC::X3 : PPC::R3, GOTEntry);
1707 SDValue ParmReg = DAG.getRegister(is64bit ? PPC::X3 : PPC::R3,
1708 is64bit ? MVT::i64 : MVT::i32);
1709 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1710 PtrVT, ParmReg, TGA);
1711 // The return value from GET_TLS_ADDR really is in X3 already, but
1712 // some hacks are needed here to tie everything together. The extra
1713 // copies dissolve during subsequent transforms.
1714 Chain = DAG.getCopyToReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, TLSAddr);
1715 return DAG.getCopyFromReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, PtrVT);
1718 if (Model == TLSModel::LocalDynamic) {
1719 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1722 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1723 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1726 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1728 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1731 // We need a chain node, and don't have one handy. The underlying
1732 // call has no side effects, so using the function entry node
1734 SDValue Chain = DAG.getEntryNode();
1735 Chain = DAG.getCopyToReg(Chain, dl,
1736 is64bit ? PPC::X3 : PPC::R3, GOTEntry);
1737 SDValue ParmReg = DAG.getRegister(is64bit ? PPC::X3 : PPC::R3,
1738 is64bit ? MVT::i64 : MVT::i32);
1739 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1740 PtrVT, ParmReg, TGA);
1741 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1742 // some hacks are needed here to tie everything together. The extra
1743 // copies dissolve during subsequent transforms.
1744 Chain = DAG.getCopyToReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, TLSAddr);
1745 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1746 Chain, ParmReg, TGA);
1747 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1750 llvm_unreachable("Unknown TLS model!");
1753 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1754 SelectionDAG &DAG) const {
1755 EVT PtrVT = Op.getValueType();
1756 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1758 const GlobalValue *GV = GSDN->getGlobal();
1760 // 64-bit SVR4 ABI code is always position-independent.
1761 // The actual address of the GlobalValue is stored in the TOC.
1762 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1763 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1764 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1765 DAG.getRegister(PPC::X2, MVT::i64));
1768 unsigned MOHiFlag, MOLoFlag;
1769 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1771 if (isPIC && Subtarget.isSVR4ABI()) {
1772 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1774 PPCII::MO_PIC_FLAG);
1775 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1776 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1780 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1782 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1784 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1786 // If the global reference is actually to a non-lazy-pointer, we have to do an
1787 // extra load to get the address of the global.
1788 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1789 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1790 false, false, false, 0);
1794 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1795 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1798 if (Op.getValueType() == MVT::v2i64) {
1799 // When the operands themselves are v2i64 values, we need to do something
1800 // special because VSX has no underlying comparison operations for these.
1801 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1802 // Equality can be handled by casting to the legal type for Altivec
1803 // comparisons, everything else needs to be expanded.
1804 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1805 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1806 DAG.getSetCC(dl, MVT::v4i32,
1807 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1808 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1815 // We handle most of these in the usual way.
1819 // If we're comparing for equality to zero, expose the fact that this is
1820 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1821 // fold the new nodes.
1822 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1823 if (C->isNullValue() && CC == ISD::SETEQ) {
1824 EVT VT = Op.getOperand(0).getValueType();
1825 SDValue Zext = Op.getOperand(0);
1826 if (VT.bitsLT(MVT::i32)) {
1828 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1830 unsigned Log2b = Log2_32(VT.getSizeInBits());
1831 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1832 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1833 DAG.getConstant(Log2b, MVT::i32));
1834 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1836 // Leave comparisons against 0 and -1 alone for now, since they're usually
1837 // optimized. FIXME: revisit this when we can custom lower all setcc
1839 if (C->isAllOnesValue() || C->isNullValue())
1843 // If we have an integer seteq/setne, turn it into a compare against zero
1844 // by xor'ing the rhs with the lhs, which is faster than setting a
1845 // condition register, reading it back out, and masking the correct bit. The
1846 // normal approach here uses sub to do this instead of xor. Using xor exposes
1847 // the result to other bit-twiddling opportunities.
1848 EVT LHSVT = Op.getOperand(0).getValueType();
1849 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1850 EVT VT = Op.getValueType();
1851 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1853 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1858 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1859 const PPCSubtarget &Subtarget) const {
1860 SDNode *Node = Op.getNode();
1861 EVT VT = Node->getValueType(0);
1862 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1863 SDValue InChain = Node->getOperand(0);
1864 SDValue VAListPtr = Node->getOperand(1);
1865 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1868 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1871 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1872 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1873 false, false, false, 0);
1874 InChain = GprIndex.getValue(1);
1876 if (VT == MVT::i64) {
1877 // Check if GprIndex is even
1878 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1879 DAG.getConstant(1, MVT::i32));
1880 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1881 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1882 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1883 DAG.getConstant(1, MVT::i32));
1884 // Align GprIndex to be even if it isn't
1885 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1889 // fpr index is 1 byte after gpr
1890 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1891 DAG.getConstant(1, MVT::i32));
1894 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1895 FprPtr, MachinePointerInfo(SV), MVT::i8,
1896 false, false, false, 0);
1897 InChain = FprIndex.getValue(1);
1899 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1900 DAG.getConstant(8, MVT::i32));
1902 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1903 DAG.getConstant(4, MVT::i32));
1906 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1907 MachinePointerInfo(), false, false,
1909 InChain = OverflowArea.getValue(1);
1911 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1912 MachinePointerInfo(), false, false,
1914 InChain = RegSaveArea.getValue(1);
1916 // select overflow_area if index > 8
1917 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1918 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1920 // adjustment constant gpr_index * 4/8
1921 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1922 VT.isInteger() ? GprIndex : FprIndex,
1923 DAG.getConstant(VT.isInteger() ? 4 : 8,
1926 // OurReg = RegSaveArea + RegConstant
1927 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1930 // Floating types are 32 bytes into RegSaveArea
1931 if (VT.isFloatingPoint())
1932 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1933 DAG.getConstant(32, MVT::i32));
1935 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1936 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1937 VT.isInteger() ? GprIndex : FprIndex,
1938 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1941 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1942 VT.isInteger() ? VAListPtr : FprPtr,
1943 MachinePointerInfo(SV),
1944 MVT::i8, false, false, 0);
1946 // determine if we should load from reg_save_area or overflow_area
1947 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1949 // increase overflow_area by 4/8 if gpr/fpr > 8
1950 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1951 DAG.getConstant(VT.isInteger() ? 4 : 8,
1954 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1957 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1959 MachinePointerInfo(),
1960 MVT::i32, false, false, 0);
1962 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1963 false, false, false, 0);
1966 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1967 const PPCSubtarget &Subtarget) const {
1968 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1970 // We have to copy the entire va_list struct:
1971 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1972 return DAG.getMemcpy(Op.getOperand(0), Op,
1973 Op.getOperand(1), Op.getOperand(2),
1974 DAG.getConstant(12, MVT::i32), 8, false, true,
1975 MachinePointerInfo(), MachinePointerInfo());
1978 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1979 SelectionDAG &DAG) const {
1980 return Op.getOperand(0);
1983 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1984 SelectionDAG &DAG) const {
1985 SDValue Chain = Op.getOperand(0);
1986 SDValue Trmp = Op.getOperand(1); // trampoline
1987 SDValue FPtr = Op.getOperand(2); // nested function
1988 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1991 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1992 bool isPPC64 = (PtrVT == MVT::i64);
1994 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1997 TargetLowering::ArgListTy Args;
1998 TargetLowering::ArgListEntry Entry;
2000 Entry.Ty = IntPtrTy;
2001 Entry.Node = Trmp; Args.push_back(Entry);
2003 // TrampSize == (isPPC64 ? 48 : 40);
2004 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2005 isPPC64 ? MVT::i64 : MVT::i32);
2006 Args.push_back(Entry);
2008 Entry.Node = FPtr; Args.push_back(Entry);
2009 Entry.Node = Nest; Args.push_back(Entry);
2011 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2012 TargetLowering::CallLoweringInfo CLI(DAG);
2013 CLI.setDebugLoc(dl).setChain(Chain)
2014 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2015 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2016 std::move(Args), 0);
2018 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2019 return CallResult.second;
2022 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2023 const PPCSubtarget &Subtarget) const {
2024 MachineFunction &MF = DAG.getMachineFunction();
2025 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2029 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2030 // vastart just stores the address of the VarArgsFrameIndex slot into the
2031 // memory location argument.
2032 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2033 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2034 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2035 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2036 MachinePointerInfo(SV),
2040 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2041 // We suppose the given va_list is already allocated.
2044 // char gpr; /* index into the array of 8 GPRs
2045 // * stored in the register save area
2046 // * gpr=0 corresponds to r3,
2047 // * gpr=1 to r4, etc.
2049 // char fpr; /* index into the array of 8 FPRs
2050 // * stored in the register save area
2051 // * fpr=0 corresponds to f1,
2052 // * fpr=1 to f2, etc.
2054 // char *overflow_arg_area;
2055 // /* location on stack that holds
2056 // * the next overflow argument
2058 // char *reg_save_area;
2059 // /* where r3:r10 and f1:f8 (if saved)
2065 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2066 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2069 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2071 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2073 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2076 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2077 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2079 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2080 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2082 uint64_t FPROffset = 1;
2083 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2085 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2087 // Store first byte : number of int regs
2088 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2090 MachinePointerInfo(SV),
2091 MVT::i8, false, false, 0);
2092 uint64_t nextOffset = FPROffset;
2093 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2096 // Store second byte : number of float regs
2097 SDValue secondStore =
2098 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2099 MachinePointerInfo(SV, nextOffset), MVT::i8,
2101 nextOffset += StackOffset;
2102 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2104 // Store second word : arguments given on stack
2105 SDValue thirdStore =
2106 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2107 MachinePointerInfo(SV, nextOffset),
2109 nextOffset += FrameOffset;
2110 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2112 // Store third word : arguments given in registers
2113 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2114 MachinePointerInfo(SV, nextOffset),
2119 #include "PPCGenCallingConv.inc"
2121 // Function whose sole purpose is to kill compiler warnings
2122 // stemming from unused functions included from PPCGenCallingConv.inc.
2123 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2124 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2127 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2128 CCValAssign::LocInfo &LocInfo,
2129 ISD::ArgFlagsTy &ArgFlags,
2134 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2136 CCValAssign::LocInfo &LocInfo,
2137 ISD::ArgFlagsTy &ArgFlags,
2139 static const MCPhysReg ArgRegs[] = {
2140 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2141 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2143 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2145 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2147 // Skip one register if the first unallocated register has an even register
2148 // number and there are still argument registers available which have not been
2149 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2150 // need to skip a register if RegNum is odd.
2151 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2152 State.AllocateReg(ArgRegs[RegNum]);
2155 // Always return false here, as this function only makes sure that the first
2156 // unallocated register has an odd register number and does not actually
2157 // allocate a register for the current argument.
2161 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2163 CCValAssign::LocInfo &LocInfo,
2164 ISD::ArgFlagsTy &ArgFlags,
2166 static const MCPhysReg ArgRegs[] = {
2167 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2171 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2173 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2175 // If there is only one Floating-point register left we need to put both f64
2176 // values of a split ppc_fp128 value on the stack.
2177 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2178 State.AllocateReg(ArgRegs[RegNum]);
2181 // Always return false here, as this function only makes sure that the two f64
2182 // values a ppc_fp128 value is split into are both passed in registers or both
2183 // passed on the stack and does not actually allocate a register for the
2184 // current argument.
2188 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2190 static const MCPhysReg *GetFPR() {
2191 static const MCPhysReg FPR[] = {
2192 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2193 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2199 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2201 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2202 unsigned PtrByteSize) {
2203 unsigned ArgSize = ArgVT.getStoreSize();
2204 if (Flags.isByVal())
2205 ArgSize = Flags.getByValSize();
2207 // Round up to multiples of the pointer size, except for array members,
2208 // which are always packed.
2209 if (!Flags.isInConsecutiveRegs())
2210 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2215 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2217 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2218 ISD::ArgFlagsTy Flags,
2219 unsigned PtrByteSize) {
2220 unsigned Align = PtrByteSize;
2222 // Altivec parameters are padded to a 16 byte boundary.
2223 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2224 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2225 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2228 // ByVal parameters are aligned as requested.
2229 if (Flags.isByVal()) {
2230 unsigned BVAlign = Flags.getByValAlign();
2231 if (BVAlign > PtrByteSize) {
2232 if (BVAlign % PtrByteSize != 0)
2234 "ByVal alignment is not a multiple of the pointer size");
2240 // Array members are always packed to their original alignment.
2241 if (Flags.isInConsecutiveRegs()) {
2242 // If the array member was split into multiple registers, the first
2243 // needs to be aligned to the size of the full type. (Except for
2244 // ppcf128, which is only aligned as its f64 components.)
2245 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2246 Align = OrigVT.getStoreSize();
2248 Align = ArgVT.getStoreSize();
2254 /// CalculateStackSlotUsed - Return whether this argument will use its
2255 /// stack slot (instead of being passed in registers). ArgOffset,
2256 /// AvailableFPRs, and AvailableVRs must hold the current argument
2257 /// position, and will be updated to account for this argument.
2258 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2259 ISD::ArgFlagsTy Flags,
2260 unsigned PtrByteSize,
2261 unsigned LinkageSize,
2262 unsigned ParamAreaSize,
2263 unsigned &ArgOffset,
2264 unsigned &AvailableFPRs,
2265 unsigned &AvailableVRs) {
2266 bool UseMemory = false;
2268 // Respect alignment of argument on the stack.
2270 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2271 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2272 // If there's no space left in the argument save area, we must
2273 // use memory (this check also catches zero-sized arguments).
2274 if (ArgOffset >= LinkageSize + ParamAreaSize)
2277 // Allocate argument on the stack.
2278 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2279 if (Flags.isInConsecutiveRegsLast())
2280 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2281 // If we overran the argument save area, we must use memory
2282 // (this check catches arguments passed partially in memory)
2283 if (ArgOffset > LinkageSize + ParamAreaSize)
2286 // However, if the argument is actually passed in an FPR or a VR,
2287 // we don't use memory after all.
2288 if (!Flags.isByVal()) {
2289 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2290 if (AvailableFPRs > 0) {
2294 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2295 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2296 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2297 if (AvailableVRs > 0) {
2306 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2307 /// ensure minimum alignment required for target.
2308 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2309 unsigned NumBytes) {
2310 unsigned TargetAlign =
2311 Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2312 unsigned AlignMask = TargetAlign - 1;
2313 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2318 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2319 CallingConv::ID CallConv, bool isVarArg,
2320 const SmallVectorImpl<ISD::InputArg>
2322 SDLoc dl, SelectionDAG &DAG,
2323 SmallVectorImpl<SDValue> &InVals)
2325 if (Subtarget.isSVR4ABI()) {
2326 if (Subtarget.isPPC64())
2327 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2330 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2333 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2339 PPCTargetLowering::LowerFormalArguments_32SVR4(
2341 CallingConv::ID CallConv, bool isVarArg,
2342 const SmallVectorImpl<ISD::InputArg>
2344 SDLoc dl, SelectionDAG &DAG,
2345 SmallVectorImpl<SDValue> &InVals) const {
2347 // 32-bit SVR4 ABI Stack Frame Layout:
2348 // +-----------------------------------+
2349 // +--> | Back chain |
2350 // | +-----------------------------------+
2351 // | | Floating-point register save area |
2352 // | +-----------------------------------+
2353 // | | General register save area |
2354 // | +-----------------------------------+
2355 // | | CR save word |
2356 // | +-----------------------------------+
2357 // | | VRSAVE save word |
2358 // | +-----------------------------------+
2359 // | | Alignment padding |
2360 // | +-----------------------------------+
2361 // | | Vector register save area |
2362 // | +-----------------------------------+
2363 // | | Local variable space |
2364 // | +-----------------------------------+
2365 // | | Parameter list area |
2366 // | +-----------------------------------+
2367 // | | LR save word |
2368 // | +-----------------------------------+
2369 // SP--> +--- | Back chain |
2370 // +-----------------------------------+
2373 // System V Application Binary Interface PowerPC Processor Supplement
2374 // AltiVec Technology Programming Interface Manual
2376 MachineFunction &MF = DAG.getMachineFunction();
2377 MachineFrameInfo *MFI = MF.getFrameInfo();
2378 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2380 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2381 // Potential tail calls could cause overwriting of argument stack slots.
2382 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2383 (CallConv == CallingConv::Fast));
2384 unsigned PtrByteSize = 4;
2386 // Assign locations to all of the incoming arguments.
2387 SmallVector<CCValAssign, 16> ArgLocs;
2388 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2391 // Reserve space for the linkage area on the stack.
2392 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2393 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2395 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2397 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2398 CCValAssign &VA = ArgLocs[i];
2400 // Arguments stored in registers.
2401 if (VA.isRegLoc()) {
2402 const TargetRegisterClass *RC;
2403 EVT ValVT = VA.getValVT();
2405 switch (ValVT.getSimpleVT().SimpleTy) {
2407 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2410 RC = &PPC::GPRCRegClass;
2413 RC = &PPC::F4RCRegClass;
2416 if (Subtarget.hasVSX())
2417 RC = &PPC::VSFRCRegClass;
2419 RC = &PPC::F8RCRegClass;
2425 RC = &PPC::VRRCRegClass;
2429 RC = &PPC::VSHRCRegClass;
2433 // Transform the arguments stored in physical registers into virtual ones.
2434 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2435 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2436 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2438 if (ValVT == MVT::i1)
2439 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2441 InVals.push_back(ArgValue);
2443 // Argument stored in memory.
2444 assert(VA.isMemLoc());
2446 unsigned ArgSize = VA.getLocVT().getStoreSize();
2447 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2450 // Create load nodes to retrieve arguments from the stack.
2451 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2452 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2453 MachinePointerInfo(),
2454 false, false, false, 0));
2458 // Assign locations to all of the incoming aggregate by value arguments.
2459 // Aggregates passed by value are stored in the local variable space of the
2460 // caller's stack frame, right above the parameter list area.
2461 SmallVector<CCValAssign, 16> ByValArgLocs;
2462 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2463 ByValArgLocs, *DAG.getContext());
2465 // Reserve stack space for the allocations in CCInfo.
2466 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2468 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2470 // Area that is at least reserved in the caller of this function.
2471 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2472 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2474 // Set the size that is at least reserved in caller of this function. Tail
2475 // call optimized function's reserved stack space needs to be aligned so that
2476 // taking the difference between two stack areas will result in an aligned
2478 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2479 FuncInfo->setMinReservedArea(MinReservedArea);
2481 SmallVector<SDValue, 8> MemOps;
2483 // If the function takes variable number of arguments, make a frame index for
2484 // the start of the first vararg value... for expansion of llvm.va_start.
2486 static const MCPhysReg GPArgRegs[] = {
2487 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2488 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2490 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2492 static const MCPhysReg FPArgRegs[] = {
2493 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2496 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2497 if (DisablePPCFloatInVariadic)
2500 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2502 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2505 // Make room for NumGPArgRegs and NumFPArgRegs.
2506 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2507 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2509 FuncInfo->setVarArgsStackOffset(
2510 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2511 CCInfo.getNextStackOffset(), true));
2513 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2514 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2516 // The fixed integer arguments of a variadic function are stored to the
2517 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2518 // the result of va_next.
2519 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2520 // Get an existing live-in vreg, or add a new one.
2521 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2523 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2525 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2526 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2527 MachinePointerInfo(), false, false, 0);
2528 MemOps.push_back(Store);
2529 // Increment the address by four for the next argument to store
2530 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2531 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2534 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2536 // The double arguments are stored to the VarArgsFrameIndex
2538 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2539 // Get an existing live-in vreg, or add a new one.
2540 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2542 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2544 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2545 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2546 MachinePointerInfo(), false, false, 0);
2547 MemOps.push_back(Store);
2548 // Increment the address by eight for the next argument to store
2549 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2551 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2555 if (!MemOps.empty())
2556 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2561 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2562 // value to MVT::i64 and then truncate to the correct register size.
2564 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2565 SelectionDAG &DAG, SDValue ArgVal,
2568 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2569 DAG.getValueType(ObjectVT));
2570 else if (Flags.isZExt())
2571 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2572 DAG.getValueType(ObjectVT));
2574 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2578 PPCTargetLowering::LowerFormalArguments_64SVR4(
2580 CallingConv::ID CallConv, bool isVarArg,
2581 const SmallVectorImpl<ISD::InputArg>
2583 SDLoc dl, SelectionDAG &DAG,
2584 SmallVectorImpl<SDValue> &InVals) const {
2585 // TODO: add description of PPC stack frame format, or at least some docs.
2587 bool isELFv2ABI = Subtarget.isELFv2ABI();
2588 bool isLittleEndian = Subtarget.isLittleEndian();
2589 MachineFunction &MF = DAG.getMachineFunction();
2590 MachineFrameInfo *MFI = MF.getFrameInfo();
2591 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2593 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2594 // Potential tail calls could cause overwriting of argument stack slots.
2595 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2596 (CallConv == CallingConv::Fast));
2597 unsigned PtrByteSize = 8;
2599 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2602 static const MCPhysReg GPR[] = {
2603 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2604 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2607 static const MCPhysReg *FPR = GetFPR();
2609 static const MCPhysReg VR[] = {
2610 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2611 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2613 static const MCPhysReg VSRH[] = {
2614 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2615 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2618 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2619 const unsigned Num_FPR_Regs = 13;
2620 const unsigned Num_VR_Regs = array_lengthof(VR);
2622 // Do a first pass over the arguments to determine whether the ABI
2623 // guarantees that our caller has allocated the parameter save area
2624 // on its stack frame. In the ELFv1 ABI, this is always the case;
2625 // in the ELFv2 ABI, it is true if this is a vararg function or if
2626 // any parameter is located in a stack slot.
2628 bool HasParameterArea = !isELFv2ABI || isVarArg;
2629 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2630 unsigned NumBytes = LinkageSize;
2631 unsigned AvailableFPRs = Num_FPR_Regs;
2632 unsigned AvailableVRs = Num_VR_Regs;
2633 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2634 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2635 PtrByteSize, LinkageSize, ParamAreaSize,
2636 NumBytes, AvailableFPRs, AvailableVRs))
2637 HasParameterArea = true;
2639 // Add DAG nodes to load the arguments or copy them out of registers. On
2640 // entry to a function on PPC, the arguments start after the linkage area,
2641 // although the first ones are often in registers.
2643 unsigned ArgOffset = LinkageSize;
2644 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2645 SmallVector<SDValue, 8> MemOps;
2646 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2647 unsigned CurArgIdx = 0;
2648 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2650 bool needsLoad = false;
2651 EVT ObjectVT = Ins[ArgNo].VT;
2652 EVT OrigVT = Ins[ArgNo].ArgVT;
2653 unsigned ObjSize = ObjectVT.getStoreSize();
2654 unsigned ArgSize = ObjSize;
2655 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2656 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2657 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2659 /* Respect alignment of argument on the stack. */
2661 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2662 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2663 unsigned CurArgOffset = ArgOffset;
2665 /* Compute GPR index associated with argument offset. */
2666 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2667 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2669 // FIXME the codegen can be much improved in some cases.
2670 // We do not have to keep everything in memory.
2671 if (Flags.isByVal()) {
2672 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2673 ObjSize = Flags.getByValSize();
2674 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2675 // Empty aggregate parameters do not take up registers. Examples:
2679 // etc. However, we have to provide a place-holder in InVals, so
2680 // pretend we have an 8-byte item at the current address for that
2683 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2684 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2685 InVals.push_back(FIN);
2689 // Create a stack object covering all stack doublewords occupied
2690 // by the argument. If the argument is (fully or partially) on
2691 // the stack, or if the argument is fully in registers but the
2692 // caller has allocated the parameter save anyway, we can refer
2693 // directly to the caller's stack frame. Otherwise, create a
2694 // local copy in our own frame.
2696 if (HasParameterArea ||
2697 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2698 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2700 FI = MFI->CreateStackObject(ArgSize, Align, false);
2701 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2703 // Handle aggregates smaller than 8 bytes.
2704 if (ObjSize < PtrByteSize) {
2705 // The value of the object is its address, which differs from the
2706 // address of the enclosing doubleword on big-endian systems.
2708 if (!isLittleEndian) {
2709 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2710 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2712 InVals.push_back(Arg);
2714 if (GPR_idx != Num_GPR_Regs) {
2715 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2716 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2719 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2720 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2721 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2722 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2723 MachinePointerInfo(FuncArg),
2724 ObjType, false, false, 0);
2726 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2727 // store the whole register as-is to the parameter save area
2729 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2730 MachinePointerInfo(FuncArg),
2734 MemOps.push_back(Store);
2736 // Whether we copied from a register or not, advance the offset
2737 // into the parameter save area by a full doubleword.
2738 ArgOffset += PtrByteSize;
2742 // The value of the object is its address, which is the address of
2743 // its first stack doubleword.
2744 InVals.push_back(FIN);
2746 // Store whatever pieces of the object are in registers to memory.
2747 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2748 if (GPR_idx == Num_GPR_Regs)
2751 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2752 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2755 SDValue Off = DAG.getConstant(j, PtrVT);
2756 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2758 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2759 MachinePointerInfo(FuncArg, j),
2761 MemOps.push_back(Store);
2764 ArgOffset += ArgSize;
2768 switch (ObjectVT.getSimpleVT().SimpleTy) {
2769 default: llvm_unreachable("Unhandled argument type!");
2773 // These can be scalar arguments or elements of an integer array type
2774 // passed directly. Clang may use those instead of "byval" aggregate
2775 // types to avoid forcing arguments to memory unnecessarily.
2776 if (GPR_idx != Num_GPR_Regs) {
2777 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2778 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2780 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2781 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2782 // value to MVT::i64 and then truncate to the correct register size.
2783 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2786 ArgSize = PtrByteSize;
2793 // These can be scalar arguments or elements of a float array type
2794 // passed directly. The latter are used to implement ELFv2 homogenous
2795 // float aggregates.
2796 if (FPR_idx != Num_FPR_Regs) {
2799 if (ObjectVT == MVT::f32)
2800 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2802 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2803 &PPC::VSFRCRegClass :
2804 &PPC::F8RCRegClass);
2806 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2808 } else if (GPR_idx != Num_GPR_Regs) {
2809 // This can only ever happen in the presence of f32 array types,
2810 // since otherwise we never run out of FPRs before running out
2812 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2813 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2815 if (ObjectVT == MVT::f32) {
2816 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2817 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2818 DAG.getConstant(32, MVT::i32));
2819 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2822 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2827 // When passing an array of floats, the array occupies consecutive
2828 // space in the argument area; only round up to the next doubleword
2829 // at the end of the array. Otherwise, each float takes 8 bytes.
2830 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2831 ArgOffset += ArgSize;
2832 if (Flags.isInConsecutiveRegsLast())
2833 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2841 // These can be scalar arguments or elements of a vector array type
2842 // passed directly. The latter are used to implement ELFv2 homogenous
2843 // vector aggregates.
2844 if (VR_idx != Num_VR_Regs) {
2845 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2846 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2847 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2848 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2857 // We need to load the argument to a virtual register if we determined
2858 // above that we ran out of physical registers of the appropriate type.
2860 if (ObjSize < ArgSize && !isLittleEndian)
2861 CurArgOffset += ArgSize - ObjSize;
2862 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2863 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2864 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2865 false, false, false, 0);
2868 InVals.push_back(ArgVal);
2871 // Area that is at least reserved in the caller of this function.
2872 unsigned MinReservedArea;
2873 if (HasParameterArea)
2874 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2876 MinReservedArea = LinkageSize;
2878 // Set the size that is at least reserved in caller of this function. Tail
2879 // call optimized functions' reserved stack space needs to be aligned so that
2880 // taking the difference between two stack areas will result in an aligned
2882 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2883 FuncInfo->setMinReservedArea(MinReservedArea);
2885 // If the function takes variable number of arguments, make a frame index for
2886 // the start of the first vararg value... for expansion of llvm.va_start.
2888 int Depth = ArgOffset;
2890 FuncInfo->setVarArgsFrameIndex(
2891 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2892 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2894 // If this function is vararg, store any remaining integer argument regs
2895 // to their spots on the stack so that they may be loaded by deferencing the
2896 // result of va_next.
2897 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2898 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2899 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2900 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2901 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2902 MachinePointerInfo(), false, false, 0);
2903 MemOps.push_back(Store);
2904 // Increment the address by four for the next argument to store
2905 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2906 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2910 if (!MemOps.empty())
2911 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2917 PPCTargetLowering::LowerFormalArguments_Darwin(
2919 CallingConv::ID CallConv, bool isVarArg,
2920 const SmallVectorImpl<ISD::InputArg>
2922 SDLoc dl, SelectionDAG &DAG,
2923 SmallVectorImpl<SDValue> &InVals) const {
2924 // TODO: add description of PPC stack frame format, or at least some docs.
2926 MachineFunction &MF = DAG.getMachineFunction();
2927 MachineFrameInfo *MFI = MF.getFrameInfo();
2928 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2930 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2931 bool isPPC64 = PtrVT == MVT::i64;
2932 // Potential tail calls could cause overwriting of argument stack slots.
2933 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2934 (CallConv == CallingConv::Fast));
2935 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2937 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2939 unsigned ArgOffset = LinkageSize;
2940 // Area that is at least reserved in caller of this function.
2941 unsigned MinReservedArea = ArgOffset;
2943 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2944 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2945 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2947 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2948 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2949 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2952 static const MCPhysReg *FPR = GetFPR();
2954 static const MCPhysReg VR[] = {
2955 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2956 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2959 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2960 const unsigned Num_FPR_Regs = 13;
2961 const unsigned Num_VR_Regs = array_lengthof( VR);
2963 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2965 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2967 // In 32-bit non-varargs functions, the stack space for vectors is after the
2968 // stack space for non-vectors. We do not use this space unless we have
2969 // too many vectors to fit in registers, something that only occurs in
2970 // constructed examples:), but we have to walk the arglist to figure
2971 // that out...for the pathological case, compute VecArgOffset as the
2972 // start of the vector parameter area. Computing VecArgOffset is the
2973 // entire point of the following loop.
2974 unsigned VecArgOffset = ArgOffset;
2975 if (!isVarArg && !isPPC64) {
2976 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2978 EVT ObjectVT = Ins[ArgNo].VT;
2979 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2981 if (Flags.isByVal()) {
2982 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2983 unsigned ObjSize = Flags.getByValSize();
2985 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2986 VecArgOffset += ArgSize;
2990 switch(ObjectVT.getSimpleVT().SimpleTy) {
2991 default: llvm_unreachable("Unhandled argument type!");
2997 case MVT::i64: // PPC64
2999 // FIXME: We are guaranteed to be !isPPC64 at this point.
3000 // Does MVT::i64 apply?
3007 // Nothing to do, we're only looking at Nonvector args here.
3012 // We've found where the vector parameter area in memory is. Skip the
3013 // first 12 parameters; these don't use that memory.
3014 VecArgOffset = ((VecArgOffset+15)/16)*16;
3015 VecArgOffset += 12*16;
3017 // Add DAG nodes to load the arguments or copy them out of registers. On
3018 // entry to a function on PPC, the arguments start after the linkage area,
3019 // although the first ones are often in registers.
3021 SmallVector<SDValue, 8> MemOps;
3022 unsigned nAltivecParamsAtEnd = 0;
3023 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3024 unsigned CurArgIdx = 0;
3025 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3027 bool needsLoad = false;
3028 EVT ObjectVT = Ins[ArgNo].VT;
3029 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3030 unsigned ArgSize = ObjSize;
3031 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3032 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3033 CurArgIdx = Ins[ArgNo].OrigArgIndex;
3035 unsigned CurArgOffset = ArgOffset;
3037 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3038 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3039 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3040 if (isVarArg || isPPC64) {
3041 MinReservedArea = ((MinReservedArea+15)/16)*16;
3042 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3045 } else nAltivecParamsAtEnd++;
3047 // Calculate min reserved area.
3048 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3052 // FIXME the codegen can be much improved in some cases.
3053 // We do not have to keep everything in memory.
3054 if (Flags.isByVal()) {
3055 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3056 ObjSize = Flags.getByValSize();
3057 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3058 // Objects of size 1 and 2 are right justified, everything else is
3059 // left justified. This means the memory address is adjusted forwards.
3060 if (ObjSize==1 || ObjSize==2) {
3061 CurArgOffset = CurArgOffset + (4 - ObjSize);
3063 // The value of the object is its address.
3064 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3065 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3066 InVals.push_back(FIN);
3067 if (ObjSize==1 || ObjSize==2) {
3068 if (GPR_idx != Num_GPR_Regs) {
3071 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3073 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3074 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3075 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3076 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3077 MachinePointerInfo(FuncArg),
3078 ObjType, false, false, 0);
3079 MemOps.push_back(Store);
3083 ArgOffset += PtrByteSize;
3087 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3088 // Store whatever pieces of the object are in registers
3089 // to memory. ArgOffset will be the address of the beginning
3091 if (GPR_idx != Num_GPR_Regs) {
3094 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3096 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3097 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3098 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3099 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3100 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3101 MachinePointerInfo(FuncArg, j),
3103 MemOps.push_back(Store);
3105 ArgOffset += PtrByteSize;
3107 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3114 switch (ObjectVT.getSimpleVT().SimpleTy) {
3115 default: llvm_unreachable("Unhandled argument type!");
3119 if (GPR_idx != Num_GPR_Regs) {
3120 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3121 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3123 if (ObjectVT == MVT::i1)
3124 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3129 ArgSize = PtrByteSize;
3131 // All int arguments reserve stack space in the Darwin ABI.
3132 ArgOffset += PtrByteSize;
3136 case MVT::i64: // PPC64
3137 if (GPR_idx != Num_GPR_Regs) {
3138 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3139 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3141 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3142 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3143 // value to MVT::i64 and then truncate to the correct register size.
3144 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3149 ArgSize = PtrByteSize;
3151 // All int arguments reserve stack space in the Darwin ABI.
3157 // Every 4 bytes of argument space consumes one of the GPRs available for
3158 // argument passing.
3159 if (GPR_idx != Num_GPR_Regs) {
3161 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3164 if (FPR_idx != Num_FPR_Regs) {
3167 if (ObjectVT == MVT::f32)
3168 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3170 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3172 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3178 // All FP arguments reserve stack space in the Darwin ABI.
3179 ArgOffset += isPPC64 ? 8 : ObjSize;
3185 // Note that vector arguments in registers don't reserve stack space,
3186 // except in varargs functions.
3187 if (VR_idx != Num_VR_Regs) {
3188 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3189 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3191 while ((ArgOffset % 16) != 0) {
3192 ArgOffset += PtrByteSize;
3193 if (GPR_idx != Num_GPR_Regs)
3197 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3201 if (!isVarArg && !isPPC64) {
3202 // Vectors go after all the nonvectors.
3203 CurArgOffset = VecArgOffset;
3206 // Vectors are aligned.
3207 ArgOffset = ((ArgOffset+15)/16)*16;
3208 CurArgOffset = ArgOffset;
3216 // We need to load the argument to a virtual register if we determined above
3217 // that we ran out of physical registers of the appropriate type.
3219 int FI = MFI->CreateFixedObject(ObjSize,
3220 CurArgOffset + (ArgSize - ObjSize),
3222 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3223 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3224 false, false, false, 0);
3227 InVals.push_back(ArgVal);
3230 // Allow for Altivec parameters at the end, if needed.
3231 if (nAltivecParamsAtEnd) {
3232 MinReservedArea = ((MinReservedArea+15)/16)*16;
3233 MinReservedArea += 16*nAltivecParamsAtEnd;
3236 // Area that is at least reserved in the caller of this function.
3237 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3239 // Set the size that is at least reserved in caller of this function. Tail
3240 // call optimized functions' reserved stack space needs to be aligned so that
3241 // taking the difference between two stack areas will result in an aligned
3243 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3244 FuncInfo->setMinReservedArea(MinReservedArea);
3246 // If the function takes variable number of arguments, make a frame index for
3247 // the start of the first vararg value... for expansion of llvm.va_start.
3249 int Depth = ArgOffset;
3251 FuncInfo->setVarArgsFrameIndex(
3252 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3254 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3256 // If this function is vararg, store any remaining integer argument regs
3257 // to their spots on the stack so that they may be loaded by deferencing the
3258 // result of va_next.
3259 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3263 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3265 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3267 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3268 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3269 MachinePointerInfo(), false, false, 0);
3270 MemOps.push_back(Store);
3271 // Increment the address by four for the next argument to store
3272 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3273 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3277 if (!MemOps.empty())
3278 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3283 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3284 /// adjusted to accommodate the arguments for the tailcall.
3285 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3286 unsigned ParamSize) {
3288 if (!isTailCall) return 0;
3290 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3291 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3292 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3293 // Remember only if the new adjustement is bigger.
3294 if (SPDiff < FI->getTailCallSPDelta())
3295 FI->setTailCallSPDelta(SPDiff);
3300 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3301 /// for tail call optimization. Targets which want to do tail call
3302 /// optimization should implement this function.
3304 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3305 CallingConv::ID CalleeCC,
3307 const SmallVectorImpl<ISD::InputArg> &Ins,
3308 SelectionDAG& DAG) const {
3309 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3312 // Variable argument functions are not supported.
3316 MachineFunction &MF = DAG.getMachineFunction();
3317 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3318 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3319 // Functions containing by val parameters are not supported.
3320 for (unsigned i = 0; i != Ins.size(); i++) {
3321 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3322 if (Flags.isByVal()) return false;
3325 // Non-PIC/GOT tail calls are supported.
3326 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3329 // At the moment we can only do local tail calls (in same module, hidden
3330 // or protected) if we are generating PIC.
3331 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3332 return G->getGlobal()->hasHiddenVisibility()
3333 || G->getGlobal()->hasProtectedVisibility();
3339 /// isCallCompatibleAddress - Return the immediate to use if the specified
3340 /// 32-bit value is representable in the immediate field of a BxA instruction.
3341 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3342 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3343 if (!C) return nullptr;
3345 int Addr = C->getZExtValue();
3346 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3347 SignExtend32<26>(Addr) != Addr)
3348 return nullptr; // Top 6 bits have to be sext of immediate.
3350 return DAG.getConstant((int)C->getZExtValue() >> 2,
3351 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3356 struct TailCallArgumentInfo {
3361 TailCallArgumentInfo() : FrameIdx(0) {}
3366 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3368 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3370 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3371 SmallVectorImpl<SDValue> &MemOpChains,
3373 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3374 SDValue Arg = TailCallArgs[i].Arg;
3375 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3376 int FI = TailCallArgs[i].FrameIdx;
3377 // Store relative to framepointer.
3378 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3379 MachinePointerInfo::getFixedStack(FI),
3384 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3385 /// the appropriate stack slot for the tail call optimized function call.
3386 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3387 MachineFunction &MF,
3396 // Calculate the new stack slot for the return address.
3397 int SlotSize = isPPC64 ? 8 : 4;
3398 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3400 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3401 NewRetAddrLoc, true);
3402 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3403 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3404 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3405 MachinePointerInfo::getFixedStack(NewRetAddr),
3408 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3409 // slot as the FP is never overwritten.
3412 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3413 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3415 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3416 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3417 MachinePointerInfo::getFixedStack(NewFPIdx),
3424 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3425 /// the position of the argument.
3427 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3428 SDValue Arg, int SPDiff, unsigned ArgOffset,
3429 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3430 int Offset = ArgOffset + SPDiff;
3431 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3432 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3433 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3434 SDValue FIN = DAG.getFrameIndex(FI, VT);
3435 TailCallArgumentInfo Info;
3437 Info.FrameIdxOp = FIN;
3439 TailCallArguments.push_back(Info);
3442 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3443 /// stack slot. Returns the chain as result and the loaded frame pointers in
3444 /// LROpOut/FPOpout. Used when tail calling.
3445 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3453 // Load the LR and FP stack slot for later adjusting.
3454 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3455 LROpOut = getReturnAddrFrameIndex(DAG);
3456 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3457 false, false, false, 0);
3458 Chain = SDValue(LROpOut.getNode(), 1);
3460 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3461 // slot as the FP is never overwritten.
3463 FPOpOut = getFramePointerFrameIndex(DAG);
3464 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3465 false, false, false, 0);
3466 Chain = SDValue(FPOpOut.getNode(), 1);
3472 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3473 /// by "Src" to address "Dst" of size "Size". Alignment information is
3474 /// specified by the specific parameter attribute. The copy will be passed as
3475 /// a byval function parameter.
3476 /// Sometimes what we are copying is the end of a larger object, the part that
3477 /// does not fit in registers.
3479 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3480 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3482 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3483 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3484 false, false, MachinePointerInfo(),
3485 MachinePointerInfo());
3488 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3491 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3492 SDValue Arg, SDValue PtrOff, int SPDiff,
3493 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3494 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3495 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3497 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3502 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3504 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3505 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3506 DAG.getConstant(ArgOffset, PtrVT));
3508 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3509 MachinePointerInfo(), false, false, 0));
3510 // Calculate and remember argument location.
3511 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3516 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3517 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3518 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3519 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3520 MachineFunction &MF = DAG.getMachineFunction();
3522 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3523 // might overwrite each other in case of tail call optimization.
3524 SmallVector<SDValue, 8> MemOpChains2;
3525 // Do not flag preceding copytoreg stuff together with the following stuff.
3527 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3529 if (!MemOpChains2.empty())
3530 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3532 // Store the return address to the appropriate stack slot.
3533 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3534 isPPC64, isDarwinABI, dl);
3536 // Emit callseq_end just before tailcall node.
3537 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3538 DAG.getIntPtrConstant(0, true), InFlag, dl);
3539 InFlag = Chain.getValue(1);
3543 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3544 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3545 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3546 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3547 const PPCSubtarget &Subtarget) {
3549 bool isPPC64 = Subtarget.isPPC64();
3550 bool isSVR4ABI = Subtarget.isSVR4ABI();
3551 bool isELFv2ABI = Subtarget.isELFv2ABI();
3553 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3554 NodeTys.push_back(MVT::Other); // Returns a chain
3555 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3557 unsigned CallOpc = PPCISD::CALL;
3559 bool needIndirectCall = true;
3560 if (!isSVR4ABI || !isPPC64)
3561 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3562 // If this is an absolute destination address, use the munged value.
3563 Callee = SDValue(Dest, 0);
3564 needIndirectCall = false;
3567 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3568 unsigned OpFlags = 0;
3569 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3570 (Subtarget.getTargetTriple().isMacOSX() &&
3571 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3572 (G->getGlobal()->isDeclaration() ||
3573 G->getGlobal()->isWeakForLinker())) ||
3574 (Subtarget.isTargetELF() && !isPPC64 &&
3575 !G->getGlobal()->hasLocalLinkage() &&
3576 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3577 // PC-relative references to external symbols should go through $stub,
3578 // unless we're building with the leopard linker or later, which
3579 // automatically synthesizes these stubs.
3580 OpFlags = PPCII::MO_PLT_OR_STUB;
3583 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3584 // every direct call is) turn it into a TargetGlobalAddress /
3585 // TargetExternalSymbol node so that legalize doesn't hack it.
3586 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3587 Callee.getValueType(), 0, OpFlags);
3588 needIndirectCall = false;
3591 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3592 unsigned char OpFlags = 0;
3594 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3595 (Subtarget.getTargetTriple().isMacOSX() &&
3596 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3597 (Subtarget.isTargetELF() && !isPPC64 &&
3598 DAG.getTarget().getRelocationModel() == Reloc::PIC_) ) {
3599 // PC-relative references to external symbols should go through $stub,
3600 // unless we're building with the leopard linker or later, which
3601 // automatically synthesizes these stubs.
3602 OpFlags = PPCII::MO_PLT_OR_STUB;
3605 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3607 needIndirectCall = false;
3610 if (needIndirectCall) {
3611 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3612 // to do the call, we can't use PPCISD::CALL.
3613 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3615 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3616 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3617 // entry point, but to the function descriptor (the function entry point
3618 // address is part of the function descriptor though).
3619 // The function descriptor is a three doubleword structure with the
3620 // following fields: function entry point, TOC base address and
3621 // environment pointer.
3622 // Thus for a call through a function pointer, the following actions need
3624 // 1. Save the TOC of the caller in the TOC save area of its stack
3625 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3626 // 2. Load the address of the function entry point from the function
3628 // 3. Load the TOC of the callee from the function descriptor into r2.
3629 // 4. Load the environment pointer from the function descriptor into
3631 // 5. Branch to the function entry point address.
3632 // 6. On return of the callee, the TOC of the caller needs to be
3633 // restored (this is done in FinishCall()).
3635 // All those operations are flagged together to ensure that no other
3636 // operations can be scheduled in between. E.g. without flagging the
3637 // operations together, a TOC access in the caller could be scheduled
3638 // between the load of the callee TOC and the branch to the callee, which
3639 // results in the TOC access going through the TOC of the callee instead
3640 // of going through the TOC of the caller, which leads to incorrect code.
3642 // Load the address of the function entry point from the function
3644 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3645 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3646 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3647 Chain = LoadFuncPtr.getValue(1);
3648 InFlag = LoadFuncPtr.getValue(2);
3650 // Load environment pointer into r11.
3651 // Offset of the environment pointer within the function descriptor.
3652 SDValue PtrOff = DAG.getIntPtrConstant(16);
3654 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3655 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3657 Chain = LoadEnvPtr.getValue(1);
3658 InFlag = LoadEnvPtr.getValue(2);
3660 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3662 Chain = EnvVal.getValue(0);
3663 InFlag = EnvVal.getValue(1);
3665 // Load TOC of the callee into r2. We are using a target-specific load
3666 // with r2 hard coded, because the result of a target-independent load
3667 // would never go directly into r2, since r2 is a reserved register (which
3668 // prevents the register allocator from allocating it), resulting in an
3669 // additional register being allocated and an unnecessary move instruction
3671 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3672 SDValue TOCOff = DAG.getIntPtrConstant(8);
3673 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3674 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3676 Chain = LoadTOCPtr.getValue(0);
3677 InFlag = LoadTOCPtr.getValue(1);
3679 MTCTROps[0] = Chain;
3680 MTCTROps[1] = LoadFuncPtr;
3681 MTCTROps[2] = InFlag;
3684 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3685 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3686 InFlag = Chain.getValue(1);
3689 NodeTys.push_back(MVT::Other);
3690 NodeTys.push_back(MVT::Glue);
3691 Ops.push_back(Chain);
3692 CallOpc = PPCISD::BCTRL;
3693 Callee.setNode(nullptr);
3694 // Add use of X11 (holding environment pointer)
3695 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3696 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3697 // Add CTR register as callee so a bctr can be emitted later.
3699 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3702 // If this is a direct call, pass the chain and the callee.
3703 if (Callee.getNode()) {
3704 Ops.push_back(Chain);
3705 Ops.push_back(Callee);
3707 // If this is a tail call add stack pointer delta.
3709 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3711 // Add argument registers to the end of the list so that they are known live
3713 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3714 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3715 RegsToPass[i].second.getValueType()));
3717 // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3718 if (Callee.getNode() && isELFv2ABI)
3719 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3725 bool isLocalCall(const SDValue &Callee)
3727 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3728 return !G->getGlobal()->isDeclaration() &&
3729 !G->getGlobal()->isWeakForLinker();
3734 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3735 CallingConv::ID CallConv, bool isVarArg,
3736 const SmallVectorImpl<ISD::InputArg> &Ins,
3737 SDLoc dl, SelectionDAG &DAG,
3738 SmallVectorImpl<SDValue> &InVals) const {
3740 SmallVector<CCValAssign, 16> RVLocs;
3741 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3743 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3745 // Copy all of the result registers out of their specified physreg.
3746 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3747 CCValAssign &VA = RVLocs[i];
3748 assert(VA.isRegLoc() && "Can only return in registers!");
3750 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3751 VA.getLocReg(), VA.getLocVT(), InFlag);
3752 Chain = Val.getValue(1);
3753 InFlag = Val.getValue(2);
3755 switch (VA.getLocInfo()) {
3756 default: llvm_unreachable("Unknown loc info!");
3757 case CCValAssign::Full: break;
3758 case CCValAssign::AExt:
3759 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3761 case CCValAssign::ZExt:
3762 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3763 DAG.getValueType(VA.getValVT()));
3764 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3766 case CCValAssign::SExt:
3767 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3768 DAG.getValueType(VA.getValVT()));
3769 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3773 InVals.push_back(Val);
3780 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3781 bool isTailCall, bool isVarArg,
3783 SmallVector<std::pair<unsigned, SDValue>, 8>
3785 SDValue InFlag, SDValue Chain,
3787 int SPDiff, unsigned NumBytes,
3788 const SmallVectorImpl<ISD::InputArg> &Ins,
3789 SmallVectorImpl<SDValue> &InVals) const {
3791 bool isELFv2ABI = Subtarget.isELFv2ABI();
3792 std::vector<EVT> NodeTys;
3793 SmallVector<SDValue, 8> Ops;
3794 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3795 isTailCall, RegsToPass, Ops, NodeTys,
3798 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3799 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3800 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3802 // When performing tail call optimization the callee pops its arguments off
3803 // the stack. Account for this here so these bytes can be pushed back on in
3804 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3805 int BytesCalleePops =
3806 (CallConv == CallingConv::Fast &&
3807 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3809 // Add a register mask operand representing the call-preserved registers.
3810 const TargetRegisterInfo *TRI =
3811 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3812 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3813 assert(Mask && "Missing call preserved mask for calling convention");
3814 Ops.push_back(DAG.getRegisterMask(Mask));
3816 if (InFlag.getNode())
3817 Ops.push_back(InFlag);
3821 assert(((Callee.getOpcode() == ISD::Register &&
3822 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3823 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3824 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3825 isa<ConstantSDNode>(Callee)) &&
3826 "Expecting an global address, external symbol, absolute value or register");
3828 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3831 // Add a NOP immediately after the branch instruction when using the 64-bit
3832 // SVR4 ABI. At link time, if caller and callee are in a different module and
3833 // thus have a different TOC, the call will be replaced with a call to a stub
3834 // function which saves the current TOC, loads the TOC of the callee and
3835 // branches to the callee. The NOP will be replaced with a load instruction
3836 // which restores the TOC of the caller from the TOC save slot of the current
3837 // stack frame. If caller and callee belong to the same module (and have the
3838 // same TOC), the NOP will remain unchanged.
3840 bool needsTOCRestore = false;
3841 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3842 if (CallOpc == PPCISD::BCTRL) {
3843 // This is a call through a function pointer.
3844 // Restore the caller TOC from the save area into R2.
3845 // See PrepareCall() for more information about calls through function
3846 // pointers in the 64-bit SVR4 ABI.
3847 // We are using a target-specific load with r2 hard coded, because the
3848 // result of a target-independent load would never go directly into r2,
3849 // since r2 is a reserved register (which prevents the register allocator
3850 // from allocating it), resulting in an additional register being
3851 // allocated and an unnecessary move instruction being generated.
3852 needsTOCRestore = true;
3853 } else if ((CallOpc == PPCISD::CALL) &&
3854 (!isLocalCall(Callee) ||
3855 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3856 // Otherwise insert NOP for non-local calls.
3857 CallOpc = PPCISD::CALL_NOP;
3861 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3862 InFlag = Chain.getValue(1);
3864 if (needsTOCRestore) {
3865 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3866 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3867 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3868 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3869 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3870 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3871 Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
3872 InFlag = Chain.getValue(1);
3875 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3876 DAG.getIntPtrConstant(BytesCalleePops, true),
3879 InFlag = Chain.getValue(1);
3881 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3882 Ins, dl, DAG, InVals);
3886 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3887 SmallVectorImpl<SDValue> &InVals) const {
3888 SelectionDAG &DAG = CLI.DAG;
3890 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3891 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3892 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3893 SDValue Chain = CLI.Chain;
3894 SDValue Callee = CLI.Callee;
3895 bool &isTailCall = CLI.IsTailCall;
3896 CallingConv::ID CallConv = CLI.CallConv;
3897 bool isVarArg = CLI.IsVarArg;
3900 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3903 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3904 report_fatal_error("failed to perform tail call elimination on a call "
3905 "site marked musttail");
3907 if (Subtarget.isSVR4ABI()) {
3908 if (Subtarget.isPPC64())
3909 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3910 isTailCall, Outs, OutVals, Ins,
3913 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3914 isTailCall, Outs, OutVals, Ins,
3918 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3919 isTailCall, Outs, OutVals, Ins,
3924 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3925 CallingConv::ID CallConv, bool isVarArg,
3927 const SmallVectorImpl<ISD::OutputArg> &Outs,
3928 const SmallVectorImpl<SDValue> &OutVals,
3929 const SmallVectorImpl<ISD::InputArg> &Ins,
3930 SDLoc dl, SelectionDAG &DAG,
3931 SmallVectorImpl<SDValue> &InVals) const {
3932 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3933 // of the 32-bit SVR4 ABI stack frame layout.
3935 assert((CallConv == CallingConv::C ||
3936 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3938 unsigned PtrByteSize = 4;
3940 MachineFunction &MF = DAG.getMachineFunction();
3942 // Mark this function as potentially containing a function that contains a
3943 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3944 // and restoring the callers stack pointer in this functions epilog. This is
3945 // done because by tail calling the called function might overwrite the value
3946 // in this function's (MF) stack pointer stack slot 0(SP).
3947 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3948 CallConv == CallingConv::Fast)
3949 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3951 // Count how many bytes are to be pushed on the stack, including the linkage
3952 // area, parameter list area and the part of the local variable space which
3953 // contains copies of aggregates which are passed by value.
3955 // Assign locations to all of the outgoing arguments.
3956 SmallVector<CCValAssign, 16> ArgLocs;
3957 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3960 // Reserve space for the linkage area on the stack.
3961 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
3965 // Handle fixed and variable vector arguments differently.
3966 // Fixed vector arguments go into registers as long as registers are
3967 // available. Variable vector arguments always go into memory.
3968 unsigned NumArgs = Outs.size();
3970 for (unsigned i = 0; i != NumArgs; ++i) {
3971 MVT ArgVT = Outs[i].VT;
3972 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3975 if (Outs[i].IsFixed) {
3976 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3979 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3985 errs() << "Call operand #" << i << " has unhandled type "
3986 << EVT(ArgVT).getEVTString() << "\n";
3988 llvm_unreachable(nullptr);
3992 // All arguments are treated the same.
3993 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3996 // Assign locations to all of the outgoing aggregate by value arguments.
3997 SmallVector<CCValAssign, 16> ByValArgLocs;
3998 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3999 ByValArgLocs, *DAG.getContext());
4001 // Reserve stack space for the allocations in CCInfo.
4002 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4004 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4006 // Size of the linkage area, parameter list area and the part of the local
4007 // space variable where copies of aggregates which are passed by value are
4009 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4011 // Calculate by how many bytes the stack has to be adjusted in case of tail
4012 // call optimization.
4013 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4015 // Adjust the stack pointer for the new arguments...
4016 // These operations are automatically eliminated by the prolog/epilog pass
4017 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4019 SDValue CallSeqStart = Chain;
4021 // Load the return address and frame pointer so it can be moved somewhere else
4024 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4027 // Set up a copy of the stack pointer for use loading and storing any
4028 // arguments that may not fit in the registers available for argument
4030 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4032 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4033 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4034 SmallVector<SDValue, 8> MemOpChains;
4036 bool seenFloatArg = false;
4037 // Walk the register/memloc assignments, inserting copies/loads.
4038 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4041 CCValAssign &VA = ArgLocs[i];
4042 SDValue Arg = OutVals[i];
4043 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4045 if (Flags.isByVal()) {
4046 // Argument is an aggregate which is passed by value, thus we need to
4047 // create a copy of it in the local variable space of the current stack
4048 // frame (which is the stack frame of the caller) and pass the address of
4049 // this copy to the callee.
4050 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4051 CCValAssign &ByValVA = ByValArgLocs[j++];
4052 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4054 // Memory reserved in the local variable space of the callers stack frame.
4055 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4057 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4058 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4060 // Create a copy of the argument in the local area of the current
4062 SDValue MemcpyCall =
4063 CreateCopyOfByValArgument(Arg, PtrOff,
4064 CallSeqStart.getNode()->getOperand(0),
4067 // This must go outside the CALLSEQ_START..END.
4068 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4069 CallSeqStart.getNode()->getOperand(1),
4071 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4072 NewCallSeqStart.getNode());
4073 Chain = CallSeqStart = NewCallSeqStart;
4075 // Pass the address of the aggregate copy on the stack either in a
4076 // physical register or in the parameter list area of the current stack
4077 // frame to the callee.
4081 if (VA.isRegLoc()) {
4082 if (Arg.getValueType() == MVT::i1)
4083 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4085 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4086 // Put argument in a physical register.
4087 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4089 // Put argument in the parameter list area of the current stack frame.
4090 assert(VA.isMemLoc());
4091 unsigned LocMemOffset = VA.getLocMemOffset();
4094 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4095 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4097 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4098 MachinePointerInfo(),
4101 // Calculate and remember argument location.
4102 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4108 if (!MemOpChains.empty())
4109 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4111 // Build a sequence of copy-to-reg nodes chained together with token chain
4112 // and flag operands which copy the outgoing args into the appropriate regs.
4114 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4115 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4116 RegsToPass[i].second, InFlag);
4117 InFlag = Chain.getValue(1);
4120 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4123 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4124 SDValue Ops[] = { Chain, InFlag };
4126 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4127 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4129 InFlag = Chain.getValue(1);
4133 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4134 false, TailCallArguments);
4136 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4137 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4141 // Copy an argument into memory, being careful to do this outside the
4142 // call sequence for the call to which the argument belongs.
4144 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4145 SDValue CallSeqStart,
4146 ISD::ArgFlagsTy Flags,
4149 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4150 CallSeqStart.getNode()->getOperand(0),
4152 // The MEMCPY must go outside the CALLSEQ_START..END.
4153 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4154 CallSeqStart.getNode()->getOperand(1),
4156 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4157 NewCallSeqStart.getNode());
4158 return NewCallSeqStart;
4162 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4163 CallingConv::ID CallConv, bool isVarArg,
4165 const SmallVectorImpl<ISD::OutputArg> &Outs,
4166 const SmallVectorImpl<SDValue> &OutVals,
4167 const SmallVectorImpl<ISD::InputArg> &Ins,
4168 SDLoc dl, SelectionDAG &DAG,
4169 SmallVectorImpl<SDValue> &InVals) const {
4171 bool isELFv2ABI = Subtarget.isELFv2ABI();
4172 bool isLittleEndian = Subtarget.isLittleEndian();
4173 unsigned NumOps = Outs.size();
4175 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4176 unsigned PtrByteSize = 8;
4178 MachineFunction &MF = DAG.getMachineFunction();
4180 // Mark this function as potentially containing a function that contains a
4181 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4182 // and restoring the callers stack pointer in this functions epilog. This is
4183 // done because by tail calling the called function might overwrite the value
4184 // in this function's (MF) stack pointer stack slot 0(SP).
4185 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4186 CallConv == CallingConv::Fast)
4187 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4189 // Count how many bytes are to be pushed on the stack, including the linkage
4190 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4191 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4192 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4193 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4195 unsigned NumBytes = LinkageSize;
4197 // Add up all the space actually used.
4198 for (unsigned i = 0; i != NumOps; ++i) {
4199 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4200 EVT ArgVT = Outs[i].VT;
4201 EVT OrigVT = Outs[i].ArgVT;
4203 /* Respect alignment of argument on the stack. */
4205 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4206 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4208 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4209 if (Flags.isInConsecutiveRegsLast())
4210 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4213 unsigned NumBytesActuallyUsed = NumBytes;
4215 // The prolog code of the callee may store up to 8 GPR argument registers to
4216 // the stack, allowing va_start to index over them in memory if its varargs.
4217 // Because we cannot tell if this is needed on the caller side, we have to
4218 // conservatively assume that it is needed. As such, make sure we have at
4219 // least enough stack space for the caller to store the 8 GPRs.
4220 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4221 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4223 // Tail call needs the stack to be aligned.
4224 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4225 CallConv == CallingConv::Fast)
4226 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4228 // Calculate by how many bytes the stack has to be adjusted in case of tail
4229 // call optimization.
4230 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4232 // To protect arguments on the stack from being clobbered in a tail call,
4233 // force all the loads to happen before doing any other lowering.
4235 Chain = DAG.getStackArgumentTokenFactor(Chain);
4237 // Adjust the stack pointer for the new arguments...
4238 // These operations are automatically eliminated by the prolog/epilog pass
4239 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4241 SDValue CallSeqStart = Chain;
4243 // Load the return address and frame pointer so it can be move somewhere else
4246 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4249 // Set up a copy of the stack pointer for use loading and storing any
4250 // arguments that may not fit in the registers available for argument
4252 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4254 // Figure out which arguments are going to go in registers, and which in
4255 // memory. Also, if this is a vararg function, floating point operations
4256 // must be stored to our stack, and loaded into integer regs as well, if
4257 // any integer regs are available for argument passing.
4258 unsigned ArgOffset = LinkageSize;
4259 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4261 static const MCPhysReg GPR[] = {
4262 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4263 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4265 static const MCPhysReg *FPR = GetFPR();
4267 static const MCPhysReg VR[] = {
4268 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4269 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4271 static const MCPhysReg VSRH[] = {
4272 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4273 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4276 const unsigned NumGPRs = array_lengthof(GPR);
4277 const unsigned NumFPRs = 13;
4278 const unsigned NumVRs = array_lengthof(VR);
4280 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4281 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4283 SmallVector<SDValue, 8> MemOpChains;
4284 for (unsigned i = 0; i != NumOps; ++i) {
4285 SDValue Arg = OutVals[i];
4286 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4287 EVT ArgVT = Outs[i].VT;
4288 EVT OrigVT = Outs[i].ArgVT;
4290 /* Respect alignment of argument on the stack. */
4292 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4293 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4295 /* Compute GPR index associated with argument offset. */
4296 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4297 GPR_idx = std::min(GPR_idx, NumGPRs);
4299 // PtrOff will be used to store the current argument to the stack if a
4300 // register cannot be found for it.
4303 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4305 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4307 // Promote integers to 64-bit values.
4308 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4309 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4310 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4311 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4314 // FIXME memcpy is used way more than necessary. Correctness first.
4315 // Note: "by value" is code for passing a structure by value, not
4317 if (Flags.isByVal()) {
4318 // Note: Size includes alignment padding, so
4319 // struct x { short a; char b; }
4320 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4321 // These are the proper values we need for right-justifying the
4322 // aggregate in a parameter register.
4323 unsigned Size = Flags.getByValSize();
4325 // An empty aggregate parameter takes up no storage and no
4330 // All aggregates smaller than 8 bytes must be passed right-justified.
4331 if (Size==1 || Size==2 || Size==4) {
4332 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4333 if (GPR_idx != NumGPRs) {
4334 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4335 MachinePointerInfo(), VT,
4336 false, false, false, 0);
4337 MemOpChains.push_back(Load.getValue(1));
4338 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4340 ArgOffset += PtrByteSize;
4345 if (GPR_idx == NumGPRs && Size < 8) {
4346 SDValue AddPtr = PtrOff;
4347 if (!isLittleEndian) {
4348 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4349 PtrOff.getValueType());
4350 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4352 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4355 ArgOffset += PtrByteSize;
4358 // Copy entire object into memory. There are cases where gcc-generated
4359 // code assumes it is there, even if it could be put entirely into
4360 // registers. (This is not what the doc says.)
4362 // FIXME: The above statement is likely due to a misunderstanding of the
4363 // documents. All arguments must be copied into the parameter area BY
4364 // THE CALLEE in the event that the callee takes the address of any
4365 // formal argument. That has not yet been implemented. However, it is
4366 // reasonable to use the stack area as a staging area for the register
4369 // Skip this for small aggregates, as we will use the same slot for a
4370 // right-justified copy, below.
4372 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4376 // When a register is available, pass a small aggregate right-justified.
4377 if (Size < 8 && GPR_idx != NumGPRs) {
4378 // The easiest way to get this right-justified in a register
4379 // is to copy the structure into the rightmost portion of a
4380 // local variable slot, then load the whole slot into the
4382 // FIXME: The memcpy seems to produce pretty awful code for
4383 // small aggregates, particularly for packed ones.
4384 // FIXME: It would be preferable to use the slot in the
4385 // parameter save area instead of a new local variable.
4386 SDValue AddPtr = PtrOff;
4387 if (!isLittleEndian) {
4388 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4389 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4391 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4395 // Load the slot into the register.
4396 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4397 MachinePointerInfo(),
4398 false, false, false, 0);
4399 MemOpChains.push_back(Load.getValue(1));
4400 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4402 // Done with this argument.
4403 ArgOffset += PtrByteSize;
4407 // For aggregates larger than PtrByteSize, copy the pieces of the
4408 // object that fit into registers from the parameter save area.
4409 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4410 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4411 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4412 if (GPR_idx != NumGPRs) {
4413 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4414 MachinePointerInfo(),
4415 false, false, false, 0);
4416 MemOpChains.push_back(Load.getValue(1));
4417 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4418 ArgOffset += PtrByteSize;
4420 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4427 switch (Arg.getSimpleValueType().SimpleTy) {
4428 default: llvm_unreachable("Unexpected ValueType for argument!");
4432 // These can be scalar arguments or elements of an integer array type
4433 // passed directly. Clang may use those instead of "byval" aggregate
4434 // types to avoid forcing arguments to memory unnecessarily.
4435 if (GPR_idx != NumGPRs) {
4436 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4438 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4439 true, isTailCall, false, MemOpChains,
4440 TailCallArguments, dl);
4442 ArgOffset += PtrByteSize;
4446 // These can be scalar arguments or elements of a float array type
4447 // passed directly. The latter are used to implement ELFv2 homogenous
4448 // float aggregates.
4450 // Named arguments go into FPRs first, and once they overflow, the
4451 // remaining arguments go into GPRs and then the parameter save area.
4452 // Unnamed arguments for vararg functions always go to GPRs and
4453 // then the parameter save area. For now, put all arguments to vararg
4454 // routines always in both locations (FPR *and* GPR or stack slot).
4455 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4457 // First load the argument into the next available FPR.
4458 if (FPR_idx != NumFPRs)
4459 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4461 // Next, load the argument into GPR or stack slot if needed.
4462 if (!NeedGPROrStack)
4464 else if (GPR_idx != NumGPRs) {
4465 // In the non-vararg case, this can only ever happen in the
4466 // presence of f32 array types, since otherwise we never run
4467 // out of FPRs before running out of GPRs.
4470 // Double values are always passed in a single GPR.
4471 if (Arg.getValueType() != MVT::f32) {
4472 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4474 // Non-array float values are extended and passed in a GPR.
4475 } else if (!Flags.isInConsecutiveRegs()) {
4476 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4477 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4479 // If we have an array of floats, we collect every odd element
4480 // together with its predecessor into one GPR.
4481 } else if (ArgOffset % PtrByteSize != 0) {
4483 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4484 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4485 if (!isLittleEndian)
4487 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4489 // The final element, if even, goes into the first half of a GPR.
4490 } else if (Flags.isInConsecutiveRegsLast()) {
4491 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4492 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4493 if (!isLittleEndian)
4494 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4495 DAG.getConstant(32, MVT::i32));
4497 // Non-final even elements are skipped; they will be handled
4498 // together the with subsequent argument on the next go-around.
4502 if (ArgVal.getNode())
4503 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4505 // Single-precision floating-point values are mapped to the
4506 // second (rightmost) word of the stack doubleword.
4507 if (Arg.getValueType() == MVT::f32 &&
4508 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4509 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4510 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4513 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4514 true, isTailCall, false, MemOpChains,
4515 TailCallArguments, dl);
4517 // When passing an array of floats, the array occupies consecutive
4518 // space in the argument area; only round up to the next doubleword
4519 // at the end of the array. Otherwise, each float takes 8 bytes.
4520 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4521 Flags.isInConsecutiveRegs()) ? 4 : 8;
4522 if (Flags.isInConsecutiveRegsLast())
4523 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4532 // These can be scalar arguments or elements of a vector array type
4533 // passed directly. The latter are used to implement ELFv2 homogenous
4534 // vector aggregates.
4536 // For a varargs call, named arguments go into VRs or on the stack as
4537 // usual; unnamed arguments always go to the stack or the corresponding
4538 // GPRs when within range. For now, we always put the value in both
4539 // locations (or even all three).
4541 // We could elide this store in the case where the object fits
4542 // entirely in R registers. Maybe later.
4543 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4544 MachinePointerInfo(), false, false, 0);
4545 MemOpChains.push_back(Store);
4546 if (VR_idx != NumVRs) {
4547 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4548 MachinePointerInfo(),
4549 false, false, false, 0);
4550 MemOpChains.push_back(Load.getValue(1));
4552 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4553 Arg.getSimpleValueType() == MVT::v2i64) ?
4554 VSRH[VR_idx] : VR[VR_idx];
4557 RegsToPass.push_back(std::make_pair(VReg, Load));
4560 for (unsigned i=0; i<16; i+=PtrByteSize) {
4561 if (GPR_idx == NumGPRs)
4563 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4564 DAG.getConstant(i, PtrVT));
4565 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4566 false, false, false, 0);
4567 MemOpChains.push_back(Load.getValue(1));
4568 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4573 // Non-varargs Altivec params go into VRs or on the stack.
4574 if (VR_idx != NumVRs) {
4575 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4576 Arg.getSimpleValueType() == MVT::v2i64) ?
4577 VSRH[VR_idx] : VR[VR_idx];
4580 RegsToPass.push_back(std::make_pair(VReg, Arg));
4582 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4583 true, isTailCall, true, MemOpChains,
4584 TailCallArguments, dl);
4591 assert(NumBytesActuallyUsed == ArgOffset);
4592 (void)NumBytesActuallyUsed;
4594 if (!MemOpChains.empty())
4595 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4597 // Check if this is an indirect call (MTCTR/BCTRL).
4598 // See PrepareCall() for more information about calls through function
4599 // pointers in the 64-bit SVR4 ABI.
4601 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4602 !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4603 // Load r2 into a virtual register and store it to the TOC save area.
4604 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4605 // TOC save area offset.
4606 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4607 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4608 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4609 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4611 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4612 // This does not mean the MTCTR instruction must use R12; it's easier
4613 // to model this as an extra parameter, so do that.
4615 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4618 // Build a sequence of copy-to-reg nodes chained together with token chain
4619 // and flag operands which copy the outgoing args into the appropriate regs.
4621 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4622 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4623 RegsToPass[i].second, InFlag);
4624 InFlag = Chain.getValue(1);
4628 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4629 FPOp, true, TailCallArguments);
4631 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4632 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4637 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4638 CallingConv::ID CallConv, bool isVarArg,
4640 const SmallVectorImpl<ISD::OutputArg> &Outs,
4641 const SmallVectorImpl<SDValue> &OutVals,
4642 const SmallVectorImpl<ISD::InputArg> &Ins,
4643 SDLoc dl, SelectionDAG &DAG,
4644 SmallVectorImpl<SDValue> &InVals) const {
4646 unsigned NumOps = Outs.size();
4648 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4649 bool isPPC64 = PtrVT == MVT::i64;
4650 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4652 MachineFunction &MF = DAG.getMachineFunction();
4654 // Mark this function as potentially containing a function that contains a
4655 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4656 // and restoring the callers stack pointer in this functions epilog. This is
4657 // done because by tail calling the called function might overwrite the value
4658 // in this function's (MF) stack pointer stack slot 0(SP).
4659 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4660 CallConv == CallingConv::Fast)
4661 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4663 // Count how many bytes are to be pushed on the stack, including the linkage
4664 // area, and parameter passing area. We start with 24/48 bytes, which is
4665 // prereserved space for [SP][CR][LR][3 x unused].
4666 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4668 unsigned NumBytes = LinkageSize;
4670 // Add up all the space actually used.
4671 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4672 // they all go in registers, but we must reserve stack space for them for
4673 // possible use by the caller. In varargs or 64-bit calls, parameters are
4674 // assigned stack space in order, with padding so Altivec parameters are
4676 unsigned nAltivecParamsAtEnd = 0;
4677 for (unsigned i = 0; i != NumOps; ++i) {
4678 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4679 EVT ArgVT = Outs[i].VT;
4680 // Varargs Altivec parameters are padded to a 16 byte boundary.
4681 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4682 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4683 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4684 if (!isVarArg && !isPPC64) {
4685 // Non-varargs Altivec parameters go after all the non-Altivec
4686 // parameters; handle those later so we know how much padding we need.
4687 nAltivecParamsAtEnd++;
4690 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4691 NumBytes = ((NumBytes+15)/16)*16;
4693 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4696 // Allow for Altivec parameters at the end, if needed.
4697 if (nAltivecParamsAtEnd) {
4698 NumBytes = ((NumBytes+15)/16)*16;
4699 NumBytes += 16*nAltivecParamsAtEnd;
4702 // The prolog code of the callee may store up to 8 GPR argument registers to
4703 // the stack, allowing va_start to index over them in memory if its varargs.
4704 // Because we cannot tell if this is needed on the caller side, we have to
4705 // conservatively assume that it is needed. As such, make sure we have at
4706 // least enough stack space for the caller to store the 8 GPRs.
4707 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4709 // Tail call needs the stack to be aligned.
4710 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4711 CallConv == CallingConv::Fast)
4712 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4714 // Calculate by how many bytes the stack has to be adjusted in case of tail
4715 // call optimization.
4716 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4718 // To protect arguments on the stack from being clobbered in a tail call,
4719 // force all the loads to happen before doing any other lowering.
4721 Chain = DAG.getStackArgumentTokenFactor(Chain);
4723 // Adjust the stack pointer for the new arguments...
4724 // These operations are automatically eliminated by the prolog/epilog pass
4725 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4727 SDValue CallSeqStart = Chain;
4729 // Load the return address and frame pointer so it can be move somewhere else
4732 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4735 // Set up a copy of the stack pointer for use loading and storing any
4736 // arguments that may not fit in the registers available for argument
4740 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4742 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4744 // Figure out which arguments are going to go in registers, and which in
4745 // memory. Also, if this is a vararg function, floating point operations
4746 // must be stored to our stack, and loaded into integer regs as well, if
4747 // any integer regs are available for argument passing.
4748 unsigned ArgOffset = LinkageSize;
4749 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4751 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4752 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4753 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4755 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4756 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4757 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4759 static const MCPhysReg *FPR = GetFPR();
4761 static const MCPhysReg VR[] = {
4762 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4763 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4765 const unsigned NumGPRs = array_lengthof(GPR_32);
4766 const unsigned NumFPRs = 13;
4767 const unsigned NumVRs = array_lengthof(VR);
4769 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4771 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4772 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4774 SmallVector<SDValue, 8> MemOpChains;
4775 for (unsigned i = 0; i != NumOps; ++i) {
4776 SDValue Arg = OutVals[i];
4777 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4779 // PtrOff will be used to store the current argument to the stack if a
4780 // register cannot be found for it.
4783 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4785 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4787 // On PPC64, promote integers to 64-bit values.
4788 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4789 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4790 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4791 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4794 // FIXME memcpy is used way more than necessary. Correctness first.
4795 // Note: "by value" is code for passing a structure by value, not
4797 if (Flags.isByVal()) {
4798 unsigned Size = Flags.getByValSize();
4799 // Very small objects are passed right-justified. Everything else is
4800 // passed left-justified.
4801 if (Size==1 || Size==2) {
4802 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4803 if (GPR_idx != NumGPRs) {
4804 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4805 MachinePointerInfo(), VT,
4806 false, false, false, 0);
4807 MemOpChains.push_back(Load.getValue(1));
4808 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4810 ArgOffset += PtrByteSize;
4812 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4813 PtrOff.getValueType());
4814 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4815 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4818 ArgOffset += PtrByteSize;
4822 // Copy entire object into memory. There are cases where gcc-generated
4823 // code assumes it is there, even if it could be put entirely into
4824 // registers. (This is not what the doc says.)
4825 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4829 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4830 // copy the pieces of the object that fit into registers from the
4831 // parameter save area.
4832 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4833 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4834 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4835 if (GPR_idx != NumGPRs) {
4836 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4837 MachinePointerInfo(),
4838 false, false, false, 0);
4839 MemOpChains.push_back(Load.getValue(1));
4840 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4841 ArgOffset += PtrByteSize;
4843 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4850 switch (Arg.getSimpleValueType().SimpleTy) {
4851 default: llvm_unreachable("Unexpected ValueType for argument!");
4855 if (GPR_idx != NumGPRs) {
4856 if (Arg.getValueType() == MVT::i1)
4857 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4859 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4861 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4862 isPPC64, isTailCall, false, MemOpChains,
4863 TailCallArguments, dl);
4865 ArgOffset += PtrByteSize;
4869 if (FPR_idx != NumFPRs) {
4870 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4873 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4874 MachinePointerInfo(), false, false, 0);
4875 MemOpChains.push_back(Store);
4877 // Float varargs are always shadowed in available integer registers
4878 if (GPR_idx != NumGPRs) {
4879 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4880 MachinePointerInfo(), false, false,
4882 MemOpChains.push_back(Load.getValue(1));
4883 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4885 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4886 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4887 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4888 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4889 MachinePointerInfo(),
4890 false, false, false, 0);
4891 MemOpChains.push_back(Load.getValue(1));
4892 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4895 // If we have any FPRs remaining, we may also have GPRs remaining.
4896 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4898 if (GPR_idx != NumGPRs)
4900 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4901 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4905 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4906 isPPC64, isTailCall, false, MemOpChains,
4907 TailCallArguments, dl);
4911 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4918 // These go aligned on the stack, or in the corresponding R registers
4919 // when within range. The Darwin PPC ABI doc claims they also go in
4920 // V registers; in fact gcc does this only for arguments that are
4921 // prototyped, not for those that match the ... We do it for all
4922 // arguments, seems to work.
4923 while (ArgOffset % 16 !=0) {
4924 ArgOffset += PtrByteSize;
4925 if (GPR_idx != NumGPRs)
4928 // We could elide this store in the case where the object fits
4929 // entirely in R registers. Maybe later.
4930 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4931 DAG.getConstant(ArgOffset, PtrVT));
4932 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4933 MachinePointerInfo(), false, false, 0);
4934 MemOpChains.push_back(Store);
4935 if (VR_idx != NumVRs) {
4936 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4937 MachinePointerInfo(),
4938 false, false, false, 0);
4939 MemOpChains.push_back(Load.getValue(1));
4940 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4943 for (unsigned i=0; i<16; i+=PtrByteSize) {
4944 if (GPR_idx == NumGPRs)
4946 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4947 DAG.getConstant(i, PtrVT));
4948 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4949 false, false, false, 0);
4950 MemOpChains.push_back(Load.getValue(1));
4951 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4956 // Non-varargs Altivec params generally go in registers, but have
4957 // stack space allocated at the end.
4958 if (VR_idx != NumVRs) {
4959 // Doesn't have GPR space allocated.
4960 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4961 } else if (nAltivecParamsAtEnd==0) {
4962 // We are emitting Altivec params in order.
4963 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4964 isPPC64, isTailCall, true, MemOpChains,
4965 TailCallArguments, dl);
4971 // If all Altivec parameters fit in registers, as they usually do,
4972 // they get stack space following the non-Altivec parameters. We
4973 // don't track this here because nobody below needs it.
4974 // If there are more Altivec parameters than fit in registers emit
4976 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4978 // Offset is aligned; skip 1st 12 params which go in V registers.
4979 ArgOffset = ((ArgOffset+15)/16)*16;
4981 for (unsigned i = 0; i != NumOps; ++i) {
4982 SDValue Arg = OutVals[i];
4983 EVT ArgType = Outs[i].VT;
4984 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4985 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4988 // We are emitting Altivec params in order.
4989 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4990 isPPC64, isTailCall, true, MemOpChains,
4991 TailCallArguments, dl);
4998 if (!MemOpChains.empty())
4999 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5001 // On Darwin, R12 must contain the address of an indirect callee. This does
5002 // not mean the MTCTR instruction must use R12; it's easier to model this as
5003 // an extra parameter, so do that.
5005 !dyn_cast<GlobalAddressSDNode>(Callee) &&
5006 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
5007 !isBLACompatibleAddress(Callee, DAG))
5008 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5009 PPC::R12), Callee));
5011 // Build a sequence of copy-to-reg nodes chained together with token chain
5012 // and flag operands which copy the outgoing args into the appropriate regs.
5014 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5015 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5016 RegsToPass[i].second, InFlag);
5017 InFlag = Chain.getValue(1);
5021 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5022 FPOp, true, TailCallArguments);
5024 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5025 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5030 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5031 MachineFunction &MF, bool isVarArg,
5032 const SmallVectorImpl<ISD::OutputArg> &Outs,
5033 LLVMContext &Context) const {
5034 SmallVector<CCValAssign, 16> RVLocs;
5035 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5036 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5040 PPCTargetLowering::LowerReturn(SDValue Chain,
5041 CallingConv::ID CallConv, bool isVarArg,
5042 const SmallVectorImpl<ISD::OutputArg> &Outs,
5043 const SmallVectorImpl<SDValue> &OutVals,
5044 SDLoc dl, SelectionDAG &DAG) const {
5046 SmallVector<CCValAssign, 16> RVLocs;
5047 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5049 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5052 SmallVector<SDValue, 4> RetOps(1, Chain);
5054 // Copy the result values into the output registers.
5055 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5056 CCValAssign &VA = RVLocs[i];
5057 assert(VA.isRegLoc() && "Can only return in registers!");
5059 SDValue Arg = OutVals[i];
5061 switch (VA.getLocInfo()) {
5062 default: llvm_unreachable("Unknown loc info!");
5063 case CCValAssign::Full: break;
5064 case CCValAssign::AExt:
5065 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5067 case CCValAssign::ZExt:
5068 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5070 case CCValAssign::SExt:
5071 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5075 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5076 Flag = Chain.getValue(1);
5077 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5080 RetOps[0] = Chain; // Update chain.
5082 // Add the flag if we have it.
5084 RetOps.push_back(Flag);
5086 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5089 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5090 const PPCSubtarget &Subtarget) const {
5091 // When we pop the dynamic allocation we need to restore the SP link.
5094 // Get the corect type for pointers.
5095 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5097 // Construct the stack pointer operand.
5098 bool isPPC64 = Subtarget.isPPC64();
5099 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5100 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5102 // Get the operands for the STACKRESTORE.
5103 SDValue Chain = Op.getOperand(0);
5104 SDValue SaveSP = Op.getOperand(1);
5106 // Load the old link SP.
5107 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5108 MachinePointerInfo(),
5109 false, false, false, 0);
5111 // Restore the stack pointer.
5112 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5114 // Store the old link SP.
5115 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5122 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5123 MachineFunction &MF = DAG.getMachineFunction();
5124 bool isPPC64 = Subtarget.isPPC64();
5125 bool isDarwinABI = Subtarget.isDarwinABI();
5126 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5128 // Get current frame pointer save index. The users of this index will be
5129 // primarily DYNALLOC instructions.
5130 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5131 int RASI = FI->getReturnAddrSaveIndex();
5133 // If the frame pointer save index hasn't been defined yet.
5135 // Find out what the fix offset of the frame pointer save area.
5136 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5137 // Allocate the frame index for frame pointer save area.
5138 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
5140 FI->setReturnAddrSaveIndex(RASI);
5142 return DAG.getFrameIndex(RASI, PtrVT);
5146 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5147 MachineFunction &MF = DAG.getMachineFunction();
5148 bool isPPC64 = Subtarget.isPPC64();
5149 bool isDarwinABI = Subtarget.isDarwinABI();
5150 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5152 // Get current frame pointer save index. The users of this index will be
5153 // primarily DYNALLOC instructions.
5154 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5155 int FPSI = FI->getFramePointerSaveIndex();
5157 // If the frame pointer save index hasn't been defined yet.
5159 // Find out what the fix offset of the frame pointer save area.
5160 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5163 // Allocate the frame index for frame pointer save area.
5164 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5166 FI->setFramePointerSaveIndex(FPSI);
5168 return DAG.getFrameIndex(FPSI, PtrVT);
5171 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5173 const PPCSubtarget &Subtarget) const {
5175 SDValue Chain = Op.getOperand(0);
5176 SDValue Size = Op.getOperand(1);
5179 // Get the corect type for pointers.
5180 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5182 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5183 DAG.getConstant(0, PtrVT), Size);
5184 // Construct a node for the frame pointer save index.
5185 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5186 // Build a DYNALLOC node.
5187 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5188 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5189 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5192 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5193 SelectionDAG &DAG) const {
5195 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5196 DAG.getVTList(MVT::i32, MVT::Other),
5197 Op.getOperand(0), Op.getOperand(1));
5200 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5201 SelectionDAG &DAG) const {
5203 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5204 Op.getOperand(0), Op.getOperand(1));
5207 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5208 assert(Op.getValueType() == MVT::i1 &&
5209 "Custom lowering only for i1 loads");
5211 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5214 LoadSDNode *LD = cast<LoadSDNode>(Op);
5216 SDValue Chain = LD->getChain();
5217 SDValue BasePtr = LD->getBasePtr();
5218 MachineMemOperand *MMO = LD->getMemOperand();
5220 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5221 BasePtr, MVT::i8, MMO);
5222 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5224 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5225 return DAG.getMergeValues(Ops, dl);
5228 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5229 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5230 "Custom lowering only for i1 stores");
5232 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5235 StoreSDNode *ST = cast<StoreSDNode>(Op);
5237 SDValue Chain = ST->getChain();
5238 SDValue BasePtr = ST->getBasePtr();
5239 SDValue Value = ST->getValue();
5240 MachineMemOperand *MMO = ST->getMemOperand();
5242 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5243 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5246 // FIXME: Remove this once the ANDI glue bug is fixed:
5247 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5248 assert(Op.getValueType() == MVT::i1 &&
5249 "Custom lowering only for i1 results");
5252 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5256 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5258 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5259 // Not FP? Not a fsel.
5260 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5261 !Op.getOperand(2).getValueType().isFloatingPoint())
5264 // We might be able to do better than this under some circumstances, but in
5265 // general, fsel-based lowering of select is a finite-math-only optimization.
5266 // For more information, see section F.3 of the 2.06 ISA specification.
5267 if (!DAG.getTarget().Options.NoInfsFPMath ||
5268 !DAG.getTarget().Options.NoNaNsFPMath)
5271 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5273 EVT ResVT = Op.getValueType();
5274 EVT CmpVT = Op.getOperand(0).getValueType();
5275 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5276 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5279 // If the RHS of the comparison is a 0.0, we don't need to do the
5280 // subtraction at all.
5282 if (isFloatingPointZero(RHS))
5284 default: break; // SETUO etc aren't handled by fsel.
5288 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5289 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5290 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5291 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5292 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5293 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5294 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5297 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5300 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5301 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5302 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5305 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5308 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5309 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5310 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5311 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5316 default: break; // SETUO etc aren't handled by fsel.
5320 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5321 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5322 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5323 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5324 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5325 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5326 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5327 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5330 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5331 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5332 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5333 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5336 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5337 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5338 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5339 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5342 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5343 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5344 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5345 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5348 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5349 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5350 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5351 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5356 // FIXME: Split this code up when LegalizeDAGTypes lands.
5357 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5359 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5360 SDValue Src = Op.getOperand(0);
5361 if (Src.getValueType() == MVT::f32)
5362 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5365 switch (Op.getSimpleValueType().SimpleTy) {
5366 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5368 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5369 (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5374 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5375 "i64 FP_TO_UINT is supported only with FPCVT");
5376 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5382 // Convert the FP value to an int value through memory.
5383 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5384 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5385 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5386 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5387 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5389 // Emit a store to the stack slot.
5392 MachineFunction &MF = DAG.getMachineFunction();
5393 MachineMemOperand *MMO =
5394 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5395 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5396 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5397 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5399 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5400 MPI, false, false, 0);
5402 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5404 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5405 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5406 DAG.getConstant(4, FIPtr.getValueType()));
5407 MPI = MachinePointerInfo();
5410 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5411 false, false, false, 0);
5414 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5415 SelectionDAG &DAG) const {
5417 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5418 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5421 if (Op.getOperand(0).getValueType() == MVT::i1)
5422 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5423 DAG.getConstantFP(1.0, Op.getValueType()),
5424 DAG.getConstantFP(0.0, Op.getValueType()));
5426 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5427 "UINT_TO_FP is supported only with FPCVT");
5429 // If we have FCFIDS, then use it when converting to single-precision.
5430 // Otherwise, convert to double-precision and then round.
5431 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5432 (Op.getOpcode() == ISD::UINT_TO_FP ?
5433 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5434 (Op.getOpcode() == ISD::UINT_TO_FP ?
5435 PPCISD::FCFIDU : PPCISD::FCFID);
5436 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5437 MVT::f32 : MVT::f64;
5439 if (Op.getOperand(0).getValueType() == MVT::i64) {
5440 SDValue SINT = Op.getOperand(0);
5441 // When converting to single-precision, we actually need to convert
5442 // to double-precision first and then round to single-precision.
5443 // To avoid double-rounding effects during that operation, we have
5444 // to prepare the input operand. Bits that might be truncated when
5445 // converting to double-precision are replaced by a bit that won't
5446 // be lost at this stage, but is below the single-precision rounding
5449 // However, if -enable-unsafe-fp-math is in effect, accept double
5450 // rounding to avoid the extra overhead.
5451 if (Op.getValueType() == MVT::f32 &&
5452 !Subtarget.hasFPCVT() &&
5453 !DAG.getTarget().Options.UnsafeFPMath) {
5455 // Twiddle input to make sure the low 11 bits are zero. (If this
5456 // is the case, we are guaranteed the value will fit into the 53 bit
5457 // mantissa of an IEEE double-precision value without rounding.)
5458 // If any of those low 11 bits were not zero originally, make sure
5459 // bit 12 (value 2048) is set instead, so that the final rounding
5460 // to single-precision gets the correct result.
5461 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5462 SINT, DAG.getConstant(2047, MVT::i64));
5463 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5464 Round, DAG.getConstant(2047, MVT::i64));
5465 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5466 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5467 Round, DAG.getConstant(-2048, MVT::i64));
5469 // However, we cannot use that value unconditionally: if the magnitude
5470 // of the input value is small, the bit-twiddling we did above might
5471 // end up visibly changing the output. Fortunately, in that case, we
5472 // don't need to twiddle bits since the original input will convert
5473 // exactly to double-precision floating-point already. Therefore,
5474 // construct a conditional to use the original value if the top 11
5475 // bits are all sign-bit copies, and use the rounded value computed
5477 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5478 SINT, DAG.getConstant(53, MVT::i32));
5479 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5480 Cond, DAG.getConstant(1, MVT::i64));
5481 Cond = DAG.getSetCC(dl, MVT::i32,
5482 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5484 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5487 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5488 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5490 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5491 FP = DAG.getNode(ISD::FP_ROUND, dl,
5492 MVT::f32, FP, DAG.getIntPtrConstant(0));
5496 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5497 "Unhandled INT_TO_FP type in custom expander!");
5498 // Since we only generate this in 64-bit mode, we can take advantage of
5499 // 64-bit registers. In particular, sign extend the input value into the
5500 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5501 // then lfd it and fcfid it.
5502 MachineFunction &MF = DAG.getMachineFunction();
5503 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5504 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5507 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5508 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5509 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5511 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5512 MachinePointerInfo::getFixedStack(FrameIdx),
5515 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5516 "Expected an i32 store");
5517 MachineMemOperand *MMO =
5518 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5519 MachineMemOperand::MOLoad, 4, 4);
5520 SDValue Ops[] = { Store, FIdx };
5521 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5522 PPCISD::LFIWZX : PPCISD::LFIWAX,
5523 dl, DAG.getVTList(MVT::f64, MVT::Other),
5524 Ops, MVT::i32, MMO);
5526 assert(Subtarget.isPPC64() &&
5527 "i32->FP without LFIWAX supported only on PPC64");
5529 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5530 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5532 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5535 // STD the extended value into the stack slot.
5536 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5537 MachinePointerInfo::getFixedStack(FrameIdx),
5540 // Load the value as a double.
5541 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5542 MachinePointerInfo::getFixedStack(FrameIdx),
5543 false, false, false, 0);
5546 // FCFID it and return it.
5547 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5548 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5549 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5553 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5554 SelectionDAG &DAG) const {
5557 The rounding mode is in bits 30:31 of FPSR, and has the following
5564 FLT_ROUNDS, on the other hand, expects the following:
5571 To perform the conversion, we do:
5572 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5575 MachineFunction &MF = DAG.getMachineFunction();
5576 EVT VT = Op.getValueType();
5577 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5579 // Save FP Control Word to register
5581 MVT::f64, // return register
5582 MVT::Glue // unused in this context
5584 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5586 // Save FP register to stack slot
5587 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5588 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5589 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5590 StackSlot, MachinePointerInfo(), false, false,0);
5592 // Load FP Control Word from low 32 bits of stack slot.
5593 SDValue Four = DAG.getConstant(4, PtrVT);
5594 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5595 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5596 false, false, false, 0);
5598 // Transform as necessary
5600 DAG.getNode(ISD::AND, dl, MVT::i32,
5601 CWD, DAG.getConstant(3, MVT::i32));
5603 DAG.getNode(ISD::SRL, dl, MVT::i32,
5604 DAG.getNode(ISD::AND, dl, MVT::i32,
5605 DAG.getNode(ISD::XOR, dl, MVT::i32,
5606 CWD, DAG.getConstant(3, MVT::i32)),
5607 DAG.getConstant(3, MVT::i32)),
5608 DAG.getConstant(1, MVT::i32));
5611 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5613 return DAG.getNode((VT.getSizeInBits() < 16 ?
5614 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5617 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5618 EVT VT = Op.getValueType();
5619 unsigned BitWidth = VT.getSizeInBits();
5621 assert(Op.getNumOperands() == 3 &&
5622 VT == Op.getOperand(1).getValueType() &&
5625 // Expand into a bunch of logical ops. Note that these ops
5626 // depend on the PPC behavior for oversized shift amounts.
5627 SDValue Lo = Op.getOperand(0);
5628 SDValue Hi = Op.getOperand(1);
5629 SDValue Amt = Op.getOperand(2);
5630 EVT AmtVT = Amt.getValueType();
5632 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5633 DAG.getConstant(BitWidth, AmtVT), Amt);
5634 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5635 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5636 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5637 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5638 DAG.getConstant(-BitWidth, AmtVT));
5639 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5640 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5641 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5642 SDValue OutOps[] = { OutLo, OutHi };
5643 return DAG.getMergeValues(OutOps, dl);
5646 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5647 EVT VT = Op.getValueType();
5649 unsigned BitWidth = VT.getSizeInBits();
5650 assert(Op.getNumOperands() == 3 &&
5651 VT == Op.getOperand(1).getValueType() &&
5654 // Expand into a bunch of logical ops. Note that these ops
5655 // depend on the PPC behavior for oversized shift amounts.
5656 SDValue Lo = Op.getOperand(0);
5657 SDValue Hi = Op.getOperand(1);
5658 SDValue Amt = Op.getOperand(2);
5659 EVT AmtVT = Amt.getValueType();
5661 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5662 DAG.getConstant(BitWidth, AmtVT), Amt);
5663 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5664 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5665 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5666 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5667 DAG.getConstant(-BitWidth, AmtVT));
5668 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5669 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5670 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5671 SDValue OutOps[] = { OutLo, OutHi };
5672 return DAG.getMergeValues(OutOps, dl);
5675 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5677 EVT VT = Op.getValueType();
5678 unsigned BitWidth = VT.getSizeInBits();
5679 assert(Op.getNumOperands() == 3 &&
5680 VT == Op.getOperand(1).getValueType() &&
5683 // Expand into a bunch of logical ops, followed by a select_cc.
5684 SDValue Lo = Op.getOperand(0);
5685 SDValue Hi = Op.getOperand(1);
5686 SDValue Amt = Op.getOperand(2);
5687 EVT AmtVT = Amt.getValueType();
5689 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5690 DAG.getConstant(BitWidth, AmtVT), Amt);
5691 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5692 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5693 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5694 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5695 DAG.getConstant(-BitWidth, AmtVT));
5696 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5697 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5698 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5699 Tmp4, Tmp6, ISD::SETLE);
5700 SDValue OutOps[] = { OutLo, OutHi };
5701 return DAG.getMergeValues(OutOps, dl);
5704 //===----------------------------------------------------------------------===//
5705 // Vector related lowering.
5708 /// BuildSplatI - Build a canonical splati of Val with an element size of
5709 /// SplatSize. Cast the result to VT.
5710 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5711 SelectionDAG &DAG, SDLoc dl) {
5712 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5714 static const EVT VTys[] = { // canonical VT to use for each size.
5715 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5718 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5720 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5724 EVT CanonicalVT = VTys[SplatSize-1];
5726 // Build a canonical splat for this value.
5727 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5728 SmallVector<SDValue, 8> Ops;
5729 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5730 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5731 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5734 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5735 /// specified intrinsic ID.
5736 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5737 SelectionDAG &DAG, SDLoc dl,
5738 EVT DestVT = MVT::Other) {
5739 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5740 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5741 DAG.getConstant(IID, MVT::i32), Op);
5744 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5745 /// specified intrinsic ID.
5746 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5747 SelectionDAG &DAG, SDLoc dl,
5748 EVT DestVT = MVT::Other) {
5749 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5750 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5751 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5754 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5755 /// specified intrinsic ID.
5756 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5757 SDValue Op2, SelectionDAG &DAG,
5758 SDLoc dl, EVT DestVT = MVT::Other) {
5759 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5760 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5761 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5765 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5766 /// amount. The result has the specified value type.
5767 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5768 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5769 // Force LHS/RHS to be the right type.
5770 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5771 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5774 for (unsigned i = 0; i != 16; ++i)
5776 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5777 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5780 // If this is a case we can't handle, return null and let the default
5781 // expansion code take care of it. If we CAN select this case, and if it
5782 // selects to a single instruction, return Op. Otherwise, if we can codegen
5783 // this case more efficiently than a constant pool load, lower it to the
5784 // sequence of ops that should be used.
5785 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5786 SelectionDAG &DAG) const {
5788 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5789 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5791 // Check if this is a splat of a constant value.
5792 APInt APSplatBits, APSplatUndef;
5793 unsigned SplatBitSize;
5795 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5796 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5799 unsigned SplatBits = APSplatBits.getZExtValue();
5800 unsigned SplatUndef = APSplatUndef.getZExtValue();
5801 unsigned SplatSize = SplatBitSize / 8;
5803 // First, handle single instruction cases.
5806 if (SplatBits == 0) {
5807 // Canonicalize all zero vectors to be v4i32.
5808 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5809 SDValue Z = DAG.getConstant(0, MVT::i32);
5810 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5811 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5816 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5817 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5819 if (SextVal >= -16 && SextVal <= 15)
5820 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5823 // Two instruction sequences.
5825 // If this value is in the range [-32,30] and is even, use:
5826 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5827 // If this value is in the range [17,31] and is odd, use:
5828 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5829 // If this value is in the range [-31,-17] and is odd, use:
5830 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5831 // Note the last two are three-instruction sequences.
5832 if (SextVal >= -32 && SextVal <= 31) {
5833 // To avoid having these optimizations undone by constant folding,
5834 // we convert to a pseudo that will be expanded later into one of
5836 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5837 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5838 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5839 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5840 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5841 if (VT == Op.getValueType())
5844 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5847 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5848 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5850 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5851 // Make -1 and vspltisw -1:
5852 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5854 // Make the VSLW intrinsic, computing 0x8000_0000.
5855 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5858 // xor by OnesV to invert it.
5859 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5860 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5863 // The remaining cases assume either big endian element order or
5864 // a splat-size that equates to the element size of the vector
5865 // to be built. An example that doesn't work for little endian is
5866 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5867 // and a vector element size of 16 bits. The code below will
5868 // produce the vector in big endian element order, which for little
5869 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5871 // For now, just avoid these optimizations in that case.
5872 // FIXME: Develop correct optimizations for LE with mismatched
5873 // splat and element sizes.
5875 if (Subtarget.isLittleEndian() &&
5876 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5879 // Check to see if this is a wide variety of vsplti*, binop self cases.
5880 static const signed char SplatCsts[] = {
5881 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5882 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5885 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5886 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5887 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5888 int i = SplatCsts[idx];
5890 // Figure out what shift amount will be used by altivec if shifted by i in
5892 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5894 // vsplti + shl self.
5895 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5896 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5897 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5898 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5899 Intrinsic::ppc_altivec_vslw
5901 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5902 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5905 // vsplti + srl self.
5906 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5907 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5908 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5909 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5910 Intrinsic::ppc_altivec_vsrw
5912 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5913 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5916 // vsplti + sra self.
5917 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5918 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5919 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5920 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5921 Intrinsic::ppc_altivec_vsraw
5923 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5924 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5927 // vsplti + rol self.
5928 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5929 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5930 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5931 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5932 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5933 Intrinsic::ppc_altivec_vrlw
5935 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5936 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5939 // t = vsplti c, result = vsldoi t, t, 1
5940 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5941 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5942 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5944 // t = vsplti c, result = vsldoi t, t, 2
5945 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5946 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5947 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5949 // t = vsplti c, result = vsldoi t, t, 3
5950 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5951 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5952 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5959 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5960 /// the specified operations to build the shuffle.
5961 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5962 SDValue RHS, SelectionDAG &DAG,
5964 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5965 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5966 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5969 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5981 if (OpNum == OP_COPY) {
5982 if (LHSID == (1*9+2)*9+3) return LHS;
5983 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5987 SDValue OpLHS, OpRHS;
5988 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5989 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5993 default: llvm_unreachable("Unknown i32 permute!");
5995 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5996 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5997 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5998 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6001 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6002 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6003 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6004 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6007 for (unsigned i = 0; i != 16; ++i)
6008 ShufIdxs[i] = (i&3)+0;
6011 for (unsigned i = 0; i != 16; ++i)
6012 ShufIdxs[i] = (i&3)+4;
6015 for (unsigned i = 0; i != 16; ++i)
6016 ShufIdxs[i] = (i&3)+8;
6019 for (unsigned i = 0; i != 16; ++i)
6020 ShufIdxs[i] = (i&3)+12;
6023 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6025 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6027 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6029 EVT VT = OpLHS.getValueType();
6030 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6031 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6032 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6033 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6036 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6037 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6038 /// return the code it can be lowered into. Worst case, it can always be
6039 /// lowered into a vperm.
6040 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6041 SelectionDAG &DAG) const {
6043 SDValue V1 = Op.getOperand(0);
6044 SDValue V2 = Op.getOperand(1);
6045 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6046 EVT VT = Op.getValueType();
6047 bool isLittleEndian = Subtarget.isLittleEndian();
6049 // Cases that are handled by instructions that take permute immediates
6050 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6051 // selected by the instruction selector.
6052 if (V2.getOpcode() == ISD::UNDEF) {
6053 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6054 PPC::isSplatShuffleMask(SVOp, 2) ||
6055 PPC::isSplatShuffleMask(SVOp, 4) ||
6056 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6057 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6058 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6059 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6060 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6061 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6062 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6063 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6064 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6069 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6070 // and produce a fixed permutation. If any of these match, do not lower to
6072 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6073 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6074 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6075 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6076 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6077 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6078 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6079 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6080 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6081 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6084 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6085 // perfect shuffle table to emit an optimal matching sequence.
6086 ArrayRef<int> PermMask = SVOp->getMask();
6088 unsigned PFIndexes[4];
6089 bool isFourElementShuffle = true;
6090 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6091 unsigned EltNo = 8; // Start out undef.
6092 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6093 if (PermMask[i*4+j] < 0)
6094 continue; // Undef, ignore it.
6096 unsigned ByteSource = PermMask[i*4+j];
6097 if ((ByteSource & 3) != j) {
6098 isFourElementShuffle = false;
6103 EltNo = ByteSource/4;
6104 } else if (EltNo != ByteSource/4) {
6105 isFourElementShuffle = false;
6109 PFIndexes[i] = EltNo;
6112 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6113 // perfect shuffle vector to determine if it is cost effective to do this as
6114 // discrete instructions, or whether we should use a vperm.
6115 // For now, we skip this for little endian until such time as we have a
6116 // little-endian perfect shuffle table.
6117 if (isFourElementShuffle && !isLittleEndian) {
6118 // Compute the index in the perfect shuffle table.
6119 unsigned PFTableIndex =
6120 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6122 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6123 unsigned Cost = (PFEntry >> 30);
6125 // Determining when to avoid vperm is tricky. Many things affect the cost
6126 // of vperm, particularly how many times the perm mask needs to be computed.
6127 // For example, if the perm mask can be hoisted out of a loop or is already
6128 // used (perhaps because there are multiple permutes with the same shuffle
6129 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6130 // the loop requires an extra register.
6132 // As a compromise, we only emit discrete instructions if the shuffle can be
6133 // generated in 3 or fewer operations. When we have loop information
6134 // available, if this block is within a loop, we should avoid using vperm
6135 // for 3-operation perms and use a constant pool load instead.
6137 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6140 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6141 // vector that will get spilled to the constant pool.
6142 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6144 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6145 // that it is in input element units, not in bytes. Convert now.
6147 // For little endian, the order of the input vectors is reversed, and
6148 // the permutation mask is complemented with respect to 31. This is
6149 // necessary to produce proper semantics with the big-endian-biased vperm
6151 EVT EltVT = V1.getValueType().getVectorElementType();
6152 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6154 SmallVector<SDValue, 16> ResultMask;
6155 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6156 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6158 for (unsigned j = 0; j != BytesPerElement; ++j)
6160 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6163 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6167 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6170 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6173 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6177 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6178 /// altivec comparison. If it is, return true and fill in Opc/isDot with
6179 /// information about the intrinsic.
6180 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6182 unsigned IntrinsicID =
6183 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6186 switch (IntrinsicID) {
6187 default: return false;
6188 // Comparison predicates.
6189 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
6190 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6191 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
6192 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
6193 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6194 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6195 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6196 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6197 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6198 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6199 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6200 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6201 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6203 // Normal Comparisons.
6204 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
6205 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
6206 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
6207 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
6208 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
6209 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
6210 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
6211 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
6212 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
6213 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
6214 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
6215 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
6216 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
6221 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6222 /// lower, do it, otherwise return null.
6223 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6224 SelectionDAG &DAG) const {
6225 // If this is a lowered altivec predicate compare, CompareOpc is set to the
6226 // opcode number of the comparison.
6230 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6231 return SDValue(); // Don't custom lower most intrinsics.
6233 // If this is a non-dot comparison, make the VCMP node and we are done.
6235 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6236 Op.getOperand(1), Op.getOperand(2),
6237 DAG.getConstant(CompareOpc, MVT::i32));
6238 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6241 // Create the PPCISD altivec 'dot' comparison node.
6243 Op.getOperand(2), // LHS
6244 Op.getOperand(3), // RHS
6245 DAG.getConstant(CompareOpc, MVT::i32)
6247 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6248 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6250 // Now that we have the comparison, emit a copy from the CR to a GPR.
6251 // This is flagged to the above dot comparison.
6252 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6253 DAG.getRegister(PPC::CR6, MVT::i32),
6254 CompNode.getValue(1));
6256 // Unpack the result based on how the target uses it.
6257 unsigned BitNo; // Bit # of CR6.
6258 bool InvertBit; // Invert result?
6259 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6260 default: // Can't happen, don't crash on invalid number though.
6261 case 0: // Return the value of the EQ bit of CR6.
6262 BitNo = 0; InvertBit = false;
6264 case 1: // Return the inverted value of the EQ bit of CR6.
6265 BitNo = 0; InvertBit = true;
6267 case 2: // Return the value of the LT bit of CR6.
6268 BitNo = 2; InvertBit = false;
6270 case 3: // Return the inverted value of the LT bit of CR6.
6271 BitNo = 2; InvertBit = true;
6275 // Shift the bit into the low position.
6276 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6277 DAG.getConstant(8-(3-BitNo), MVT::i32));
6279 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6280 DAG.getConstant(1, MVT::i32));
6282 // If we are supposed to, toggle the bit.
6284 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6285 DAG.getConstant(1, MVT::i32));
6289 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6290 SelectionDAG &DAG) const {
6292 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6293 // instructions), but for smaller types, we need to first extend up to v2i32
6294 // before doing going farther.
6295 if (Op.getValueType() == MVT::v2i64) {
6296 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6297 if (ExtVT != MVT::v2i32) {
6298 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6299 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6300 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6301 ExtVT.getVectorElementType(), 4)));
6302 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6303 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6304 DAG.getValueType(MVT::v2i32));
6313 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6314 SelectionDAG &DAG) const {
6316 // Create a stack slot that is 16-byte aligned.
6317 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6318 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6319 EVT PtrVT = getPointerTy();
6320 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6322 // Store the input value into Value#0 of the stack slot.
6323 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6324 Op.getOperand(0), FIdx, MachinePointerInfo(),
6327 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6328 false, false, false, 0);
6331 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6333 if (Op.getValueType() == MVT::v4i32) {
6334 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6336 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6337 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6339 SDValue RHSSwap = // = vrlw RHS, 16
6340 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6342 // Shrinkify inputs to v8i16.
6343 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6344 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6345 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6347 // Low parts multiplied together, generating 32-bit results (we ignore the
6349 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6350 LHS, RHS, DAG, dl, MVT::v4i32);
6352 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6353 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6354 // Shift the high parts up 16 bits.
6355 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6357 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6358 } else if (Op.getValueType() == MVT::v8i16) {
6359 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6361 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6363 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6364 LHS, RHS, Zero, DAG, dl);
6365 } else if (Op.getValueType() == MVT::v16i8) {
6366 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6367 bool isLittleEndian = Subtarget.isLittleEndian();
6369 // Multiply the even 8-bit parts, producing 16-bit sums.
6370 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6371 LHS, RHS, DAG, dl, MVT::v8i16);
6372 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6374 // Multiply the odd 8-bit parts, producing 16-bit sums.
6375 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6376 LHS, RHS, DAG, dl, MVT::v8i16);
6377 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6379 // Merge the results together. Because vmuleub and vmuloub are
6380 // instructions with a big-endian bias, we must reverse the
6381 // element numbering and reverse the meaning of "odd" and "even"
6382 // when generating little endian code.
6384 for (unsigned i = 0; i != 8; ++i) {
6385 if (isLittleEndian) {
6387 Ops[i*2+1] = 2*i+16;
6390 Ops[i*2+1] = 2*i+1+16;
6394 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6396 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6398 llvm_unreachable("Unknown mul to lower!");
6402 /// LowerOperation - Provide custom lowering hooks for some operations.
6404 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6405 switch (Op.getOpcode()) {
6406 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6407 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6408 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6409 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6410 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6411 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6412 case ISD::SETCC: return LowerSETCC(Op, DAG);
6413 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6414 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6416 return LowerVASTART(Op, DAG, Subtarget);
6419 return LowerVAARG(Op, DAG, Subtarget);
6422 return LowerVACOPY(Op, DAG, Subtarget);
6424 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
6425 case ISD::DYNAMIC_STACKALLOC:
6426 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6428 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6429 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6431 case ISD::LOAD: return LowerLOAD(Op, DAG);
6432 case ISD::STORE: return LowerSTORE(Op, DAG);
6433 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6434 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6435 case ISD::FP_TO_UINT:
6436 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6438 case ISD::UINT_TO_FP:
6439 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6440 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6442 // Lower 64-bit shifts.
6443 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6444 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6445 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6447 // Vector-related lowering.
6448 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6449 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6450 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6451 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6452 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6453 case ISD::MUL: return LowerMUL(Op, DAG);
6455 // For counter-based loop handling.
6456 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6458 // Frame & Return address.
6459 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6460 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6464 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6465 SmallVectorImpl<SDValue>&Results,
6466 SelectionDAG &DAG) const {
6467 const TargetMachine &TM = getTargetMachine();
6469 switch (N->getOpcode()) {
6471 llvm_unreachable("Do not know how to custom type legalize this operation!");
6472 case ISD::INTRINSIC_W_CHAIN: {
6473 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6474 Intrinsic::ppc_is_decremented_ctr_nonzero)
6477 assert(N->getValueType(0) == MVT::i1 &&
6478 "Unexpected result type for CTR decrement intrinsic");
6479 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6480 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6481 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6484 Results.push_back(NewInt);
6485 Results.push_back(NewInt.getValue(1));
6489 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6490 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6493 EVT VT = N->getValueType(0);
6495 if (VT == MVT::i64) {
6496 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6498 Results.push_back(NewNode);
6499 Results.push_back(NewNode.getValue(1));
6503 case ISD::FP_ROUND_INREG: {
6504 assert(N->getValueType(0) == MVT::ppcf128);
6505 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6506 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6507 MVT::f64, N->getOperand(0),
6508 DAG.getIntPtrConstant(0));
6509 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6510 MVT::f64, N->getOperand(0),
6511 DAG.getIntPtrConstant(1));
6513 // Add the two halves of the long double in round-to-zero mode.
6514 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6516 // We know the low half is about to be thrown away, so just use something
6518 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6522 case ISD::FP_TO_SINT:
6523 // LowerFP_TO_INT() can only handle f32 and f64.
6524 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6526 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6532 //===----------------------------------------------------------------------===//
6533 // Other Lowering Code
6534 //===----------------------------------------------------------------------===//
6537 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6538 bool is64bit, unsigned BinOpcode) const {
6539 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6540 const TargetInstrInfo *TII =
6541 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6543 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6544 MachineFunction *F = BB->getParent();
6545 MachineFunction::iterator It = BB;
6548 unsigned dest = MI->getOperand(0).getReg();
6549 unsigned ptrA = MI->getOperand(1).getReg();
6550 unsigned ptrB = MI->getOperand(2).getReg();
6551 unsigned incr = MI->getOperand(3).getReg();
6552 DebugLoc dl = MI->getDebugLoc();
6554 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6555 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6556 F->insert(It, loopMBB);
6557 F->insert(It, exitMBB);
6558 exitMBB->splice(exitMBB->begin(), BB,
6559 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6560 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6562 MachineRegisterInfo &RegInfo = F->getRegInfo();
6563 unsigned TmpReg = (!BinOpcode) ? incr :
6564 RegInfo.createVirtualRegister(
6565 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6566 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6570 // fallthrough --> loopMBB
6571 BB->addSuccessor(loopMBB);
6574 // l[wd]arx dest, ptr
6575 // add r0, dest, incr
6576 // st[wd]cx. r0, ptr
6578 // fallthrough --> exitMBB
6580 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6581 .addReg(ptrA).addReg(ptrB);
6583 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6584 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6585 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6586 BuildMI(BB, dl, TII->get(PPC::BCC))
6587 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6588 BB->addSuccessor(loopMBB);
6589 BB->addSuccessor(exitMBB);
6598 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6599 MachineBasicBlock *BB,
6600 bool is8bit, // operation
6601 unsigned BinOpcode) const {
6602 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6603 const TargetInstrInfo *TII =
6604 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6605 // In 64 bit mode we have to use 64 bits for addresses, even though the
6606 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6607 // registers without caring whether they're 32 or 64, but here we're
6608 // doing actual arithmetic on the addresses.
6609 bool is64bit = Subtarget.isPPC64();
6610 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6612 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6613 MachineFunction *F = BB->getParent();
6614 MachineFunction::iterator It = BB;
6617 unsigned dest = MI->getOperand(0).getReg();
6618 unsigned ptrA = MI->getOperand(1).getReg();
6619 unsigned ptrB = MI->getOperand(2).getReg();
6620 unsigned incr = MI->getOperand(3).getReg();
6621 DebugLoc dl = MI->getDebugLoc();
6623 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6624 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6625 F->insert(It, loopMBB);
6626 F->insert(It, exitMBB);
6627 exitMBB->splice(exitMBB->begin(), BB,
6628 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6629 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6631 MachineRegisterInfo &RegInfo = F->getRegInfo();
6632 const TargetRegisterClass *RC =
6633 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6634 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6635 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6636 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6637 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6638 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6639 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6640 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6641 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6642 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6643 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6644 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6645 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6647 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6651 // fallthrough --> loopMBB
6652 BB->addSuccessor(loopMBB);
6654 // The 4-byte load must be aligned, while a char or short may be
6655 // anywhere in the word. Hence all this nasty bookkeeping code.
6656 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6657 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6658 // xori shift, shift1, 24 [16]
6659 // rlwinm ptr, ptr1, 0, 0, 29
6660 // slw incr2, incr, shift
6661 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6662 // slw mask, mask2, shift
6664 // lwarx tmpDest, ptr
6665 // add tmp, tmpDest, incr2
6666 // andc tmp2, tmpDest, mask
6667 // and tmp3, tmp, mask
6668 // or tmp4, tmp3, tmp2
6671 // fallthrough --> exitMBB
6672 // srw dest, tmpDest, shift
6673 if (ptrA != ZeroReg) {
6674 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6675 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6676 .addReg(ptrA).addReg(ptrB);
6680 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6681 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6682 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6683 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6685 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6686 .addReg(Ptr1Reg).addImm(0).addImm(61);
6688 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6689 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6690 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6691 .addReg(incr).addReg(ShiftReg);
6693 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6695 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6696 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6698 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6699 .addReg(Mask2Reg).addReg(ShiftReg);
6702 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6703 .addReg(ZeroReg).addReg(PtrReg);
6705 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6706 .addReg(Incr2Reg).addReg(TmpDestReg);
6707 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6708 .addReg(TmpDestReg).addReg(MaskReg);
6709 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6710 .addReg(TmpReg).addReg(MaskReg);
6711 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6712 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6713 BuildMI(BB, dl, TII->get(PPC::STWCX))
6714 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6715 BuildMI(BB, dl, TII->get(PPC::BCC))
6716 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6717 BB->addSuccessor(loopMBB);
6718 BB->addSuccessor(exitMBB);
6723 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6728 llvm::MachineBasicBlock*
6729 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6730 MachineBasicBlock *MBB) const {
6731 DebugLoc DL = MI->getDebugLoc();
6732 const TargetInstrInfo *TII =
6733 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6735 MachineFunction *MF = MBB->getParent();
6736 MachineRegisterInfo &MRI = MF->getRegInfo();
6738 const BasicBlock *BB = MBB->getBasicBlock();
6739 MachineFunction::iterator I = MBB;
6743 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6744 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6746 unsigned DstReg = MI->getOperand(0).getReg();
6747 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6748 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6749 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6750 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6752 MVT PVT = getPointerTy();
6753 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6754 "Invalid Pointer Size!");
6755 // For v = setjmp(buf), we generate
6758 // SjLjSetup mainMBB
6764 // buf[LabelOffset] = LR
6768 // v = phi(main, restore)
6771 MachineBasicBlock *thisMBB = MBB;
6772 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6773 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6774 MF->insert(I, mainMBB);
6775 MF->insert(I, sinkMBB);
6777 MachineInstrBuilder MIB;
6779 // Transfer the remainder of BB and its successor edges to sinkMBB.
6780 sinkMBB->splice(sinkMBB->begin(), MBB,
6781 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6782 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6784 // Note that the structure of the jmp_buf used here is not compatible
6785 // with that used by libc, and is not designed to be. Specifically, it
6786 // stores only those 'reserved' registers that LLVM does not otherwise
6787 // understand how to spill. Also, by convention, by the time this
6788 // intrinsic is called, Clang has already stored the frame address in the
6789 // first slot of the buffer and stack address in the third. Following the
6790 // X86 target code, we'll store the jump address in the second slot. We also
6791 // need to save the TOC pointer (R2) to handle jumps between shared
6792 // libraries, and that will be stored in the fourth slot. The thread
6793 // identifier (R13) is not affected.
6796 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6797 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6798 const int64_t BPOffset = 4 * PVT.getStoreSize();
6800 // Prepare IP either in reg.
6801 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6802 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6803 unsigned BufReg = MI->getOperand(1).getReg();
6805 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6806 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6810 MIB.setMemRefs(MMOBegin, MMOEnd);
6813 // Naked functions never have a base pointer, and so we use r1. For all
6814 // other functions, this decision must be delayed until during PEI.
6816 if (MF->getFunction()->getAttributes().hasAttribute(
6817 AttributeSet::FunctionIndex, Attribute::Naked))
6818 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6820 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6822 MIB = BuildMI(*thisMBB, MI, DL,
6823 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6827 MIB.setMemRefs(MMOBegin, MMOEnd);
6830 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6831 const PPCRegisterInfo *TRI =
6832 getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
6833 MIB.addRegMask(TRI->getNoPreservedMask());
6835 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6837 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6839 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6841 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6842 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6846 MIB = BuildMI(mainMBB, DL,
6847 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6850 if (Subtarget.isPPC64()) {
6851 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6853 .addImm(LabelOffset)
6856 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6858 .addImm(LabelOffset)
6862 MIB.setMemRefs(MMOBegin, MMOEnd);
6864 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6865 mainMBB->addSuccessor(sinkMBB);
6868 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6869 TII->get(PPC::PHI), DstReg)
6870 .addReg(mainDstReg).addMBB(mainMBB)
6871 .addReg(restoreDstReg).addMBB(thisMBB);
6873 MI->eraseFromParent();
6878 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6879 MachineBasicBlock *MBB) const {
6880 DebugLoc DL = MI->getDebugLoc();
6881 const TargetInstrInfo *TII =
6882 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6884 MachineFunction *MF = MBB->getParent();
6885 MachineRegisterInfo &MRI = MF->getRegInfo();
6888 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6889 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6891 MVT PVT = getPointerTy();
6892 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6893 "Invalid Pointer Size!");
6895 const TargetRegisterClass *RC =
6896 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6897 unsigned Tmp = MRI.createVirtualRegister(RC);
6898 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6899 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6900 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6901 unsigned BP = (PVT == MVT::i64) ? PPC::X30 :
6902 (Subtarget.isSVR4ABI() &&
6903 MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6904 PPC::R29 : PPC::R30);
6906 MachineInstrBuilder MIB;
6908 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6909 const int64_t SPOffset = 2 * PVT.getStoreSize();
6910 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6911 const int64_t BPOffset = 4 * PVT.getStoreSize();
6913 unsigned BufReg = MI->getOperand(0).getReg();
6915 // Reload FP (the jumped-to function may not have had a
6916 // frame pointer, and if so, then its r31 will be restored
6918 if (PVT == MVT::i64) {
6919 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6923 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6927 MIB.setMemRefs(MMOBegin, MMOEnd);
6930 if (PVT == MVT::i64) {
6931 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6932 .addImm(LabelOffset)
6935 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6936 .addImm(LabelOffset)
6939 MIB.setMemRefs(MMOBegin, MMOEnd);
6942 if (PVT == MVT::i64) {
6943 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6947 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6951 MIB.setMemRefs(MMOBegin, MMOEnd);
6954 if (PVT == MVT::i64) {
6955 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6959 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6963 MIB.setMemRefs(MMOBegin, MMOEnd);
6966 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
6967 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6971 MIB.setMemRefs(MMOBegin, MMOEnd);
6975 BuildMI(*MBB, MI, DL,
6976 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6977 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6979 MI->eraseFromParent();
6984 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6985 MachineBasicBlock *BB) const {
6986 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6987 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6988 return emitEHSjLjSetJmp(MI, BB);
6989 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6990 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6991 return emitEHSjLjLongJmp(MI, BB);
6994 const TargetInstrInfo *TII =
6995 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6997 // To "insert" these instructions we actually have to insert their
6998 // control-flow patterns.
6999 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7000 MachineFunction::iterator It = BB;
7003 MachineFunction *F = BB->getParent();
7005 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7006 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7007 MI->getOpcode() == PPC::SELECT_I4 ||
7008 MI->getOpcode() == PPC::SELECT_I8)) {
7009 SmallVector<MachineOperand, 2> Cond;
7010 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7011 MI->getOpcode() == PPC::SELECT_CC_I8)
7012 Cond.push_back(MI->getOperand(4));
7014 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7015 Cond.push_back(MI->getOperand(1));
7017 DebugLoc dl = MI->getDebugLoc();
7018 const TargetInstrInfo *TII =
7019 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7020 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7021 Cond, MI->getOperand(2).getReg(),
7022 MI->getOperand(3).getReg());
7023 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7024 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7025 MI->getOpcode() == PPC::SELECT_CC_F4 ||
7026 MI->getOpcode() == PPC::SELECT_CC_F8 ||
7027 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7028 MI->getOpcode() == PPC::SELECT_I4 ||
7029 MI->getOpcode() == PPC::SELECT_I8 ||
7030 MI->getOpcode() == PPC::SELECT_F4 ||
7031 MI->getOpcode() == PPC::SELECT_F8 ||
7032 MI->getOpcode() == PPC::SELECT_VRRC) {
7033 // The incoming instruction knows the destination vreg to set, the
7034 // condition code register to branch on, the true/false values to
7035 // select between, and a branch opcode to use.
7040 // cmpTY ccX, r1, r2
7042 // fallthrough --> copy0MBB
7043 MachineBasicBlock *thisMBB = BB;
7044 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7045 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7046 DebugLoc dl = MI->getDebugLoc();
7047 F->insert(It, copy0MBB);
7048 F->insert(It, sinkMBB);
7050 // Transfer the remainder of BB and its successor edges to sinkMBB.
7051 sinkMBB->splice(sinkMBB->begin(), BB,
7052 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7053 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7055 // Next, add the true and fallthrough blocks as its successors.
7056 BB->addSuccessor(copy0MBB);
7057 BB->addSuccessor(sinkMBB);
7059 if (MI->getOpcode() == PPC::SELECT_I4 ||
7060 MI->getOpcode() == PPC::SELECT_I8 ||
7061 MI->getOpcode() == PPC::SELECT_F4 ||
7062 MI->getOpcode() == PPC::SELECT_F8 ||
7063 MI->getOpcode() == PPC::SELECT_VRRC) {
7064 BuildMI(BB, dl, TII->get(PPC::BC))
7065 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7067 unsigned SelectPred = MI->getOperand(4).getImm();
7068 BuildMI(BB, dl, TII->get(PPC::BCC))
7069 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7073 // %FalseValue = ...
7074 // # fallthrough to sinkMBB
7077 // Update machine-CFG edges
7078 BB->addSuccessor(sinkMBB);
7081 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7084 BuildMI(*BB, BB->begin(), dl,
7085 TII->get(PPC::PHI), MI->getOperand(0).getReg())
7086 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7087 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7089 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7090 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7091 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7092 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7093 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7094 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7095 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7096 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7098 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7099 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7100 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7101 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7102 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7103 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7104 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7105 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7107 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7108 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7109 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7110 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7111 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7112 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7113 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7114 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7116 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7117 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7118 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7119 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7120 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7121 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7122 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7123 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7125 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7126 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7127 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7128 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7129 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7130 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7131 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7132 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7134 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7135 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7136 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7137 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7138 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7139 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7140 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7141 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7143 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7144 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7145 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7146 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7147 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7148 BB = EmitAtomicBinary(MI, BB, false, 0);
7149 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7150 BB = EmitAtomicBinary(MI, BB, true, 0);
7152 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7153 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7154 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7156 unsigned dest = MI->getOperand(0).getReg();
7157 unsigned ptrA = MI->getOperand(1).getReg();
7158 unsigned ptrB = MI->getOperand(2).getReg();
7159 unsigned oldval = MI->getOperand(3).getReg();
7160 unsigned newval = MI->getOperand(4).getReg();
7161 DebugLoc dl = MI->getDebugLoc();
7163 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7164 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7165 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7166 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7167 F->insert(It, loop1MBB);
7168 F->insert(It, loop2MBB);
7169 F->insert(It, midMBB);
7170 F->insert(It, exitMBB);
7171 exitMBB->splice(exitMBB->begin(), BB,
7172 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7173 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7177 // fallthrough --> loopMBB
7178 BB->addSuccessor(loop1MBB);
7181 // l[wd]arx dest, ptr
7182 // cmp[wd] dest, oldval
7185 // st[wd]cx. newval, ptr
7189 // st[wd]cx. dest, ptr
7192 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7193 .addReg(ptrA).addReg(ptrB);
7194 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7195 .addReg(oldval).addReg(dest);
7196 BuildMI(BB, dl, TII->get(PPC::BCC))
7197 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7198 BB->addSuccessor(loop2MBB);
7199 BB->addSuccessor(midMBB);
7202 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7203 .addReg(newval).addReg(ptrA).addReg(ptrB);
7204 BuildMI(BB, dl, TII->get(PPC::BCC))
7205 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7206 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7207 BB->addSuccessor(loop1MBB);
7208 BB->addSuccessor(exitMBB);
7211 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7212 .addReg(dest).addReg(ptrA).addReg(ptrB);
7213 BB->addSuccessor(exitMBB);
7218 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7219 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7220 // We must use 64-bit registers for addresses when targeting 64-bit,
7221 // since we're actually doing arithmetic on them. Other registers
7223 bool is64bit = Subtarget.isPPC64();
7224 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7226 unsigned dest = MI->getOperand(0).getReg();
7227 unsigned ptrA = MI->getOperand(1).getReg();
7228 unsigned ptrB = MI->getOperand(2).getReg();
7229 unsigned oldval = MI->getOperand(3).getReg();
7230 unsigned newval = MI->getOperand(4).getReg();
7231 DebugLoc dl = MI->getDebugLoc();
7233 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7234 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7235 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7236 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7237 F->insert(It, loop1MBB);
7238 F->insert(It, loop2MBB);
7239 F->insert(It, midMBB);
7240 F->insert(It, exitMBB);
7241 exitMBB->splice(exitMBB->begin(), BB,
7242 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7243 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7245 MachineRegisterInfo &RegInfo = F->getRegInfo();
7246 const TargetRegisterClass *RC =
7247 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
7248 (const TargetRegisterClass *) &PPC::GPRCRegClass;
7249 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7250 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7251 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7252 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7253 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7254 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7255 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7256 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7257 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7258 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7259 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7260 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7261 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7263 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7264 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7267 // fallthrough --> loopMBB
7268 BB->addSuccessor(loop1MBB);
7270 // The 4-byte load must be aligned, while a char or short may be
7271 // anywhere in the word. Hence all this nasty bookkeeping code.
7272 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7273 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7274 // xori shift, shift1, 24 [16]
7275 // rlwinm ptr, ptr1, 0, 0, 29
7276 // slw newval2, newval, shift
7277 // slw oldval2, oldval,shift
7278 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7279 // slw mask, mask2, shift
7280 // and newval3, newval2, mask
7281 // and oldval3, oldval2, mask
7283 // lwarx tmpDest, ptr
7284 // and tmp, tmpDest, mask
7285 // cmpw tmp, oldval3
7288 // andc tmp2, tmpDest, mask
7289 // or tmp4, tmp2, newval3
7294 // stwcx. tmpDest, ptr
7296 // srw dest, tmpDest, shift
7297 if (ptrA != ZeroReg) {
7298 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7299 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7300 .addReg(ptrA).addReg(ptrB);
7304 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7305 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7306 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7307 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7309 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7310 .addReg(Ptr1Reg).addImm(0).addImm(61);
7312 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7313 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7314 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7315 .addReg(newval).addReg(ShiftReg);
7316 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7317 .addReg(oldval).addReg(ShiftReg);
7319 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7321 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7322 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7323 .addReg(Mask3Reg).addImm(65535);
7325 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7326 .addReg(Mask2Reg).addReg(ShiftReg);
7327 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7328 .addReg(NewVal2Reg).addReg(MaskReg);
7329 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7330 .addReg(OldVal2Reg).addReg(MaskReg);
7333 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7334 .addReg(ZeroReg).addReg(PtrReg);
7335 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7336 .addReg(TmpDestReg).addReg(MaskReg);
7337 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7338 .addReg(TmpReg).addReg(OldVal3Reg);
7339 BuildMI(BB, dl, TII->get(PPC::BCC))
7340 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7341 BB->addSuccessor(loop2MBB);
7342 BB->addSuccessor(midMBB);
7345 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7346 .addReg(TmpDestReg).addReg(MaskReg);
7347 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7348 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7349 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7350 .addReg(ZeroReg).addReg(PtrReg);
7351 BuildMI(BB, dl, TII->get(PPC::BCC))
7352 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7353 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7354 BB->addSuccessor(loop1MBB);
7355 BB->addSuccessor(exitMBB);
7358 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7359 .addReg(ZeroReg).addReg(PtrReg);
7360 BB->addSuccessor(exitMBB);
7365 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7367 } else if (MI->getOpcode() == PPC::FADDrtz) {
7368 // This pseudo performs an FADD with rounding mode temporarily forced
7369 // to round-to-zero. We emit this via custom inserter since the FPSCR
7370 // is not modeled at the SelectionDAG level.
7371 unsigned Dest = MI->getOperand(0).getReg();
7372 unsigned Src1 = MI->getOperand(1).getReg();
7373 unsigned Src2 = MI->getOperand(2).getReg();
7374 DebugLoc dl = MI->getDebugLoc();
7376 MachineRegisterInfo &RegInfo = F->getRegInfo();
7377 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7379 // Save FPSCR value.
7380 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7382 // Set rounding mode to round-to-zero.
7383 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7384 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7386 // Perform addition.
7387 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7389 // Restore FPSCR value.
7390 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7391 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7392 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7393 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7394 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7395 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7396 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7397 PPC::ANDIo8 : PPC::ANDIo;
7398 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7399 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7401 MachineRegisterInfo &RegInfo = F->getRegInfo();
7402 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7403 &PPC::GPRCRegClass :
7404 &PPC::G8RCRegClass);
7406 DebugLoc dl = MI->getDebugLoc();
7407 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7408 .addReg(MI->getOperand(1).getReg()).addImm(1);
7409 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7410 MI->getOperand(0).getReg())
7411 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7413 llvm_unreachable("Unexpected instr type to insert");
7416 MI->eraseFromParent(); // The pseudo instruction is gone now.
7420 //===----------------------------------------------------------------------===//
7421 // Target Optimization Hooks
7422 //===----------------------------------------------------------------------===//
7424 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7425 DAGCombinerInfo &DCI) const {
7426 if (DCI.isAfterLegalizeVectorOps())
7429 EVT VT = Op.getValueType();
7431 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7432 (VT == MVT::f64 && Subtarget.hasFRE()) ||
7433 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7434 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7436 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7437 // For the reciprocal, we need to find the zero of the function:
7438 // F(X) = A X - 1 [which has a zero at X = 1/A]
7440 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7441 // does not require additional intermediate precision]
7443 // Convergence is quadratic, so we essentially double the number of digits
7444 // correct after every iteration. The minimum architected relative
7445 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7446 // 23 digits and double has 52 digits.
7447 int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7448 if (VT.getScalarType() == MVT::f64)
7451 SelectionDAG &DAG = DCI.DAG;
7455 DAG.getConstantFP(1.0, VT.getScalarType());
7456 if (VT.isVector()) {
7457 assert(VT.getVectorNumElements() == 4 &&
7458 "Unknown vector type");
7459 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7460 FPOne, FPOne, FPOne, FPOne);
7463 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7464 DCI.AddToWorklist(Est.getNode());
7466 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7467 for (int i = 0; i < Iterations; ++i) {
7468 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7469 DCI.AddToWorklist(NewEst.getNode());
7471 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7472 DCI.AddToWorklist(NewEst.getNode());
7474 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7475 DCI.AddToWorklist(NewEst.getNode());
7477 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7478 DCI.AddToWorklist(Est.getNode());
7487 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7488 DAGCombinerInfo &DCI) const {
7489 if (DCI.isAfterLegalizeVectorOps())
7492 EVT VT = Op.getValueType();
7494 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7495 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7496 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7497 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7499 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7500 // For the reciprocal sqrt, we need to find the zero of the function:
7501 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7503 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7504 // As a result, we precompute A/2 prior to the iteration loop.
7506 // Convergence is quadratic, so we essentially double the number of digits
7507 // correct after every iteration. The minimum architected relative
7508 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7509 // 23 digits and double has 52 digits.
7510 int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7511 if (VT.getScalarType() == MVT::f64)
7514 SelectionDAG &DAG = DCI.DAG;
7517 SDValue FPThreeHalves =
7518 DAG.getConstantFP(1.5, VT.getScalarType());
7519 if (VT.isVector()) {
7520 assert(VT.getVectorNumElements() == 4 &&
7521 "Unknown vector type");
7522 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7523 FPThreeHalves, FPThreeHalves,
7524 FPThreeHalves, FPThreeHalves);
7527 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7528 DCI.AddToWorklist(Est.getNode());
7530 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7531 // this entire sequence requires only one FP constant.
7532 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7533 DCI.AddToWorklist(HalfArg.getNode());
7535 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7536 DCI.AddToWorklist(HalfArg.getNode());
7538 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7539 for (int i = 0; i < Iterations; ++i) {
7540 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7541 DCI.AddToWorklist(NewEst.getNode());
7543 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7544 DCI.AddToWorklist(NewEst.getNode());
7546 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7547 DCI.AddToWorklist(NewEst.getNode());
7549 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7550 DCI.AddToWorklist(Est.getNode());
7559 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7560 unsigned Bytes, int Dist,
7561 SelectionDAG &DAG) {
7562 if (VT.getSizeInBits() / 8 != Bytes)
7565 SDValue BaseLoc = Base->getBasePtr();
7566 if (Loc.getOpcode() == ISD::FrameIndex) {
7567 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7569 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7570 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7571 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7572 int FS = MFI->getObjectSize(FI);
7573 int BFS = MFI->getObjectSize(BFI);
7574 if (FS != BFS || FS != (int)Bytes) return false;
7575 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7579 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7580 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7583 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7584 const GlobalValue *GV1 = nullptr;
7585 const GlobalValue *GV2 = nullptr;
7586 int64_t Offset1 = 0;
7587 int64_t Offset2 = 0;
7588 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7589 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7590 if (isGA1 && isGA2 && GV1 == GV2)
7591 return Offset1 == (Offset2 + Dist*Bytes);
7595 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7596 // not enforce equality of the chain operands.
7597 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7598 unsigned Bytes, int Dist,
7599 SelectionDAG &DAG) {
7600 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7601 EVT VT = LS->getMemoryVT();
7602 SDValue Loc = LS->getBasePtr();
7603 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7606 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7608 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7609 default: return false;
7610 case Intrinsic::ppc_altivec_lvx:
7611 case Intrinsic::ppc_altivec_lvxl:
7614 case Intrinsic::ppc_altivec_lvebx:
7617 case Intrinsic::ppc_altivec_lvehx:
7620 case Intrinsic::ppc_altivec_lvewx:
7625 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7628 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7630 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7631 default: return false;
7632 case Intrinsic::ppc_altivec_stvx:
7633 case Intrinsic::ppc_altivec_stvxl:
7636 case Intrinsic::ppc_altivec_stvebx:
7639 case Intrinsic::ppc_altivec_stvehx:
7642 case Intrinsic::ppc_altivec_stvewx:
7647 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7653 // Return true is there is a nearyby consecutive load to the one provided
7654 // (regardless of alignment). We search up and down the chain, looking though
7655 // token factors and other loads (but nothing else). As a result, a true result
7656 // indicates that it is safe to create a new consecutive load adjacent to the
7658 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7659 SDValue Chain = LD->getChain();
7660 EVT VT = LD->getMemoryVT();
7662 SmallSet<SDNode *, 16> LoadRoots;
7663 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7664 SmallSet<SDNode *, 16> Visited;
7666 // First, search up the chain, branching to follow all token-factor operands.
7667 // If we find a consecutive load, then we're done, otherwise, record all
7668 // nodes just above the top-level loads and token factors.
7669 while (!Queue.empty()) {
7670 SDNode *ChainNext = Queue.pop_back_val();
7671 if (!Visited.insert(ChainNext))
7674 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7675 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7678 if (!Visited.count(ChainLD->getChain().getNode()))
7679 Queue.push_back(ChainLD->getChain().getNode());
7680 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7681 for (const SDUse &O : ChainNext->ops())
7682 if (!Visited.count(O.getNode()))
7683 Queue.push_back(O.getNode());
7685 LoadRoots.insert(ChainNext);
7688 // Second, search down the chain, starting from the top-level nodes recorded
7689 // in the first phase. These top-level nodes are the nodes just above all
7690 // loads and token factors. Starting with their uses, recursively look though
7691 // all loads (just the chain uses) and token factors to find a consecutive
7696 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7697 IE = LoadRoots.end(); I != IE; ++I) {
7698 Queue.push_back(*I);
7700 while (!Queue.empty()) {
7701 SDNode *LoadRoot = Queue.pop_back_val();
7702 if (!Visited.insert(LoadRoot))
7705 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7706 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7709 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7710 UE = LoadRoot->use_end(); UI != UE; ++UI)
7711 if (((isa<MemSDNode>(*UI) &&
7712 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7713 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7714 Queue.push_back(*UI);
7721 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7722 DAGCombinerInfo &DCI) const {
7723 SelectionDAG &DAG = DCI.DAG;
7726 assert(Subtarget.useCRBits() &&
7727 "Expecting to be tracking CR bits");
7728 // If we're tracking CR bits, we need to be careful that we don't have:
7729 // trunc(binary-ops(zext(x), zext(y)))
7731 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7732 // such that we're unnecessarily moving things into GPRs when it would be
7733 // better to keep them in CR bits.
7735 // Note that trunc here can be an actual i1 trunc, or can be the effective
7736 // truncation that comes from a setcc or select_cc.
7737 if (N->getOpcode() == ISD::TRUNCATE &&
7738 N->getValueType(0) != MVT::i1)
7741 if (N->getOperand(0).getValueType() != MVT::i32 &&
7742 N->getOperand(0).getValueType() != MVT::i64)
7745 if (N->getOpcode() == ISD::SETCC ||
7746 N->getOpcode() == ISD::SELECT_CC) {
7747 // If we're looking at a comparison, then we need to make sure that the
7748 // high bits (all except for the first) don't matter the result.
7750 cast<CondCodeSDNode>(N->getOperand(
7751 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7752 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7754 if (ISD::isSignedIntSetCC(CC)) {
7755 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7756 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7758 } else if (ISD::isUnsignedIntSetCC(CC)) {
7759 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7760 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7761 !DAG.MaskedValueIsZero(N->getOperand(1),
7762 APInt::getHighBitsSet(OpBits, OpBits-1)))
7765 // This is neither a signed nor an unsigned comparison, just make sure
7766 // that the high bits are equal.
7767 APInt Op1Zero, Op1One;
7768 APInt Op2Zero, Op2One;
7769 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7770 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7772 // We don't really care about what is known about the first bit (if
7773 // anything), so clear it in all masks prior to comparing them.
7774 Op1Zero.clearBit(0); Op1One.clearBit(0);
7775 Op2Zero.clearBit(0); Op2One.clearBit(0);
7777 if (Op1Zero != Op2Zero || Op1One != Op2One)
7782 // We now know that the higher-order bits are irrelevant, we just need to
7783 // make sure that all of the intermediate operations are bit operations, and
7784 // all inputs are extensions.
7785 if (N->getOperand(0).getOpcode() != ISD::AND &&
7786 N->getOperand(0).getOpcode() != ISD::OR &&
7787 N->getOperand(0).getOpcode() != ISD::XOR &&
7788 N->getOperand(0).getOpcode() != ISD::SELECT &&
7789 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7790 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7791 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7792 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7793 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7796 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7797 N->getOperand(1).getOpcode() != ISD::AND &&
7798 N->getOperand(1).getOpcode() != ISD::OR &&
7799 N->getOperand(1).getOpcode() != ISD::XOR &&
7800 N->getOperand(1).getOpcode() != ISD::SELECT &&
7801 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7802 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7803 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7804 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7805 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7808 SmallVector<SDValue, 4> Inputs;
7809 SmallVector<SDValue, 8> BinOps, PromOps;
7810 SmallPtrSet<SDNode *, 16> Visited;
7812 for (unsigned i = 0; i < 2; ++i) {
7813 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7814 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7815 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7816 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7817 isa<ConstantSDNode>(N->getOperand(i)))
7818 Inputs.push_back(N->getOperand(i));
7820 BinOps.push_back(N->getOperand(i));
7822 if (N->getOpcode() == ISD::TRUNCATE)
7826 // Visit all inputs, collect all binary operations (and, or, xor and
7827 // select) that are all fed by extensions.
7828 while (!BinOps.empty()) {
7829 SDValue BinOp = BinOps.back();
7832 if (!Visited.insert(BinOp.getNode()))
7835 PromOps.push_back(BinOp);
7837 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7838 // The condition of the select is not promoted.
7839 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7841 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7844 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7845 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7846 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7847 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7848 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7849 Inputs.push_back(BinOp.getOperand(i));
7850 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7851 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7852 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7853 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7854 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7855 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7856 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7857 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7858 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7859 BinOps.push_back(BinOp.getOperand(i));
7861 // We have an input that is not an extension or another binary
7862 // operation; we'll abort this transformation.
7868 // Make sure that this is a self-contained cluster of operations (which
7869 // is not quite the same thing as saying that everything has only one
7871 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7872 if (isa<ConstantSDNode>(Inputs[i]))
7875 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7876 UE = Inputs[i].getNode()->use_end();
7879 if (User != N && !Visited.count(User))
7882 // Make sure that we're not going to promote the non-output-value
7883 // operand(s) or SELECT or SELECT_CC.
7884 // FIXME: Although we could sometimes handle this, and it does occur in
7885 // practice that one of the condition inputs to the select is also one of
7886 // the outputs, we currently can't deal with this.
7887 if (User->getOpcode() == ISD::SELECT) {
7888 if (User->getOperand(0) == Inputs[i])
7890 } else if (User->getOpcode() == ISD::SELECT_CC) {
7891 if (User->getOperand(0) == Inputs[i] ||
7892 User->getOperand(1) == Inputs[i])
7898 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7899 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7900 UE = PromOps[i].getNode()->use_end();
7903 if (User != N && !Visited.count(User))
7906 // Make sure that we're not going to promote the non-output-value
7907 // operand(s) or SELECT or SELECT_CC.
7908 // FIXME: Although we could sometimes handle this, and it does occur in
7909 // practice that one of the condition inputs to the select is also one of
7910 // the outputs, we currently can't deal with this.
7911 if (User->getOpcode() == ISD::SELECT) {
7912 if (User->getOperand(0) == PromOps[i])
7914 } else if (User->getOpcode() == ISD::SELECT_CC) {
7915 if (User->getOperand(0) == PromOps[i] ||
7916 User->getOperand(1) == PromOps[i])
7922 // Replace all inputs with the extension operand.
7923 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7924 // Constants may have users outside the cluster of to-be-promoted nodes,
7925 // and so we need to replace those as we do the promotions.
7926 if (isa<ConstantSDNode>(Inputs[i]))
7929 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7932 // Replace all operations (these are all the same, but have a different
7933 // (i1) return type). DAG.getNode will validate that the types of
7934 // a binary operator match, so go through the list in reverse so that
7935 // we've likely promoted both operands first. Any intermediate truncations or
7936 // extensions disappear.
7937 while (!PromOps.empty()) {
7938 SDValue PromOp = PromOps.back();
7941 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7942 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7943 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7944 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7945 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7946 PromOp.getOperand(0).getValueType() != MVT::i1) {
7947 // The operand is not yet ready (see comment below).
7948 PromOps.insert(PromOps.begin(), PromOp);
7952 SDValue RepValue = PromOp.getOperand(0);
7953 if (isa<ConstantSDNode>(RepValue))
7954 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7956 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7961 switch (PromOp.getOpcode()) {
7962 default: C = 0; break;
7963 case ISD::SELECT: C = 1; break;
7964 case ISD::SELECT_CC: C = 2; break;
7967 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7968 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7969 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7970 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7971 // The to-be-promoted operands of this node have not yet been
7972 // promoted (this should be rare because we're going through the
7973 // list backward, but if one of the operands has several users in
7974 // this cluster of to-be-promoted nodes, it is possible).
7975 PromOps.insert(PromOps.begin(), PromOp);
7979 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7980 PromOp.getNode()->op_end());
7982 // If there are any constant inputs, make sure they're replaced now.
7983 for (unsigned i = 0; i < 2; ++i)
7984 if (isa<ConstantSDNode>(Ops[C+i]))
7985 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7987 DAG.ReplaceAllUsesOfValueWith(PromOp,
7988 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7991 // Now we're left with the initial truncation itself.
7992 if (N->getOpcode() == ISD::TRUNCATE)
7993 return N->getOperand(0);
7995 // Otherwise, this is a comparison. The operands to be compared have just
7996 // changed type (to i1), but everything else is the same.
7997 return SDValue(N, 0);
8000 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8001 DAGCombinerInfo &DCI) const {
8002 SelectionDAG &DAG = DCI.DAG;
8005 // If we're tracking CR bits, we need to be careful that we don't have:
8006 // zext(binary-ops(trunc(x), trunc(y)))
8008 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8009 // such that we're unnecessarily moving things into CR bits that can more
8010 // efficiently stay in GPRs. Note that if we're not certain that the high
8011 // bits are set as required by the final extension, we still may need to do
8012 // some masking to get the proper behavior.
8014 // This same functionality is important on PPC64 when dealing with
8015 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8016 // the return values of functions. Because it is so similar, it is handled
8019 if (N->getValueType(0) != MVT::i32 &&
8020 N->getValueType(0) != MVT::i64)
8023 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8024 Subtarget.useCRBits()) ||
8025 (N->getOperand(0).getValueType() == MVT::i32 &&
8026 Subtarget.isPPC64())))
8029 if (N->getOperand(0).getOpcode() != ISD::AND &&
8030 N->getOperand(0).getOpcode() != ISD::OR &&
8031 N->getOperand(0).getOpcode() != ISD::XOR &&
8032 N->getOperand(0).getOpcode() != ISD::SELECT &&
8033 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8036 SmallVector<SDValue, 4> Inputs;
8037 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8038 SmallPtrSet<SDNode *, 16> Visited;
8040 // Visit all inputs, collect all binary operations (and, or, xor and
8041 // select) that are all fed by truncations.
8042 while (!BinOps.empty()) {
8043 SDValue BinOp = BinOps.back();
8046 if (!Visited.insert(BinOp.getNode()))
8049 PromOps.push_back(BinOp);
8051 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8052 // The condition of the select is not promoted.
8053 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8055 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8058 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8059 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8060 Inputs.push_back(BinOp.getOperand(i));
8061 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8062 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8063 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8064 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8065 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8066 BinOps.push_back(BinOp.getOperand(i));
8068 // We have an input that is not a truncation or another binary
8069 // operation; we'll abort this transformation.
8075 // Make sure that this is a self-contained cluster of operations (which
8076 // is not quite the same thing as saying that everything has only one
8078 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8079 if (isa<ConstantSDNode>(Inputs[i]))
8082 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8083 UE = Inputs[i].getNode()->use_end();
8086 if (User != N && !Visited.count(User))
8089 // Make sure that we're not going to promote the non-output-value
8090 // operand(s) or SELECT or SELECT_CC.
8091 // FIXME: Although we could sometimes handle this, and it does occur in
8092 // practice that one of the condition inputs to the select is also one of
8093 // the outputs, we currently can't deal with this.
8094 if (User->getOpcode() == ISD::SELECT) {
8095 if (User->getOperand(0) == Inputs[i])
8097 } else if (User->getOpcode() == ISD::SELECT_CC) {
8098 if (User->getOperand(0) == Inputs[i] ||
8099 User->getOperand(1) == Inputs[i])
8105 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8106 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8107 UE = PromOps[i].getNode()->use_end();
8110 if (User != N && !Visited.count(User))
8113 // Make sure that we're not going to promote the non-output-value
8114 // operand(s) or SELECT or SELECT_CC.
8115 // FIXME: Although we could sometimes handle this, and it does occur in
8116 // practice that one of the condition inputs to the select is also one of
8117 // the outputs, we currently can't deal with this.
8118 if (User->getOpcode() == ISD::SELECT) {
8119 if (User->getOperand(0) == PromOps[i])
8121 } else if (User->getOpcode() == ISD::SELECT_CC) {
8122 if (User->getOperand(0) == PromOps[i] ||
8123 User->getOperand(1) == PromOps[i])
8129 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8130 bool ReallyNeedsExt = false;
8131 if (N->getOpcode() != ISD::ANY_EXTEND) {
8132 // If all of the inputs are not already sign/zero extended, then
8133 // we'll still need to do that at the end.
8134 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8135 if (isa<ConstantSDNode>(Inputs[i]))
8139 Inputs[i].getOperand(0).getValueSizeInBits();
8140 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8142 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8143 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8144 APInt::getHighBitsSet(OpBits,
8145 OpBits-PromBits))) ||
8146 (N->getOpcode() == ISD::SIGN_EXTEND &&
8147 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8148 (OpBits-(PromBits-1)))) {
8149 ReallyNeedsExt = true;
8155 // Replace all inputs, either with the truncation operand, or a
8156 // truncation or extension to the final output type.
8157 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8158 // Constant inputs need to be replaced with the to-be-promoted nodes that
8159 // use them because they might have users outside of the cluster of
8161 if (isa<ConstantSDNode>(Inputs[i]))
8164 SDValue InSrc = Inputs[i].getOperand(0);
8165 if (Inputs[i].getValueType() == N->getValueType(0))
8166 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8167 else if (N->getOpcode() == ISD::SIGN_EXTEND)
8168 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8169 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8170 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8171 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8172 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8174 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8175 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8178 // Replace all operations (these are all the same, but have a different
8179 // (promoted) return type). DAG.getNode will validate that the types of
8180 // a binary operator match, so go through the list in reverse so that
8181 // we've likely promoted both operands first.
8182 while (!PromOps.empty()) {
8183 SDValue PromOp = PromOps.back();
8187 switch (PromOp.getOpcode()) {
8188 default: C = 0; break;
8189 case ISD::SELECT: C = 1; break;
8190 case ISD::SELECT_CC: C = 2; break;
8193 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8194 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8195 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8196 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8197 // The to-be-promoted operands of this node have not yet been
8198 // promoted (this should be rare because we're going through the
8199 // list backward, but if one of the operands has several users in
8200 // this cluster of to-be-promoted nodes, it is possible).
8201 PromOps.insert(PromOps.begin(), PromOp);
8205 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8206 PromOp.getNode()->op_end());
8208 // If this node has constant inputs, then they'll need to be promoted here.
8209 for (unsigned i = 0; i < 2; ++i) {
8210 if (!isa<ConstantSDNode>(Ops[C+i]))
8212 if (Ops[C+i].getValueType() == N->getValueType(0))
8215 if (N->getOpcode() == ISD::SIGN_EXTEND)
8216 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8217 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8218 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8220 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8223 DAG.ReplaceAllUsesOfValueWith(PromOp,
8224 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8227 // Now we're left with the initial extension itself.
8228 if (!ReallyNeedsExt)
8229 return N->getOperand(0);
8231 // To zero extend, just mask off everything except for the first bit (in the
8233 if (N->getOpcode() == ISD::ZERO_EXTEND)
8234 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8235 DAG.getConstant(APInt::getLowBitsSet(
8236 N->getValueSizeInBits(0), PromBits),
8237 N->getValueType(0)));
8239 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8240 "Invalid extension type");
8241 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8243 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8244 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
8245 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8246 N->getOperand(0), ShiftCst), ShiftCst);
8249 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8250 DAGCombinerInfo &DCI) const {
8251 const TargetMachine &TM = getTargetMachine();
8252 SelectionDAG &DAG = DCI.DAG;
8254 switch (N->getOpcode()) {
8257 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8258 if (C->isNullValue()) // 0 << V -> 0.
8259 return N->getOperand(0);
8263 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8264 if (C->isNullValue()) // 0 >>u V -> 0.
8265 return N->getOperand(0);
8269 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8270 if (C->isNullValue() || // 0 >>s V -> 0.
8271 C->isAllOnesValue()) // -1 >>s V -> -1.
8272 return N->getOperand(0);
8275 case ISD::SIGN_EXTEND:
8276 case ISD::ZERO_EXTEND:
8277 case ISD::ANY_EXTEND:
8278 return DAGCombineExtBoolTrunc(N, DCI);
8281 case ISD::SELECT_CC:
8282 return DAGCombineTruncBoolExt(N, DCI);
8284 assert(TM.Options.UnsafeFPMath &&
8285 "Reciprocal estimates require UnsafeFPMath");
8287 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
8289 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
8291 DCI.AddToWorklist(RV.getNode());
8292 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8293 N->getOperand(0), RV);
8295 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
8296 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8298 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8301 DCI.AddToWorklist(RV.getNode());
8302 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
8303 N->getValueType(0), RV);
8304 DCI.AddToWorklist(RV.getNode());
8305 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8306 N->getOperand(0), RV);
8308 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
8309 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8311 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8314 DCI.AddToWorklist(RV.getNode());
8315 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
8316 N->getValueType(0), RV,
8317 N->getOperand(1).getOperand(1));
8318 DCI.AddToWorklist(RV.getNode());
8319 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8320 N->getOperand(0), RV);
8324 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
8326 DCI.AddToWorklist(RV.getNode());
8327 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8328 N->getOperand(0), RV);
8334 assert(TM.Options.UnsafeFPMath &&
8335 "Reciprocal estimates require UnsafeFPMath");
8337 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
8339 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
8341 DCI.AddToWorklist(RV.getNode());
8342 RV = DAGCombineFastRecip(RV, DCI);
8344 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
8345 // this case and force the answer to 0.
8347 EVT VT = RV.getValueType();
8349 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
8350 if (VT.isVector()) {
8351 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
8352 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
8356 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
8357 N->getOperand(0), Zero, ISD::SETEQ);
8358 DCI.AddToWorklist(ZeroCmp.getNode());
8359 DCI.AddToWorklist(RV.getNode());
8361 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
8369 case ISD::SINT_TO_FP:
8370 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8371 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8372 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8373 // We allow the src/dst to be either f32/f64, but the intermediate
8374 // type must be i64.
8375 if (N->getOperand(0).getValueType() == MVT::i64 &&
8376 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8377 SDValue Val = N->getOperand(0).getOperand(0);
8378 if (Val.getValueType() == MVT::f32) {
8379 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8380 DCI.AddToWorklist(Val.getNode());
8383 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8384 DCI.AddToWorklist(Val.getNode());
8385 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8386 DCI.AddToWorklist(Val.getNode());
8387 if (N->getValueType(0) == MVT::f32) {
8388 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8389 DAG.getIntPtrConstant(0));
8390 DCI.AddToWorklist(Val.getNode());
8393 } else if (N->getOperand(0).getValueType() == MVT::i32) {
8394 // If the intermediate type is i32, we can avoid the load/store here
8401 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8402 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8403 !cast<StoreSDNode>(N)->isTruncatingStore() &&
8404 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8405 N->getOperand(1).getValueType() == MVT::i32 &&
8406 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8407 SDValue Val = N->getOperand(1).getOperand(0);
8408 if (Val.getValueType() == MVT::f32) {
8409 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8410 DCI.AddToWorklist(Val.getNode());
8412 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8413 DCI.AddToWorklist(Val.getNode());
8416 N->getOperand(0), Val, N->getOperand(2),
8417 DAG.getValueType(N->getOperand(1).getValueType())
8420 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8421 DAG.getVTList(MVT::Other), Ops,
8422 cast<StoreSDNode>(N)->getMemoryVT(),
8423 cast<StoreSDNode>(N)->getMemOperand());
8424 DCI.AddToWorklist(Val.getNode());
8428 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8429 if (cast<StoreSDNode>(N)->isUnindexed() &&
8430 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8431 N->getOperand(1).getNode()->hasOneUse() &&
8432 (N->getOperand(1).getValueType() == MVT::i32 ||
8433 N->getOperand(1).getValueType() == MVT::i16 ||
8434 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8435 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8436 N->getOperand(1).getValueType() == MVT::i64))) {
8437 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8438 // Do an any-extend to 32-bits if this is a half-word input.
8439 if (BSwapOp.getValueType() == MVT::i16)
8440 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8443 N->getOperand(0), BSwapOp, N->getOperand(2),
8444 DAG.getValueType(N->getOperand(1).getValueType())
8447 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8448 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8449 cast<StoreSDNode>(N)->getMemOperand());
8453 LoadSDNode *LD = cast<LoadSDNode>(N);
8454 EVT VT = LD->getValueType(0);
8455 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8456 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8457 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8458 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8459 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8460 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8461 LD->getAlignment() < ABIAlignment) {
8462 // This is a type-legal unaligned Altivec load.
8463 SDValue Chain = LD->getChain();
8464 SDValue Ptr = LD->getBasePtr();
8465 bool isLittleEndian = Subtarget.isLittleEndian();
8467 // This implements the loading of unaligned vectors as described in
8468 // the venerable Apple Velocity Engine overview. Specifically:
8469 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8470 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8472 // The general idea is to expand a sequence of one or more unaligned
8473 // loads into an alignment-based permutation-control instruction (lvsl
8474 // or lvsr), a series of regular vector loads (which always truncate
8475 // their input address to an aligned address), and a series of
8476 // permutations. The results of these permutations are the requested
8477 // loaded values. The trick is that the last "extra" load is not taken
8478 // from the address you might suspect (sizeof(vector) bytes after the
8479 // last requested load), but rather sizeof(vector) - 1 bytes after the
8480 // last requested vector. The point of this is to avoid a page fault if
8481 // the base address happened to be aligned. This works because if the
8482 // base address is aligned, then adding less than a full vector length
8483 // will cause the last vector in the sequence to be (re)loaded.
8484 // Otherwise, the next vector will be fetched as you might suspect was
8487 // We might be able to reuse the permutation generation from
8488 // a different base address offset from this one by an aligned amount.
8489 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8490 // optimization later.
8491 Intrinsic::ID Intr = (isLittleEndian ?
8492 Intrinsic::ppc_altivec_lvsr :
8493 Intrinsic::ppc_altivec_lvsl);
8494 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8496 // Create the new MMO for the new base load. It is like the original MMO,
8497 // but represents an area in memory almost twice the vector size centered
8498 // on the original address. If the address is unaligned, we might start
8499 // reading up to (sizeof(vector)-1) bytes below the address of the
8500 // original unaligned load.
8501 MachineFunction &MF = DAG.getMachineFunction();
8502 MachineMemOperand *BaseMMO =
8503 MF.getMachineMemOperand(LD->getMemOperand(),
8504 -LD->getMemoryVT().getStoreSize()+1,
8505 2*LD->getMemoryVT().getStoreSize()-1);
8507 // Create the new base load.
8508 SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8510 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8512 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8513 DAG.getVTList(MVT::v4i32, MVT::Other),
8514 BaseLoadOps, MVT::v4i32, BaseMMO);
8516 // Note that the value of IncOffset (which is provided to the next
8517 // load's pointer info offset value, and thus used to calculate the
8518 // alignment), and the value of IncValue (which is actually used to
8519 // increment the pointer value) are different! This is because we
8520 // require the next load to appear to be aligned, even though it
8521 // is actually offset from the base pointer by a lesser amount.
8522 int IncOffset = VT.getSizeInBits() / 8;
8523 int IncValue = IncOffset;
8525 // Walk (both up and down) the chain looking for another load at the real
8526 // (aligned) offset (the alignment of the other load does not matter in
8527 // this case). If found, then do not use the offset reduction trick, as
8528 // that will prevent the loads from being later combined (as they would
8529 // otherwise be duplicates).
8530 if (!findConsecutiveLoad(LD, DAG))
8533 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8534 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8536 MachineMemOperand *ExtraMMO =
8537 MF.getMachineMemOperand(LD->getMemOperand(),
8538 1, 2*LD->getMemoryVT().getStoreSize()-1);
8539 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8541 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8542 DAG.getVTList(MVT::v4i32, MVT::Other),
8543 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8545 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8546 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8548 // Because vperm has a big-endian bias, we must reverse the order
8549 // of the input vectors and complement the permute control vector
8550 // when generating little endian code. We have already handled the
8551 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8552 // and ExtraLoad here.
8555 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8556 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8558 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8559 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8561 if (VT != MVT::v4i32)
8562 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8564 // The output of the permutation is our loaded result, the TokenFactor is
8566 DCI.CombineTo(N, Perm, TF);
8567 return SDValue(N, 0);
8571 case ISD::INTRINSIC_WO_CHAIN: {
8572 bool isLittleEndian = Subtarget.isLittleEndian();
8573 Intrinsic::ID Intr = (isLittleEndian ?
8574 Intrinsic::ppc_altivec_lvsr :
8575 Intrinsic::ppc_altivec_lvsl);
8576 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8577 N->getOperand(1)->getOpcode() == ISD::ADD) {
8578 SDValue Add = N->getOperand(1);
8580 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8581 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8582 Add.getValueType().getScalarType().getSizeInBits()))) {
8583 SDNode *BasePtr = Add->getOperand(0).getNode();
8584 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8585 UE = BasePtr->use_end(); UI != UE; ++UI) {
8586 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8587 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8589 // We've found another LVSL/LVSR, and this address is an aligned
8590 // multiple of that one. The results will be the same, so use the
8591 // one we've just found instead.
8593 return SDValue(*UI, 0);
8602 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8603 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8604 N->getOperand(0).hasOneUse() &&
8605 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8606 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8607 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8608 N->getValueType(0) == MVT::i64))) {
8609 SDValue Load = N->getOperand(0);
8610 LoadSDNode *LD = cast<LoadSDNode>(Load);
8611 // Create the byte-swapping load.
8613 LD->getChain(), // Chain
8614 LD->getBasePtr(), // Ptr
8615 DAG.getValueType(N->getValueType(0)) // VT
8618 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8619 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8620 MVT::i64 : MVT::i32, MVT::Other),
8621 Ops, LD->getMemoryVT(), LD->getMemOperand());
8623 // If this is an i16 load, insert the truncate.
8624 SDValue ResVal = BSLoad;
8625 if (N->getValueType(0) == MVT::i16)
8626 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8628 // First, combine the bswap away. This makes the value produced by the
8630 DCI.CombineTo(N, ResVal);
8632 // Next, combine the load away, we give it a bogus result value but a real
8633 // chain result. The result value is dead because the bswap is dead.
8634 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8636 // Return N so it doesn't get rechecked!
8637 return SDValue(N, 0);
8641 case PPCISD::VCMP: {
8642 // If a VCMPo node already exists with exactly the same operands as this
8643 // node, use its result instead of this node (VCMPo computes both a CR6 and
8644 // a normal output).
8646 if (!N->getOperand(0).hasOneUse() &&
8647 !N->getOperand(1).hasOneUse() &&
8648 !N->getOperand(2).hasOneUse()) {
8650 // Scan all of the users of the LHS, looking for VCMPo's that match.
8651 SDNode *VCMPoNode = nullptr;
8653 SDNode *LHSN = N->getOperand(0).getNode();
8654 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8656 if (UI->getOpcode() == PPCISD::VCMPo &&
8657 UI->getOperand(1) == N->getOperand(1) &&
8658 UI->getOperand(2) == N->getOperand(2) &&
8659 UI->getOperand(0) == N->getOperand(0)) {
8664 // If there is no VCMPo node, or if the flag value has a single use, don't
8666 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8669 // Look at the (necessarily single) use of the flag value. If it has a
8670 // chain, this transformation is more complex. Note that multiple things
8671 // could use the value result, which we should ignore.
8672 SDNode *FlagUser = nullptr;
8673 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8674 FlagUser == nullptr; ++UI) {
8675 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8677 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8678 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8685 // If the user is a MFOCRF instruction, we know this is safe.
8686 // Otherwise we give up for right now.
8687 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8688 return SDValue(VCMPoNode, 0);
8693 SDValue Cond = N->getOperand(1);
8694 SDValue Target = N->getOperand(2);
8696 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8697 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8698 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8700 // We now need to make the intrinsic dead (it cannot be instruction
8702 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8703 assert(Cond.getNode()->hasOneUse() &&
8704 "Counter decrement has more than one use");
8706 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8707 N->getOperand(0), Target);
8712 // If this is a branch on an altivec predicate comparison, lower this so
8713 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8714 // lowering is done pre-legalize, because the legalizer lowers the predicate
8715 // compare down to code that is difficult to reassemble.
8716 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8717 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8719 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8720 // value. If so, pass-through the AND to get to the intrinsic.
8721 if (LHS.getOpcode() == ISD::AND &&
8722 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8723 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8724 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8725 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8726 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8728 LHS = LHS.getOperand(0);
8730 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8731 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8732 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8733 isa<ConstantSDNode>(RHS)) {
8734 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8735 "Counter decrement comparison is not EQ or NE");
8737 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8738 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8739 (CC == ISD::SETNE && !Val);
8741 // We now need to make the intrinsic dead (it cannot be instruction
8743 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8744 assert(LHS.getNode()->hasOneUse() &&
8745 "Counter decrement has more than one use");
8747 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8748 N->getOperand(0), N->getOperand(4));
8754 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8755 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8756 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8757 assert(isDot && "Can't compare against a vector result!");
8759 // If this is a comparison against something other than 0/1, then we know
8760 // that the condition is never/always true.
8761 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8762 if (Val != 0 && Val != 1) {
8763 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8764 return N->getOperand(0);
8765 // Always !=, turn it into an unconditional branch.
8766 return DAG.getNode(ISD::BR, dl, MVT::Other,
8767 N->getOperand(0), N->getOperand(4));
8770 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8772 // Create the PPCISD altivec 'dot' comparison node.
8774 LHS.getOperand(2), // LHS of compare
8775 LHS.getOperand(3), // RHS of compare
8776 DAG.getConstant(CompareOpc, MVT::i32)
8778 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8779 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8781 // Unpack the result based on how the target uses it.
8782 PPC::Predicate CompOpc;
8783 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8784 default: // Can't happen, don't crash on invalid number though.
8785 case 0: // Branch on the value of the EQ bit of CR6.
8786 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8788 case 1: // Branch on the inverted value of the EQ bit of CR6.
8789 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8791 case 2: // Branch on the value of the LT bit of CR6.
8792 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8794 case 3: // Branch on the inverted value of the LT bit of CR6.
8795 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8799 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8800 DAG.getConstant(CompOpc, MVT::i32),
8801 DAG.getRegister(PPC::CR6, MVT::i32),
8802 N->getOperand(4), CompNode.getValue(1));
8811 //===----------------------------------------------------------------------===//
8812 // Inline Assembly Support
8813 //===----------------------------------------------------------------------===//
8815 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8818 const SelectionDAG &DAG,
8819 unsigned Depth) const {
8820 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8821 switch (Op.getOpcode()) {
8823 case PPCISD::LBRX: {
8824 // lhbrx is known to have the top bits cleared out.
8825 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8826 KnownZero = 0xFFFF0000;
8829 case ISD::INTRINSIC_WO_CHAIN: {
8830 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8832 case Intrinsic::ppc_altivec_vcmpbfp_p:
8833 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8834 case Intrinsic::ppc_altivec_vcmpequb_p:
8835 case Intrinsic::ppc_altivec_vcmpequh_p:
8836 case Intrinsic::ppc_altivec_vcmpequw_p:
8837 case Intrinsic::ppc_altivec_vcmpgefp_p:
8838 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8839 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8840 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8841 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8842 case Intrinsic::ppc_altivec_vcmpgtub_p:
8843 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8844 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8845 KnownZero = ~1U; // All bits but the low one are known to be zero.
8853 /// getConstraintType - Given a constraint, return the type of
8854 /// constraint it is for this target.
8855 PPCTargetLowering::ConstraintType
8856 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8857 if (Constraint.size() == 1) {
8858 switch (Constraint[0]) {
8865 return C_RegisterClass;
8867 // FIXME: While Z does indicate a memory constraint, it specifically
8868 // indicates an r+r address (used in conjunction with the 'y' modifier
8869 // in the replacement string). Currently, we're forcing the base
8870 // register to be r0 in the asm printer (which is interpreted as zero)
8871 // and forming the complete address in the second register. This is
8875 } else if (Constraint == "wc") { // individual CR bits.
8876 return C_RegisterClass;
8877 } else if (Constraint == "wa" || Constraint == "wd" ||
8878 Constraint == "wf" || Constraint == "ws") {
8879 return C_RegisterClass; // VSX registers.
8881 return TargetLowering::getConstraintType(Constraint);
8884 /// Examine constraint type and operand type and determine a weight value.
8885 /// This object must already have been set up with the operand type
8886 /// and the current alternative constraint selected.
8887 TargetLowering::ConstraintWeight
8888 PPCTargetLowering::getSingleConstraintMatchWeight(
8889 AsmOperandInfo &info, const char *constraint) const {
8890 ConstraintWeight weight = CW_Invalid;
8891 Value *CallOperandVal = info.CallOperandVal;
8892 // If we don't have a value, we can't do a match,
8893 // but allow it at the lowest weight.
8894 if (!CallOperandVal)
8896 Type *type = CallOperandVal->getType();
8898 // Look at the constraint type.
8899 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8900 return CW_Register; // an individual CR bit.
8901 else if ((StringRef(constraint) == "wa" ||
8902 StringRef(constraint) == "wd" ||
8903 StringRef(constraint) == "wf") &&
8906 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8909 switch (*constraint) {
8911 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8914 if (type->isIntegerTy())
8915 weight = CW_Register;
8918 if (type->isFloatTy())
8919 weight = CW_Register;
8922 if (type->isDoubleTy())
8923 weight = CW_Register;
8926 if (type->isVectorTy())
8927 weight = CW_Register;
8930 weight = CW_Register;
8939 std::pair<unsigned, const TargetRegisterClass*>
8940 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8942 if (Constraint.size() == 1) {
8943 // GCC RS6000 Constraint Letters
8944 switch (Constraint[0]) {
8946 if (VT == MVT::i64 && Subtarget.isPPC64())
8947 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8948 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8950 if (VT == MVT::i64 && Subtarget.isPPC64())
8951 return std::make_pair(0U, &PPC::G8RCRegClass);
8952 return std::make_pair(0U, &PPC::GPRCRegClass);
8954 if (VT == MVT::f32 || VT == MVT::i32)
8955 return std::make_pair(0U, &PPC::F4RCRegClass);
8956 if (VT == MVT::f64 || VT == MVT::i64)
8957 return std::make_pair(0U, &PPC::F8RCRegClass);
8960 return std::make_pair(0U, &PPC::VRRCRegClass);
8962 return std::make_pair(0U, &PPC::CRRCRegClass);
8964 } else if (Constraint == "wc") { // an individual CR bit.
8965 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8966 } else if (Constraint == "wa" || Constraint == "wd" ||
8967 Constraint == "wf") {
8968 return std::make_pair(0U, &PPC::VSRCRegClass);
8969 } else if (Constraint == "ws") {
8970 return std::make_pair(0U, &PPC::VSFRCRegClass);
8973 std::pair<unsigned, const TargetRegisterClass*> R =
8974 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8976 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8977 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8978 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8980 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8981 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8982 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
8983 PPC::GPRCRegClass.contains(R.first)) {
8984 const TargetRegisterInfo *TRI =
8985 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8986 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8987 PPC::sub_32, &PPC::G8RCRegClass),
8988 &PPC::G8RCRegClass);
8995 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8996 /// vector. If it is invalid, don't add anything to Ops.
8997 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8998 std::string &Constraint,
8999 std::vector<SDValue>&Ops,
9000 SelectionDAG &DAG) const {
9003 // Only support length 1 constraints.
9004 if (Constraint.length() > 1) return;
9006 char Letter = Constraint[0];
9017 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9018 if (!CST) return; // Must be an immediate to match.
9019 unsigned Value = CST->getZExtValue();
9021 default: llvm_unreachable("Unknown constraint letter!");
9022 case 'I': // "I" is a signed 16-bit constant.
9023 if ((short)Value == (int)Value)
9024 Result = DAG.getTargetConstant(Value, Op.getValueType());
9026 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
9027 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
9028 if ((short)Value == 0)
9029 Result = DAG.getTargetConstant(Value, Op.getValueType());
9031 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
9032 if ((Value >> 16) == 0)
9033 Result = DAG.getTargetConstant(Value, Op.getValueType());
9035 case 'M': // "M" is a constant that is greater than 31.
9037 Result = DAG.getTargetConstant(Value, Op.getValueType());
9039 case 'N': // "N" is a positive constant that is an exact power of two.
9040 if ((int)Value > 0 && isPowerOf2_32(Value))
9041 Result = DAG.getTargetConstant(Value, Op.getValueType());
9043 case 'O': // "O" is the constant zero.
9045 Result = DAG.getTargetConstant(Value, Op.getValueType());
9047 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
9048 if ((short)-Value == (int)-Value)
9049 Result = DAG.getTargetConstant(Value, Op.getValueType());
9056 if (Result.getNode()) {
9057 Ops.push_back(Result);
9061 // Handle standard constraint letters.
9062 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9065 // isLegalAddressingMode - Return true if the addressing mode represented
9066 // by AM is legal for this target, for a load/store of the specified type.
9067 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9069 // FIXME: PPC does not allow r+i addressing modes for vectors!
9071 // PPC allows a sign-extended 16-bit immediate field.
9072 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9075 // No global is ever allowed as a base.
9079 // PPC only support r+r,
9081 case 0: // "r+i" or just "i", depending on HasBaseReg.
9084 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
9086 // Otherwise we have r+r or r+i.
9089 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
9091 // Allow 2*r as r+r.
9094 // No other scales are supported.
9101 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9102 SelectionDAG &DAG) const {
9103 MachineFunction &MF = DAG.getMachineFunction();
9104 MachineFrameInfo *MFI = MF.getFrameInfo();
9105 MFI->setReturnAddressIsTaken(true);
9107 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9111 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9113 // Make sure the function does not optimize away the store of the RA to
9115 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9116 FuncInfo->setLRStoreRequired();
9117 bool isPPC64 = Subtarget.isPPC64();
9118 bool isDarwinABI = Subtarget.isDarwinABI();
9121 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9124 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9125 isPPC64? MVT::i64 : MVT::i32);
9126 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9127 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9129 MachinePointerInfo(), false, false, false, 0);
9132 // Just load the return address off the stack.
9133 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9134 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9135 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9138 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9139 SelectionDAG &DAG) const {
9141 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9143 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9144 bool isPPC64 = PtrVT == MVT::i64;
9146 MachineFunction &MF = DAG.getMachineFunction();
9147 MachineFrameInfo *MFI = MF.getFrameInfo();
9148 MFI->setFrameAddressIsTaken(true);
9150 // Naked functions never have a frame pointer, and so we use r1. For all
9151 // other functions, this decision must be delayed until during PEI.
9153 if (MF.getFunction()->getAttributes().hasAttribute(
9154 AttributeSet::FunctionIndex, Attribute::Naked))
9155 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9157 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9159 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9162 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9163 FrameAddr, MachinePointerInfo(), false, false,
9168 // FIXME? Maybe this could be a TableGen attribute on some registers and
9169 // this table could be generated automatically from RegInfo.
9170 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9172 bool isPPC64 = Subtarget.isPPC64();
9173 bool isDarwinABI = Subtarget.isDarwinABI();
9175 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9176 (!isPPC64 && VT != MVT::i32))
9177 report_fatal_error("Invalid register global variable type");
9179 bool is64Bit = isPPC64 && VT == MVT::i64;
9180 unsigned Reg = StringSwitch<unsigned>(RegName)
9181 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9182 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9183 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9184 (is64Bit ? PPC::X13 : PPC::R13))
9189 report_fatal_error("Invalid register name global variable");
9193 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9194 // The PowerPC target isn't yet aware of offsets.
9198 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9200 unsigned Intrinsic) const {
9202 switch (Intrinsic) {
9203 case Intrinsic::ppc_altivec_lvx:
9204 case Intrinsic::ppc_altivec_lvxl:
9205 case Intrinsic::ppc_altivec_lvebx:
9206 case Intrinsic::ppc_altivec_lvehx:
9207 case Intrinsic::ppc_altivec_lvewx: {
9209 switch (Intrinsic) {
9210 case Intrinsic::ppc_altivec_lvebx:
9213 case Intrinsic::ppc_altivec_lvehx:
9216 case Intrinsic::ppc_altivec_lvewx:
9224 Info.opc = ISD::INTRINSIC_W_CHAIN;
9226 Info.ptrVal = I.getArgOperand(0);
9227 Info.offset = -VT.getStoreSize()+1;
9228 Info.size = 2*VT.getStoreSize()-1;
9231 Info.readMem = true;
9232 Info.writeMem = false;
9235 case Intrinsic::ppc_altivec_stvx:
9236 case Intrinsic::ppc_altivec_stvxl:
9237 case Intrinsic::ppc_altivec_stvebx:
9238 case Intrinsic::ppc_altivec_stvehx:
9239 case Intrinsic::ppc_altivec_stvewx: {
9241 switch (Intrinsic) {
9242 case Intrinsic::ppc_altivec_stvebx:
9245 case Intrinsic::ppc_altivec_stvehx:
9248 case Intrinsic::ppc_altivec_stvewx:
9256 Info.opc = ISD::INTRINSIC_VOID;
9258 Info.ptrVal = I.getArgOperand(1);
9259 Info.offset = -VT.getStoreSize()+1;
9260 Info.size = 2*VT.getStoreSize()-1;
9263 Info.readMem = false;
9264 Info.writeMem = true;
9274 /// getOptimalMemOpType - Returns the target specific optimal type for load
9275 /// and store operations as a result of memset, memcpy, and memmove
9276 /// lowering. If DstAlign is zero that means it's safe to destination
9277 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9278 /// means there isn't a need to check it against alignment requirement,
9279 /// probably because the source does not need to be loaded. If 'IsMemset' is
9280 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9281 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9282 /// source is constant so it does not need to be loaded.
9283 /// It returns EVT::Other if the type should be determined using generic
9284 /// target-independent logic.
9285 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9286 unsigned DstAlign, unsigned SrcAlign,
9287 bool IsMemset, bool ZeroMemset,
9289 MachineFunction &MF) const {
9290 if (Subtarget.isPPC64()) {
9297 /// \brief Returns true if it is beneficial to convert a load of a constant
9298 /// to just the constant itself.
9299 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9301 assert(Ty->isIntegerTy());
9303 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9304 if (BitSize == 0 || BitSize > 64)
9309 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9310 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9312 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9313 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9314 return NumBits1 == 64 && NumBits2 == 32;
9317 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9318 if (!VT1.isInteger() || !VT2.isInteger())
9320 unsigned NumBits1 = VT1.getSizeInBits();
9321 unsigned NumBits2 = VT2.getSizeInBits();
9322 return NumBits1 == 64 && NumBits2 == 32;
9325 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9326 return isInt<16>(Imm) || isUInt<16>(Imm);
9329 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9330 return isInt<16>(Imm) || isUInt<16>(Imm);
9333 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9337 if (DisablePPCUnaligned)
9340 // PowerPC supports unaligned memory access for simple non-vector types.
9341 // Although accessing unaligned addresses is not as efficient as accessing
9342 // aligned addresses, it is generally more efficient than manual expansion,
9343 // and generally only traps for software emulation when crossing page
9349 if (VT.getSimpleVT().isVector()) {
9350 if (Subtarget.hasVSX()) {
9351 if (VT != MVT::v2f64 && VT != MVT::v2i64)
9358 if (VT == MVT::ppcf128)
9367 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9368 VT = VT.getScalarType();
9373 switch (VT.getSimpleVT().SimpleTy) {
9385 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9386 EVT VT , unsigned DefinedValues) const {
9387 if (VT == MVT::v2i64)
9390 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9393 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9394 if (DisableILPPref || Subtarget.enableMachineScheduler())
9395 return TargetLowering::getSchedulingPreference(N);
9400 // Create a fast isel object.
9402 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9403 const TargetLibraryInfo *LibInfo) const {
9404 return PPC::createFastISel(FuncInfo, LibInfo);