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/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetOptions.h"
40 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
41 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
43 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
44 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
46 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
47 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
49 // FIXME: Remove this once the bug has been fixed!
50 extern cl::opt<bool> ANDIGlueBug;
52 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
53 if (TM.getSubtargetImpl()->isDarwin())
54 return new TargetLoweringObjectFileMachO();
56 if (TM.getSubtargetImpl()->isSVR4ABI())
57 return new PPC64LinuxTargetObjectFile();
59 return new TargetLoweringObjectFileELF();
62 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
63 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
64 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
68 // Use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(true);
70 setUseUnderscoreLongJmp(true);
72 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
73 // arguments are at least 4/8 bytes aligned.
74 bool isPPC64 = Subtarget->isPPC64();
75 setMinStackArgumentAlignment(isPPC64 ? 8:4);
77 // Set up the register classes.
78 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
79 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
80 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
82 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
84 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
86 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
88 // PowerPC has pre-inc load and store's.
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
93 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
100 if (Subtarget->useCRBits()) {
101 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
104 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
105 isPPC64 ? MVT::i64 : MVT::i32);
106 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
107 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
108 isPPC64 ? MVT::i64 : MVT::i32);
110 // PowerPC does not support direct load / store of condition registers
111 setOperationAction(ISD::LOAD, MVT::i1, Custom);
112 setOperationAction(ISD::STORE, MVT::i1, Custom);
114 // FIXME: Remove this once the ANDI glue bug is fixed:
116 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
118 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
119 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
120 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
121 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
122 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
123 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
125 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
128 // This is used in the ppcf128->int sequence. Note it has different semantics
129 // from FP_ROUND: that rounds to nearest, this rounds to zero.
130 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
132 // We do not currently implement these libm ops for PowerPC.
133 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
134 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
135 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
136 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
137 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
138 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
140 // PowerPC has no SREM/UREM instructions
141 setOperationAction(ISD::SREM, MVT::i32, Expand);
142 setOperationAction(ISD::UREM, MVT::i32, Expand);
143 setOperationAction(ISD::SREM, MVT::i64, Expand);
144 setOperationAction(ISD::UREM, MVT::i64, Expand);
146 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
147 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
148 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
149 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
150 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
151 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
152 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
153 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
154 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
156 // We don't support sin/cos/sqrt/fmod/pow
157 setOperationAction(ISD::FSIN , MVT::f64, Expand);
158 setOperationAction(ISD::FCOS , MVT::f64, Expand);
159 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
160 setOperationAction(ISD::FREM , MVT::f64, Expand);
161 setOperationAction(ISD::FPOW , MVT::f64, Expand);
162 setOperationAction(ISD::FMA , MVT::f64, Legal);
163 setOperationAction(ISD::FSIN , MVT::f32, Expand);
164 setOperationAction(ISD::FCOS , MVT::f32, Expand);
165 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
166 setOperationAction(ISD::FREM , MVT::f32, Expand);
167 setOperationAction(ISD::FPOW , MVT::f32, Expand);
168 setOperationAction(ISD::FMA , MVT::f32, Legal);
170 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
172 // If we're enabling GP optimizations, use hardware square root
173 if (!Subtarget->hasFSQRT() &&
174 !(TM.Options.UnsafeFPMath &&
175 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
176 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
178 if (!Subtarget->hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath &&
180 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
181 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
183 if (Subtarget->hasFCPSGN()) {
184 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
185 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
187 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
191 if (Subtarget->hasFPRND()) {
192 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
193 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
194 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
195 setOperationAction(ISD::FROUND, MVT::f64, Legal);
197 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
200 setOperationAction(ISD::FROUND, MVT::f32, Legal);
203 // PowerPC does not have BSWAP, CTPOP or CTTZ
204 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
205 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
206 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
207 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
208 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
209 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
210 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
211 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
213 if (Subtarget->hasPOPCNTD()) {
214 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
215 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
217 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
218 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
221 // PowerPC does not have ROTR
222 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
223 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
225 if (!Subtarget->useCRBits()) {
226 // PowerPC does not have Select
227 setOperationAction(ISD::SELECT, MVT::i32, Expand);
228 setOperationAction(ISD::SELECT, MVT::i64, Expand);
229 setOperationAction(ISD::SELECT, MVT::f32, Expand);
230 setOperationAction(ISD::SELECT, MVT::f64, Expand);
233 // PowerPC wants to turn select_cc of FP into fsel when possible.
234 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
235 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
237 // PowerPC wants to optimize integer setcc a bit
238 if (!Subtarget->useCRBits())
239 setOperationAction(ISD::SETCC, MVT::i32, Custom);
241 // PowerPC does not have BRCOND which requires SetCC
242 if (!Subtarget->useCRBits())
243 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
245 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
247 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
248 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
250 // PowerPC does not have [U|S]INT_TO_FP
251 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
252 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
254 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
255 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
256 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
257 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
259 // We cannot sextinreg(i1). Expand to shifts.
260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
262 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
263 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
264 // support continuation, user-level threading, and etc.. As a result, no
265 // other SjLj exception interfaces are implemented and please don't build
266 // your own exception handling based on them.
267 // LLVM/Clang supports zero-cost DWARF exception handling.
268 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
269 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
271 // We want to legalize GlobalAddress and ConstantPool nodes into the
272 // appropriate instructions to materialize the address.
273 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
274 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
275 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
276 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
277 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
278 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
285 setOperationAction(ISD::TRAP, MVT::Other, Legal);
287 // TRAMPOLINE is custom lowered.
288 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
289 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
291 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
292 setOperationAction(ISD::VASTART , MVT::Other, Custom);
294 if (Subtarget->isSVR4ABI()) {
296 // VAARG always uses double-word chunks, so promote anything smaller.
297 setOperationAction(ISD::VAARG, MVT::i1, Promote);
298 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
299 setOperationAction(ISD::VAARG, MVT::i8, Promote);
300 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
301 setOperationAction(ISD::VAARG, MVT::i16, Promote);
302 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
303 setOperationAction(ISD::VAARG, MVT::i32, Promote);
304 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
305 setOperationAction(ISD::VAARG, MVT::Other, Expand);
307 // VAARG is custom lowered with the 32-bit SVR4 ABI.
308 setOperationAction(ISD::VAARG, MVT::Other, Custom);
309 setOperationAction(ISD::VAARG, MVT::i64, Custom);
312 setOperationAction(ISD::VAARG, MVT::Other, Expand);
314 if (Subtarget->isSVR4ABI() && !isPPC64)
315 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
316 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
318 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
320 // Use the default implementation.
321 setOperationAction(ISD::VAEND , MVT::Other, Expand);
322 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
323 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
324 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
325 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
327 // We want to custom lower some of our intrinsics.
328 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
330 // To handle counter-based loop conditions.
331 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
333 // Comparisons that require checking two conditions.
334 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
335 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
336 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
337 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
338 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
339 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
340 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
341 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
342 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
343 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
344 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
345 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
347 if (Subtarget->has64BitSupport()) {
348 // They also have instructions for converting between i64 and fp.
349 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
350 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
351 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
352 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
353 // This is just the low 32 bits of a (signed) fp->i64 conversion.
354 // We cannot do this with Promote because i64 is not a legal type.
355 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
357 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
358 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
360 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
361 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
364 // With the instructions enabled under FPCVT, we can do everything.
365 if (PPCSubTarget.hasFPCVT()) {
366 if (Subtarget->has64BitSupport()) {
367 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
368 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
369 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
370 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
374 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
375 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
376 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
379 if (Subtarget->use64BitRegs()) {
380 // 64-bit PowerPC implementations can support i64 types directly
381 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
382 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
383 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
384 // 64-bit PowerPC wants to expand i128 shifts itself.
385 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
386 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
387 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
389 // 32-bit PowerPC wants to expand i64 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
395 if (Subtarget->hasAltivec()) {
396 // First set operation action for all vector types to expand. Then we
397 // will selectively turn on ones that can be effectively codegen'd.
398 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
399 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
400 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
402 // add/sub are legal for all supported vector VT's.
403 setOperationAction(ISD::ADD , VT, Legal);
404 setOperationAction(ISD::SUB , VT, Legal);
406 // We promote all shuffles to v16i8.
407 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
408 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
410 // We promote all non-typed operations to v4i32.
411 setOperationAction(ISD::AND , VT, Promote);
412 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
413 setOperationAction(ISD::OR , VT, Promote);
414 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
415 setOperationAction(ISD::XOR , VT, Promote);
416 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
417 setOperationAction(ISD::LOAD , VT, Promote);
418 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
419 setOperationAction(ISD::SELECT, VT, Promote);
420 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
421 setOperationAction(ISD::STORE, VT, Promote);
422 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
424 // No other operations are legal.
425 setOperationAction(ISD::MUL , VT, Expand);
426 setOperationAction(ISD::SDIV, VT, Expand);
427 setOperationAction(ISD::SREM, VT, Expand);
428 setOperationAction(ISD::UDIV, VT, Expand);
429 setOperationAction(ISD::UREM, VT, Expand);
430 setOperationAction(ISD::FDIV, VT, Expand);
431 setOperationAction(ISD::FREM, VT, Expand);
432 setOperationAction(ISD::FNEG, VT, Expand);
433 setOperationAction(ISD::FSQRT, VT, Expand);
434 setOperationAction(ISD::FLOG, VT, Expand);
435 setOperationAction(ISD::FLOG10, VT, Expand);
436 setOperationAction(ISD::FLOG2, VT, Expand);
437 setOperationAction(ISD::FEXP, VT, Expand);
438 setOperationAction(ISD::FEXP2, VT, Expand);
439 setOperationAction(ISD::FSIN, VT, Expand);
440 setOperationAction(ISD::FCOS, VT, Expand);
441 setOperationAction(ISD::FABS, VT, Expand);
442 setOperationAction(ISD::FPOWI, VT, Expand);
443 setOperationAction(ISD::FFLOOR, VT, Expand);
444 setOperationAction(ISD::FCEIL, VT, Expand);
445 setOperationAction(ISD::FTRUNC, VT, Expand);
446 setOperationAction(ISD::FRINT, VT, Expand);
447 setOperationAction(ISD::FNEARBYINT, VT, Expand);
448 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
449 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
450 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
451 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
452 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
453 setOperationAction(ISD::UDIVREM, VT, Expand);
454 setOperationAction(ISD::SDIVREM, VT, Expand);
455 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
456 setOperationAction(ISD::FPOW, VT, Expand);
457 setOperationAction(ISD::CTPOP, VT, Expand);
458 setOperationAction(ISD::CTLZ, VT, Expand);
459 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
460 setOperationAction(ISD::CTTZ, VT, Expand);
461 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
462 setOperationAction(ISD::VSELECT, VT, Expand);
463 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
465 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
466 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
467 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
468 setTruncStoreAction(VT, InnerVT, Expand);
470 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
471 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
472 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
475 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
476 // with merges, splats, etc.
477 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
479 setOperationAction(ISD::AND , MVT::v4i32, Legal);
480 setOperationAction(ISD::OR , MVT::v4i32, Legal);
481 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
482 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
483 setOperationAction(ISD::SELECT, MVT::v4i32,
484 Subtarget->useCRBits() ? Legal : Expand);
485 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
486 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
487 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
488 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
489 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
490 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
491 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
492 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
493 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
495 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
496 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
497 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
498 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
500 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
501 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
503 if (TM.Options.UnsafeFPMath) {
504 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
505 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
508 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
509 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
510 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
512 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
513 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
515 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
516 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
517 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
518 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
520 // Altivec does not contain unordered floating-point compare instructions
521 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
522 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
523 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
524 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
525 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
526 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
528 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
529 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
532 if (Subtarget->has64BitSupport()) {
533 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
534 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
537 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
538 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
539 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
540 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
542 setBooleanContents(ZeroOrOneBooleanContent);
543 // Altivec instructions set fields to all zeros or all ones.
544 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
547 setStackPointerRegisterToSaveRestore(PPC::X1);
548 setExceptionPointerRegister(PPC::X3);
549 setExceptionSelectorRegister(PPC::X4);
551 setStackPointerRegisterToSaveRestore(PPC::R1);
552 setExceptionPointerRegister(PPC::R3);
553 setExceptionSelectorRegister(PPC::R4);
556 // We have target-specific dag combine patterns for the following nodes:
557 setTargetDAGCombine(ISD::SINT_TO_FP);
558 setTargetDAGCombine(ISD::LOAD);
559 setTargetDAGCombine(ISD::STORE);
560 setTargetDAGCombine(ISD::BR_CC);
561 if (Subtarget->useCRBits())
562 setTargetDAGCombine(ISD::BRCOND);
563 setTargetDAGCombine(ISD::BSWAP);
564 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
566 if (Subtarget->useCRBits()) {
567 setTargetDAGCombine(ISD::SIGN_EXTEND);
568 setTargetDAGCombine(ISD::ZERO_EXTEND);
569 setTargetDAGCombine(ISD::ANY_EXTEND);
570 setTargetDAGCombine(ISD::TRUNCATE);
571 setTargetDAGCombine(ISD::SETCC);
572 setTargetDAGCombine(ISD::SELECT_CC);
575 // Use reciprocal estimates.
576 if (TM.Options.UnsafeFPMath) {
577 setTargetDAGCombine(ISD::FDIV);
578 setTargetDAGCombine(ISD::FSQRT);
581 // Darwin long double math library functions have $LDBL128 appended.
582 if (Subtarget->isDarwin()) {
583 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
584 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
585 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
586 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
587 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
588 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
589 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
590 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
591 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
592 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
595 // With 32 condition bits, we don't need to sink (and duplicate) compares
596 // aggressively in CodeGenPrep.
597 if (Subtarget->useCRBits())
598 setHasMultipleConditionRegisters();
600 setMinFunctionAlignment(2);
601 if (PPCSubTarget.isDarwin())
602 setPrefFunctionAlignment(4);
604 if (isPPC64 && Subtarget->isJITCodeModel())
605 // Temporary workaround for the inability of PPC64 JIT to handle jump
607 setSupportJumpTables(false);
609 setInsertFencesForAtomic(true);
611 if (Subtarget->enableMachineScheduler())
612 setSchedulingPreference(Sched::Source);
614 setSchedulingPreference(Sched::Hybrid);
616 computeRegisterProperties();
618 // The Freescale cores does better with aggressive inlining of memcpy and
619 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
620 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
621 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
622 MaxStoresPerMemset = 32;
623 MaxStoresPerMemsetOptSize = 16;
624 MaxStoresPerMemcpy = 32;
625 MaxStoresPerMemcpyOptSize = 8;
626 MaxStoresPerMemmove = 32;
627 MaxStoresPerMemmoveOptSize = 8;
629 setPrefFunctionAlignment(4);
633 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
634 /// the desired ByVal argument alignment.
635 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
636 unsigned MaxMaxAlign) {
637 if (MaxAlign == MaxMaxAlign)
639 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
640 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
642 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
644 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
645 unsigned EltAlign = 0;
646 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
647 if (EltAlign > MaxAlign)
649 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
650 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
651 unsigned EltAlign = 0;
652 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
653 if (EltAlign > MaxAlign)
655 if (MaxAlign == MaxMaxAlign)
661 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
662 /// function arguments in the caller parameter area.
663 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
664 // Darwin passes everything on 4 byte boundary.
665 if (PPCSubTarget.isDarwin())
668 // 16byte and wider vectors are passed on 16byte boundary.
669 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
670 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
671 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
672 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
676 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
679 case PPCISD::FSEL: return "PPCISD::FSEL";
680 case PPCISD::FCFID: return "PPCISD::FCFID";
681 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
682 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
683 case PPCISD::FRE: return "PPCISD::FRE";
684 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
685 case PPCISD::STFIWX: return "PPCISD::STFIWX";
686 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
687 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
688 case PPCISD::VPERM: return "PPCISD::VPERM";
689 case PPCISD::Hi: return "PPCISD::Hi";
690 case PPCISD::Lo: return "PPCISD::Lo";
691 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
692 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
693 case PPCISD::LOAD: return "PPCISD::LOAD";
694 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
695 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
696 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
697 case PPCISD::SRL: return "PPCISD::SRL";
698 case PPCISD::SRA: return "PPCISD::SRA";
699 case PPCISD::SHL: return "PPCISD::SHL";
700 case PPCISD::CALL: return "PPCISD::CALL";
701 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
702 case PPCISD::MTCTR: return "PPCISD::MTCTR";
703 case PPCISD::BCTRL: return "PPCISD::BCTRL";
704 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
705 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
706 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
707 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
708 case PPCISD::VCMP: return "PPCISD::VCMP";
709 case PPCISD::VCMPo: return "PPCISD::VCMPo";
710 case PPCISD::LBRX: return "PPCISD::LBRX";
711 case PPCISD::STBRX: return "PPCISD::STBRX";
712 case PPCISD::LARX: return "PPCISD::LARX";
713 case PPCISD::STCX: return "PPCISD::STCX";
714 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
715 case PPCISD::BDNZ: return "PPCISD::BDNZ";
716 case PPCISD::BDZ: return "PPCISD::BDZ";
717 case PPCISD::MFFS: return "PPCISD::MFFS";
718 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
719 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
720 case PPCISD::CR6SET: return "PPCISD::CR6SET";
721 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
722 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
723 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
724 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
725 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
726 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
727 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
728 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
729 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
730 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
731 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
732 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
733 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
734 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
735 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
736 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
737 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
738 case PPCISD::SC: return "PPCISD::SC";
742 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
744 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
745 return VT.changeVectorElementTypeToInteger();
748 //===----------------------------------------------------------------------===//
749 // Node matching predicates, for use by the tblgen matching code.
750 //===----------------------------------------------------------------------===//
752 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
753 static bool isFloatingPointZero(SDValue Op) {
754 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
755 return CFP->getValueAPF().isZero();
756 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
757 // Maybe this has already been legalized into the constant pool?
758 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
759 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
760 return CFP->getValueAPF().isZero();
765 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
766 /// true if Op is undef or if it matches the specified value.
767 static bool isConstantOrUndef(int Op, int Val) {
768 return Op < 0 || Op == Val;
771 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
772 /// VPKUHUM instruction.
773 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
775 for (unsigned i = 0; i != 16; ++i)
776 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
779 for (unsigned i = 0; i != 8; ++i)
780 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
781 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
787 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
788 /// VPKUWUM instruction.
789 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
791 for (unsigned i = 0; i != 16; i += 2)
792 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
793 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
796 for (unsigned i = 0; i != 8; i += 2)
797 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
798 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
799 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
800 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
806 /// isVMerge - Common function, used to match vmrg* shuffles.
808 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
809 unsigned LHSStart, unsigned RHSStart) {
810 assert(N->getValueType(0) == MVT::v16i8 &&
811 "PPC only supports shuffles by bytes!");
812 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
813 "Unsupported merge size!");
815 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
816 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
817 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
818 LHSStart+j+i*UnitSize) ||
819 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
820 RHSStart+j+i*UnitSize))
826 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
827 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
828 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
831 return isVMerge(N, UnitSize, 8, 24);
832 return isVMerge(N, UnitSize, 8, 8);
835 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
836 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
837 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
840 return isVMerge(N, UnitSize, 0, 16);
841 return isVMerge(N, UnitSize, 0, 0);
845 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
846 /// amount, otherwise return -1.
847 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
848 assert(N->getValueType(0) == MVT::v16i8 &&
849 "PPC only supports shuffles by bytes!");
851 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
853 // Find the first non-undef value in the shuffle mask.
855 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
858 if (i == 16) return -1; // all undef.
860 // Otherwise, check to see if the rest of the elements are consecutively
861 // numbered from this value.
862 unsigned ShiftAmt = SVOp->getMaskElt(i);
863 if (ShiftAmt < i) return -1;
867 // Check the rest of the elements to see if they are consecutive.
868 for (++i; i != 16; ++i)
869 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
872 // Check the rest of the elements to see if they are consecutive.
873 for (++i; i != 16; ++i)
874 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
880 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
881 /// specifies a splat of a single element that is suitable for input to
882 /// VSPLTB/VSPLTH/VSPLTW.
883 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
884 assert(N->getValueType(0) == MVT::v16i8 &&
885 (EltSize == 1 || EltSize == 2 || EltSize == 4));
887 // This is a splat operation if each element of the permute is the same, and
888 // if the value doesn't reference the second vector.
889 unsigned ElementBase = N->getMaskElt(0);
891 // FIXME: Handle UNDEF elements too!
892 if (ElementBase >= 16)
895 // Check that the indices are consecutive, in the case of a multi-byte element
896 // splatted with a v16i8 mask.
897 for (unsigned i = 1; i != EltSize; ++i)
898 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
901 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
902 if (N->getMaskElt(i) < 0) continue;
903 for (unsigned j = 0; j != EltSize; ++j)
904 if (N->getMaskElt(i+j) != N->getMaskElt(j))
910 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
912 bool PPC::isAllNegativeZeroVector(SDNode *N) {
913 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
915 APInt APVal, APUndef;
919 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
920 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
921 return CFP->getValueAPF().isNegZero();
926 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
927 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
928 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
929 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
930 assert(isSplatShuffleMask(SVOp, EltSize));
931 return SVOp->getMaskElt(0) / EltSize;
934 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
935 /// by using a vspltis[bhw] instruction of the specified element size, return
936 /// the constant being splatted. The ByteSize field indicates the number of
937 /// bytes of each element [124] -> [bhw].
938 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
941 // If ByteSize of the splat is bigger than the element size of the
942 // build_vector, then we have a case where we are checking for a splat where
943 // multiple elements of the buildvector are folded together into a single
944 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
945 unsigned EltSize = 16/N->getNumOperands();
946 if (EltSize < ByteSize) {
947 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
948 SDValue UniquedVals[4];
949 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
951 // See if all of the elements in the buildvector agree across.
952 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
953 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
954 // If the element isn't a constant, bail fully out.
955 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
958 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
959 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
960 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
961 return SDValue(); // no match.
964 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
965 // either constant or undef values that are identical for each chunk. See
966 // if these chunks can form into a larger vspltis*.
968 // Check to see if all of the leading entries are either 0 or -1. If
969 // neither, then this won't fit into the immediate field.
970 bool LeadingZero = true;
971 bool LeadingOnes = true;
972 for (unsigned i = 0; i != Multiple-1; ++i) {
973 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
975 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
976 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
978 // Finally, check the least significant entry.
980 if (UniquedVals[Multiple-1].getNode() == 0)
981 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
982 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
984 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
987 if (UniquedVals[Multiple-1].getNode() == 0)
988 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
989 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
990 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
991 return DAG.getTargetConstant(Val, MVT::i32);
997 // Check to see if this buildvec has a single non-undef value in its elements.
998 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
999 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1000 if (OpVal.getNode() == 0)
1001 OpVal = N->getOperand(i);
1002 else if (OpVal != N->getOperand(i))
1006 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
1008 unsigned ValSizeInBytes = EltSize;
1010 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1011 Value = CN->getZExtValue();
1012 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1013 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1014 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1017 // If the splat value is larger than the element value, then we can never do
1018 // this splat. The only case that we could fit the replicated bits into our
1019 // immediate field for would be zero, and we prefer to use vxor for it.
1020 if (ValSizeInBytes < ByteSize) return SDValue();
1022 // If the element value is larger than the splat value, cut it in half and
1023 // check to see if the two halves are equal. Continue doing this until we
1024 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1025 while (ValSizeInBytes > ByteSize) {
1026 ValSizeInBytes >>= 1;
1028 // If the top half equals the bottom half, we're still ok.
1029 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1030 (Value & ((1 << (8*ValSizeInBytes))-1)))
1034 // Properly sign extend the value.
1035 int MaskVal = SignExtend32(Value, ByteSize * 8);
1037 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1038 if (MaskVal == 0) return SDValue();
1040 // Finally, if this value fits in a 5 bit sext field, return it
1041 if (SignExtend32<5>(MaskVal) == MaskVal)
1042 return DAG.getTargetConstant(MaskVal, MVT::i32);
1046 //===----------------------------------------------------------------------===//
1047 // Addressing Mode Selection
1048 //===----------------------------------------------------------------------===//
1050 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1051 /// or 64-bit immediate, and if the value can be accurately represented as a
1052 /// sign extension from a 16-bit value. If so, this returns true and the
1054 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1055 if (N->getOpcode() != ISD::Constant)
1058 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1059 if (N->getValueType(0) == MVT::i32)
1060 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1062 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1064 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1065 return isIntS16Immediate(Op.getNode(), Imm);
1069 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1070 /// can be represented as an indexed [r+r] operation. Returns false if it
1071 /// can be more efficiently represented with [r+imm].
1072 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1074 SelectionDAG &DAG) const {
1076 if (N.getOpcode() == ISD::ADD) {
1077 if (isIntS16Immediate(N.getOperand(1), imm))
1078 return false; // r+i
1079 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1080 return false; // r+i
1082 Base = N.getOperand(0);
1083 Index = N.getOperand(1);
1085 } else if (N.getOpcode() == ISD::OR) {
1086 if (isIntS16Immediate(N.getOperand(1), imm))
1087 return false; // r+i can fold it if we can.
1089 // If this is an or of disjoint bitfields, we can codegen this as an add
1090 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1092 APInt LHSKnownZero, LHSKnownOne;
1093 APInt RHSKnownZero, RHSKnownOne;
1094 DAG.ComputeMaskedBits(N.getOperand(0),
1095 LHSKnownZero, LHSKnownOne);
1097 if (LHSKnownZero.getBoolValue()) {
1098 DAG.ComputeMaskedBits(N.getOperand(1),
1099 RHSKnownZero, RHSKnownOne);
1100 // If all of the bits are known zero on the LHS or RHS, the add won't
1102 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1103 Base = N.getOperand(0);
1104 Index = N.getOperand(1);
1113 // If we happen to be doing an i64 load or store into a stack slot that has
1114 // less than a 4-byte alignment, then the frame-index elimination may need to
1115 // use an indexed load or store instruction (because the offset may not be a
1116 // multiple of 4). The extra register needed to hold the offset comes from the
1117 // register scavenger, and it is possible that the scavenger will need to use
1118 // an emergency spill slot. As a result, we need to make sure that a spill slot
1119 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1121 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1122 // FIXME: This does not handle the LWA case.
1126 // NOTE: We'll exclude negative FIs here, which come from argument
1127 // lowering, because there are no known test cases triggering this problem
1128 // using packed structures (or similar). We can remove this exclusion if
1129 // we find such a test case. The reason why this is so test-case driven is
1130 // because this entire 'fixup' is only to prevent crashes (from the
1131 // register scavenger) on not-really-valid inputs. For example, if we have:
1133 // %b = bitcast i1* %a to i64*
1134 // store i64* a, i64 b
1135 // then the store should really be marked as 'align 1', but is not. If it
1136 // were marked as 'align 1' then the indexed form would have been
1137 // instruction-selected initially, and the problem this 'fixup' is preventing
1138 // won't happen regardless.
1142 MachineFunction &MF = DAG.getMachineFunction();
1143 MachineFrameInfo *MFI = MF.getFrameInfo();
1145 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1149 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1150 FuncInfo->setHasNonRISpills();
1153 /// Returns true if the address N can be represented by a base register plus
1154 /// a signed 16-bit displacement [r+imm], and if it is not better
1155 /// represented as reg+reg. If Aligned is true, only accept displacements
1156 /// suitable for STD and friends, i.e. multiples of 4.
1157 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1160 bool Aligned) const {
1161 // FIXME dl should come from parent load or store, not from address
1163 // If this can be more profitably realized as r+r, fail.
1164 if (SelectAddressRegReg(N, Disp, Base, DAG))
1167 if (N.getOpcode() == ISD::ADD) {
1169 if (isIntS16Immediate(N.getOperand(1), imm) &&
1170 (!Aligned || (imm & 3) == 0)) {
1171 Disp = DAG.getTargetConstant(imm, N.getValueType());
1172 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1173 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1174 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1176 Base = N.getOperand(0);
1178 return true; // [r+i]
1179 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1180 // Match LOAD (ADD (X, Lo(G))).
1181 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1182 && "Cannot handle constant offsets yet!");
1183 Disp = N.getOperand(1).getOperand(0); // The global address.
1184 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1185 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1186 Disp.getOpcode() == ISD::TargetConstantPool ||
1187 Disp.getOpcode() == ISD::TargetJumpTable);
1188 Base = N.getOperand(0);
1189 return true; // [&g+r]
1191 } else if (N.getOpcode() == ISD::OR) {
1193 if (isIntS16Immediate(N.getOperand(1), imm) &&
1194 (!Aligned || (imm & 3) == 0)) {
1195 // If this is an or of disjoint bitfields, we can codegen this as an add
1196 // (for better address arithmetic) if the LHS and RHS of the OR are
1197 // provably disjoint.
1198 APInt LHSKnownZero, LHSKnownOne;
1199 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1201 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1202 // If all of the bits are known zero on the LHS or RHS, the add won't
1204 Base = N.getOperand(0);
1205 Disp = DAG.getTargetConstant(imm, N.getValueType());
1209 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1210 // Loading from a constant address.
1212 // If this address fits entirely in a 16-bit sext immediate field, codegen
1215 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1216 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1217 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1218 CN->getValueType(0));
1222 // Handle 32-bit sext immediates with LIS + addr mode.
1223 if ((CN->getValueType(0) == MVT::i32 ||
1224 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1225 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1226 int Addr = (int)CN->getZExtValue();
1228 // Otherwise, break this down into an LIS + disp.
1229 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1231 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1232 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1233 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1238 Disp = DAG.getTargetConstant(0, getPointerTy());
1239 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1240 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1241 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1244 return true; // [r+0]
1247 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1248 /// represented as an indexed [r+r] operation.
1249 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1251 SelectionDAG &DAG) const {
1252 // Check to see if we can easily represent this as an [r+r] address. This
1253 // will fail if it thinks that the address is more profitably represented as
1254 // reg+imm, e.g. where imm = 0.
1255 if (SelectAddressRegReg(N, Base, Index, DAG))
1258 // If the operand is an addition, always emit this as [r+r], since this is
1259 // better (for code size, and execution, as the memop does the add for free)
1260 // than emitting an explicit add.
1261 if (N.getOpcode() == ISD::ADD) {
1262 Base = N.getOperand(0);
1263 Index = N.getOperand(1);
1267 // Otherwise, do it the hard way, using R0 as the base register.
1268 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1274 /// getPreIndexedAddressParts - returns true by value, base pointer and
1275 /// offset pointer and addressing mode by reference if the node's address
1276 /// can be legally represented as pre-indexed load / store address.
1277 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1279 ISD::MemIndexedMode &AM,
1280 SelectionDAG &DAG) const {
1281 if (DisablePPCPreinc) return false;
1287 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1288 Ptr = LD->getBasePtr();
1289 VT = LD->getMemoryVT();
1290 Alignment = LD->getAlignment();
1291 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1292 Ptr = ST->getBasePtr();
1293 VT = ST->getMemoryVT();
1294 Alignment = ST->getAlignment();
1299 // PowerPC doesn't have preinc load/store instructions for vectors.
1303 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1305 // Common code will reject creating a pre-inc form if the base pointer
1306 // is a frame index, or if N is a store and the base pointer is either
1307 // the same as or a predecessor of the value being stored. Check for
1308 // those situations here, and try with swapped Base/Offset instead.
1311 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1314 SDValue Val = cast<StoreSDNode>(N)->getValue();
1315 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1320 std::swap(Base, Offset);
1326 // LDU/STU can only handle immediates that are a multiple of 4.
1327 if (VT != MVT::i64) {
1328 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1331 // LDU/STU need an address with at least 4-byte alignment.
1335 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1339 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1340 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1341 // sext i32 to i64 when addr mode is r+i.
1342 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1343 LD->getExtensionType() == ISD::SEXTLOAD &&
1344 isa<ConstantSDNode>(Offset))
1352 //===----------------------------------------------------------------------===//
1353 // LowerOperation implementation
1354 //===----------------------------------------------------------------------===//
1356 /// GetLabelAccessInfo - Return true if we should reference labels using a
1357 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1358 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1359 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1360 HiOpFlags = PPCII::MO_HA;
1361 LoOpFlags = PPCII::MO_LO;
1363 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1364 // non-darwin platform. We don't support PIC on other platforms yet.
1365 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1366 TM.getSubtarget<PPCSubtarget>().isDarwin();
1368 HiOpFlags |= PPCII::MO_PIC_FLAG;
1369 LoOpFlags |= PPCII::MO_PIC_FLAG;
1372 // If this is a reference to a global value that requires a non-lazy-ptr, make
1373 // sure that instruction lowering adds it.
1374 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1375 HiOpFlags |= PPCII::MO_NLP_FLAG;
1376 LoOpFlags |= PPCII::MO_NLP_FLAG;
1378 if (GV->hasHiddenVisibility()) {
1379 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1380 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1387 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1388 SelectionDAG &DAG) {
1389 EVT PtrVT = HiPart.getValueType();
1390 SDValue Zero = DAG.getConstant(0, PtrVT);
1393 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1394 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1396 // With PIC, the first instruction is actually "GR+hi(&G)".
1398 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1399 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1401 // Generate non-pic code that has direct accesses to the constant pool.
1402 // The address of the global is just (hi(&g)+lo(&g)).
1403 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1406 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1407 SelectionDAG &DAG) const {
1408 EVT PtrVT = Op.getValueType();
1409 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1410 const Constant *C = CP->getConstVal();
1412 // 64-bit SVR4 ABI code is always position-independent.
1413 // The actual address of the GlobalValue is stored in the TOC.
1414 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1415 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1416 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1417 DAG.getRegister(PPC::X2, MVT::i64));
1420 unsigned MOHiFlag, MOLoFlag;
1421 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1423 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1425 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1426 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1429 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1430 EVT PtrVT = Op.getValueType();
1431 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1433 // 64-bit SVR4 ABI code is always position-independent.
1434 // The actual address of the GlobalValue is stored in the TOC.
1435 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1436 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1437 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1438 DAG.getRegister(PPC::X2, MVT::i64));
1441 unsigned MOHiFlag, MOLoFlag;
1442 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1443 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1444 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1445 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1448 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1449 SelectionDAG &DAG) const {
1450 EVT PtrVT = Op.getValueType();
1452 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1454 unsigned MOHiFlag, MOLoFlag;
1455 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1456 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1457 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1458 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1461 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1462 SelectionDAG &DAG) const {
1464 // FIXME: TLS addresses currently use medium model code sequences,
1465 // which is the most useful form. Eventually support for small and
1466 // large models could be added if users need it, at the cost of
1467 // additional complexity.
1468 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1470 const GlobalValue *GV = GA->getGlobal();
1471 EVT PtrVT = getPointerTy();
1472 bool is64bit = PPCSubTarget.isPPC64();
1474 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1476 if (Model == TLSModel::LocalExec) {
1477 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1478 PPCII::MO_TPREL_HA);
1479 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1480 PPCII::MO_TPREL_LO);
1481 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1482 is64bit ? MVT::i64 : MVT::i32);
1483 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1484 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1487 if (Model == TLSModel::InitialExec) {
1488 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1489 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1493 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1494 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1495 PtrVT, GOTReg, TGA);
1497 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1498 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1499 PtrVT, TGA, GOTPtr);
1500 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1503 if (Model == TLSModel::GeneralDynamic) {
1504 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1505 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1506 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1508 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1511 // We need a chain node, and don't have one handy. The underlying
1512 // call has no side effects, so using the function entry node
1514 SDValue Chain = DAG.getEntryNode();
1515 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1516 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1517 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1518 PtrVT, ParmReg, TGA);
1519 // The return value from GET_TLS_ADDR really is in X3 already, but
1520 // some hacks are needed here to tie everything together. The extra
1521 // copies dissolve during subsequent transforms.
1522 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1523 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1526 if (Model == TLSModel::LocalDynamic) {
1527 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1528 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1529 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1531 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1534 // We need a chain node, and don't have one handy. The underlying
1535 // call has no side effects, so using the function entry node
1537 SDValue Chain = DAG.getEntryNode();
1538 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1539 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1540 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1541 PtrVT, ParmReg, TGA);
1542 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1543 // some hacks are needed here to tie everything together. The extra
1544 // copies dissolve during subsequent transforms.
1545 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1546 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1547 Chain, ParmReg, TGA);
1548 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1551 llvm_unreachable("Unknown TLS model!");
1554 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1555 SelectionDAG &DAG) const {
1556 EVT PtrVT = Op.getValueType();
1557 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1559 const GlobalValue *GV = GSDN->getGlobal();
1561 // 64-bit SVR4 ABI code is always position-independent.
1562 // The actual address of the GlobalValue is stored in the TOC.
1563 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1564 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1565 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1566 DAG.getRegister(PPC::X2, MVT::i64));
1569 unsigned MOHiFlag, MOLoFlag;
1570 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1573 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1575 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1577 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1579 // If the global reference is actually to a non-lazy-pointer, we have to do an
1580 // extra load to get the address of the global.
1581 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1582 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1583 false, false, false, 0);
1587 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1588 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1591 // If we're comparing for equality to zero, expose the fact that this is
1592 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1593 // fold the new nodes.
1594 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1595 if (C->isNullValue() && CC == ISD::SETEQ) {
1596 EVT VT = Op.getOperand(0).getValueType();
1597 SDValue Zext = Op.getOperand(0);
1598 if (VT.bitsLT(MVT::i32)) {
1600 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1602 unsigned Log2b = Log2_32(VT.getSizeInBits());
1603 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1604 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1605 DAG.getConstant(Log2b, MVT::i32));
1606 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1608 // Leave comparisons against 0 and -1 alone for now, since they're usually
1609 // optimized. FIXME: revisit this when we can custom lower all setcc
1611 if (C->isAllOnesValue() || C->isNullValue())
1615 // If we have an integer seteq/setne, turn it into a compare against zero
1616 // by xor'ing the rhs with the lhs, which is faster than setting a
1617 // condition register, reading it back out, and masking the correct bit. The
1618 // normal approach here uses sub to do this instead of xor. Using xor exposes
1619 // the result to other bit-twiddling opportunities.
1620 EVT LHSVT = Op.getOperand(0).getValueType();
1621 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1622 EVT VT = Op.getValueType();
1623 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1625 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1630 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1631 const PPCSubtarget &Subtarget) const {
1632 SDNode *Node = Op.getNode();
1633 EVT VT = Node->getValueType(0);
1634 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1635 SDValue InChain = Node->getOperand(0);
1636 SDValue VAListPtr = Node->getOperand(1);
1637 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1640 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1643 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1644 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1646 InChain = GprIndex.getValue(1);
1648 if (VT == MVT::i64) {
1649 // Check if GprIndex is even
1650 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1651 DAG.getConstant(1, MVT::i32));
1652 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1653 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1654 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1655 DAG.getConstant(1, MVT::i32));
1656 // Align GprIndex to be even if it isn't
1657 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1661 // fpr index is 1 byte after gpr
1662 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1663 DAG.getConstant(1, MVT::i32));
1666 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1667 FprPtr, MachinePointerInfo(SV), MVT::i8,
1669 InChain = FprIndex.getValue(1);
1671 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1672 DAG.getConstant(8, MVT::i32));
1674 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1675 DAG.getConstant(4, MVT::i32));
1678 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1679 MachinePointerInfo(), false, false,
1681 InChain = OverflowArea.getValue(1);
1683 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1684 MachinePointerInfo(), false, false,
1686 InChain = RegSaveArea.getValue(1);
1688 // select overflow_area if index > 8
1689 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1690 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1692 // adjustment constant gpr_index * 4/8
1693 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1694 VT.isInteger() ? GprIndex : FprIndex,
1695 DAG.getConstant(VT.isInteger() ? 4 : 8,
1698 // OurReg = RegSaveArea + RegConstant
1699 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1702 // Floating types are 32 bytes into RegSaveArea
1703 if (VT.isFloatingPoint())
1704 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1705 DAG.getConstant(32, MVT::i32));
1707 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1708 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1709 VT.isInteger() ? GprIndex : FprIndex,
1710 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1713 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1714 VT.isInteger() ? VAListPtr : FprPtr,
1715 MachinePointerInfo(SV),
1716 MVT::i8, false, false, 0);
1718 // determine if we should load from reg_save_area or overflow_area
1719 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1721 // increase overflow_area by 4/8 if gpr/fpr > 8
1722 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1723 DAG.getConstant(VT.isInteger() ? 4 : 8,
1726 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1729 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1731 MachinePointerInfo(),
1732 MVT::i32, false, false, 0);
1734 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1735 false, false, false, 0);
1738 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1739 const PPCSubtarget &Subtarget) const {
1740 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1742 // We have to copy the entire va_list struct:
1743 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1744 return DAG.getMemcpy(Op.getOperand(0), Op,
1745 Op.getOperand(1), Op.getOperand(2),
1746 DAG.getConstant(12, MVT::i32), 8, false, true,
1747 MachinePointerInfo(), MachinePointerInfo());
1750 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1751 SelectionDAG &DAG) const {
1752 return Op.getOperand(0);
1755 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1756 SelectionDAG &DAG) const {
1757 SDValue Chain = Op.getOperand(0);
1758 SDValue Trmp = Op.getOperand(1); // trampoline
1759 SDValue FPtr = Op.getOperand(2); // nested function
1760 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1763 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1764 bool isPPC64 = (PtrVT == MVT::i64);
1766 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1769 TargetLowering::ArgListTy Args;
1770 TargetLowering::ArgListEntry Entry;
1772 Entry.Ty = IntPtrTy;
1773 Entry.Node = Trmp; Args.push_back(Entry);
1775 // TrampSize == (isPPC64 ? 48 : 40);
1776 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1777 isPPC64 ? MVT::i64 : MVT::i32);
1778 Args.push_back(Entry);
1780 Entry.Node = FPtr; Args.push_back(Entry);
1781 Entry.Node = Nest; Args.push_back(Entry);
1783 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1784 TargetLowering::CallLoweringInfo CLI(Chain,
1785 Type::getVoidTy(*DAG.getContext()),
1786 false, false, false, false, 0,
1788 /*isTailCall=*/false,
1789 /*doesNotRet=*/false,
1790 /*isReturnValueUsed=*/true,
1791 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1793 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1795 return CallResult.second;
1798 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1799 const PPCSubtarget &Subtarget) const {
1800 MachineFunction &MF = DAG.getMachineFunction();
1801 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1805 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1806 // vastart just stores the address of the VarArgsFrameIndex slot into the
1807 // memory location argument.
1808 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1809 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1810 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1811 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1812 MachinePointerInfo(SV),
1816 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1817 // We suppose the given va_list is already allocated.
1820 // char gpr; /* index into the array of 8 GPRs
1821 // * stored in the register save area
1822 // * gpr=0 corresponds to r3,
1823 // * gpr=1 to r4, etc.
1825 // char fpr; /* index into the array of 8 FPRs
1826 // * stored in the register save area
1827 // * fpr=0 corresponds to f1,
1828 // * fpr=1 to f2, etc.
1830 // char *overflow_arg_area;
1831 // /* location on stack that holds
1832 // * the next overflow argument
1834 // char *reg_save_area;
1835 // /* where r3:r10 and f1:f8 (if saved)
1841 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1842 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1845 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1847 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1849 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1852 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1853 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1855 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1856 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1858 uint64_t FPROffset = 1;
1859 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1861 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1863 // Store first byte : number of int regs
1864 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1866 MachinePointerInfo(SV),
1867 MVT::i8, false, false, 0);
1868 uint64_t nextOffset = FPROffset;
1869 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1872 // Store second byte : number of float regs
1873 SDValue secondStore =
1874 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1875 MachinePointerInfo(SV, nextOffset), MVT::i8,
1877 nextOffset += StackOffset;
1878 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1880 // Store second word : arguments given on stack
1881 SDValue thirdStore =
1882 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1883 MachinePointerInfo(SV, nextOffset),
1885 nextOffset += FrameOffset;
1886 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1888 // Store third word : arguments given in registers
1889 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1890 MachinePointerInfo(SV, nextOffset),
1895 #include "PPCGenCallingConv.inc"
1897 // Function whose sole purpose is to kill compiler warnings
1898 // stemming from unused functions included from PPCGenCallingConv.inc.
1899 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
1900 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
1903 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1904 CCValAssign::LocInfo &LocInfo,
1905 ISD::ArgFlagsTy &ArgFlags,
1910 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1912 CCValAssign::LocInfo &LocInfo,
1913 ISD::ArgFlagsTy &ArgFlags,
1915 static const uint16_t ArgRegs[] = {
1916 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1917 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1919 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1921 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1923 // Skip one register if the first unallocated register has an even register
1924 // number and there are still argument registers available which have not been
1925 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1926 // need to skip a register if RegNum is odd.
1927 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1928 State.AllocateReg(ArgRegs[RegNum]);
1931 // Always return false here, as this function only makes sure that the first
1932 // unallocated register has an odd register number and does not actually
1933 // allocate a register for the current argument.
1937 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1939 CCValAssign::LocInfo &LocInfo,
1940 ISD::ArgFlagsTy &ArgFlags,
1942 static const uint16_t ArgRegs[] = {
1943 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1947 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1949 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1951 // If there is only one Floating-point register left we need to put both f64
1952 // values of a split ppc_fp128 value on the stack.
1953 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1954 State.AllocateReg(ArgRegs[RegNum]);
1957 // Always return false here, as this function only makes sure that the two f64
1958 // values a ppc_fp128 value is split into are both passed in registers or both
1959 // passed on the stack and does not actually allocate a register for the
1960 // current argument.
1964 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1966 static const uint16_t *GetFPR() {
1967 static const uint16_t FPR[] = {
1968 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1969 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1975 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1977 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1978 unsigned PtrByteSize) {
1979 unsigned ArgSize = ArgVT.getStoreSize();
1980 if (Flags.isByVal())
1981 ArgSize = Flags.getByValSize();
1982 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1988 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1989 CallingConv::ID CallConv, bool isVarArg,
1990 const SmallVectorImpl<ISD::InputArg>
1992 SDLoc dl, SelectionDAG &DAG,
1993 SmallVectorImpl<SDValue> &InVals)
1995 if (PPCSubTarget.isSVR4ABI()) {
1996 if (PPCSubTarget.isPPC64())
1997 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2000 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2003 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2009 PPCTargetLowering::LowerFormalArguments_32SVR4(
2011 CallingConv::ID CallConv, bool isVarArg,
2012 const SmallVectorImpl<ISD::InputArg>
2014 SDLoc dl, SelectionDAG &DAG,
2015 SmallVectorImpl<SDValue> &InVals) const {
2017 // 32-bit SVR4 ABI Stack Frame Layout:
2018 // +-----------------------------------+
2019 // +--> | Back chain |
2020 // | +-----------------------------------+
2021 // | | Floating-point register save area |
2022 // | +-----------------------------------+
2023 // | | General register save area |
2024 // | +-----------------------------------+
2025 // | | CR save word |
2026 // | +-----------------------------------+
2027 // | | VRSAVE save word |
2028 // | +-----------------------------------+
2029 // | | Alignment padding |
2030 // | +-----------------------------------+
2031 // | | Vector register save area |
2032 // | +-----------------------------------+
2033 // | | Local variable space |
2034 // | +-----------------------------------+
2035 // | | Parameter list area |
2036 // | +-----------------------------------+
2037 // | | LR save word |
2038 // | +-----------------------------------+
2039 // SP--> +--- | Back chain |
2040 // +-----------------------------------+
2043 // System V Application Binary Interface PowerPC Processor Supplement
2044 // AltiVec Technology Programming Interface Manual
2046 MachineFunction &MF = DAG.getMachineFunction();
2047 MachineFrameInfo *MFI = MF.getFrameInfo();
2048 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2050 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2051 // Potential tail calls could cause overwriting of argument stack slots.
2052 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2053 (CallConv == CallingConv::Fast));
2054 unsigned PtrByteSize = 4;
2056 // Assign locations to all of the incoming arguments.
2057 SmallVector<CCValAssign, 16> ArgLocs;
2058 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2059 getTargetMachine(), ArgLocs, *DAG.getContext());
2061 // Reserve space for the linkage area on the stack.
2062 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2064 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2066 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2067 CCValAssign &VA = ArgLocs[i];
2069 // Arguments stored in registers.
2070 if (VA.isRegLoc()) {
2071 const TargetRegisterClass *RC;
2072 EVT ValVT = VA.getValVT();
2074 switch (ValVT.getSimpleVT().SimpleTy) {
2076 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2079 RC = &PPC::GPRCRegClass;
2082 RC = &PPC::F4RCRegClass;
2085 RC = &PPC::F8RCRegClass;
2091 RC = &PPC::VRRCRegClass;
2095 // Transform the arguments stored in physical registers into virtual ones.
2096 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2097 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2098 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2100 if (ValVT == MVT::i1)
2101 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2103 InVals.push_back(ArgValue);
2105 // Argument stored in memory.
2106 assert(VA.isMemLoc());
2108 unsigned ArgSize = VA.getLocVT().getStoreSize();
2109 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2112 // Create load nodes to retrieve arguments from the stack.
2113 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2114 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2115 MachinePointerInfo(),
2116 false, false, false, 0));
2120 // Assign locations to all of the incoming aggregate by value arguments.
2121 // Aggregates passed by value are stored in the local variable space of the
2122 // caller's stack frame, right above the parameter list area.
2123 SmallVector<CCValAssign, 16> ByValArgLocs;
2124 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2125 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2127 // Reserve stack space for the allocations in CCInfo.
2128 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2130 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2132 // Area that is at least reserved in the caller of this function.
2133 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2135 // Set the size that is at least reserved in caller of this function. Tail
2136 // call optimized function's reserved stack space needs to be aligned so that
2137 // taking the difference between two stack areas will result in an aligned
2139 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2142 std::max(MinReservedArea,
2143 PPCFrameLowering::getMinCallFrameSize(false, false));
2145 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2146 getStackAlignment();
2147 unsigned AlignMask = TargetAlign-1;
2148 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2150 FI->setMinReservedArea(MinReservedArea);
2152 SmallVector<SDValue, 8> MemOps;
2154 // If the function takes variable number of arguments, make a frame index for
2155 // the start of the first vararg value... for expansion of llvm.va_start.
2157 static const uint16_t GPArgRegs[] = {
2158 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2159 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2161 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2163 static const uint16_t FPArgRegs[] = {
2164 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2167 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2169 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2171 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2174 // Make room for NumGPArgRegs and NumFPArgRegs.
2175 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2176 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2178 FuncInfo->setVarArgsStackOffset(
2179 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2180 CCInfo.getNextStackOffset(), true));
2182 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2183 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2185 // The fixed integer arguments of a variadic function are stored to the
2186 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2187 // the result of va_next.
2188 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2189 // Get an existing live-in vreg, or add a new one.
2190 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2192 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2194 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2195 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2196 MachinePointerInfo(), false, false, 0);
2197 MemOps.push_back(Store);
2198 // Increment the address by four for the next argument to store
2199 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2200 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2203 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2205 // The double arguments are stored to the VarArgsFrameIndex
2207 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2208 // Get an existing live-in vreg, or add a new one.
2209 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2211 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2213 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2214 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2215 MachinePointerInfo(), false, false, 0);
2216 MemOps.push_back(Store);
2217 // Increment the address by eight for the next argument to store
2218 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2220 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2224 if (!MemOps.empty())
2225 Chain = DAG.getNode(ISD::TokenFactor, dl,
2226 MVT::Other, &MemOps[0], MemOps.size());
2231 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2232 // value to MVT::i64 and then truncate to the correct register size.
2234 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2235 SelectionDAG &DAG, SDValue ArgVal,
2238 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2239 DAG.getValueType(ObjectVT));
2240 else if (Flags.isZExt())
2241 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2242 DAG.getValueType(ObjectVT));
2244 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2247 // Set the size that is at least reserved in caller of this function. Tail
2248 // call optimized functions' reserved stack space needs to be aligned so that
2249 // taking the difference between two stack areas will result in an aligned
2252 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2253 unsigned nAltivecParamsAtEnd,
2254 unsigned MinReservedArea,
2255 bool isPPC64) const {
2256 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2257 // Add the Altivec parameters at the end, if needed.
2258 if (nAltivecParamsAtEnd) {
2259 MinReservedArea = ((MinReservedArea+15)/16)*16;
2260 MinReservedArea += 16*nAltivecParamsAtEnd;
2263 std::max(MinReservedArea,
2264 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2265 unsigned TargetAlign
2266 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2267 getStackAlignment();
2268 unsigned AlignMask = TargetAlign-1;
2269 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2270 FI->setMinReservedArea(MinReservedArea);
2274 PPCTargetLowering::LowerFormalArguments_64SVR4(
2276 CallingConv::ID CallConv, bool isVarArg,
2277 const SmallVectorImpl<ISD::InputArg>
2279 SDLoc dl, SelectionDAG &DAG,
2280 SmallVectorImpl<SDValue> &InVals) const {
2281 // TODO: add description of PPC stack frame format, or at least some docs.
2283 MachineFunction &MF = DAG.getMachineFunction();
2284 MachineFrameInfo *MFI = MF.getFrameInfo();
2285 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2287 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2288 // Potential tail calls could cause overwriting of argument stack slots.
2289 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2290 (CallConv == CallingConv::Fast));
2291 unsigned PtrByteSize = 8;
2293 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2294 // Area that is at least reserved in caller of this function.
2295 unsigned MinReservedArea = ArgOffset;
2297 static const uint16_t GPR[] = {
2298 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2299 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2302 static const uint16_t *FPR = GetFPR();
2304 static const uint16_t VR[] = {
2305 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2306 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2309 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2310 const unsigned Num_FPR_Regs = 13;
2311 const unsigned Num_VR_Regs = array_lengthof(VR);
2313 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2315 // Add DAG nodes to load the arguments or copy them out of registers. On
2316 // entry to a function on PPC, the arguments start after the linkage area,
2317 // although the first ones are often in registers.
2319 SmallVector<SDValue, 8> MemOps;
2320 unsigned nAltivecParamsAtEnd = 0;
2321 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2322 unsigned CurArgIdx = 0;
2323 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2325 bool needsLoad = false;
2326 EVT ObjectVT = Ins[ArgNo].VT;
2327 unsigned ObjSize = ObjectVT.getStoreSize();
2328 unsigned ArgSize = ObjSize;
2329 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2330 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2331 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2333 unsigned CurArgOffset = ArgOffset;
2335 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2336 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2337 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2339 MinReservedArea = ((MinReservedArea+15)/16)*16;
2340 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2344 nAltivecParamsAtEnd++;
2346 // Calculate min reserved area.
2347 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2351 // FIXME the codegen can be much improved in some cases.
2352 // We do not have to keep everything in memory.
2353 if (Flags.isByVal()) {
2354 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2355 ObjSize = Flags.getByValSize();
2356 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2357 // Empty aggregate parameters do not take up registers. Examples:
2361 // etc. However, we have to provide a place-holder in InVals, so
2362 // pretend we have an 8-byte item at the current address for that
2365 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2366 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2367 InVals.push_back(FIN);
2371 unsigned BVAlign = Flags.getByValAlign();
2373 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2374 CurArgOffset = ArgOffset;
2377 // All aggregates smaller than 8 bytes must be passed right-justified.
2378 if (ObjSize < PtrByteSize)
2379 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2380 // The value of the object is its address.
2381 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2382 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2383 InVals.push_back(FIN);
2386 if (GPR_idx != Num_GPR_Regs) {
2387 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2388 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2391 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2392 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2393 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2394 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2395 MachinePointerInfo(FuncArg),
2396 ObjType, false, false, 0);
2398 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2399 // store the whole register as-is to the parameter save area
2400 // slot. The address of the parameter was already calculated
2401 // above (InVals.push_back(FIN)) to be the right-justified
2402 // offset within the slot. For this store, we need a new
2403 // frame index that points at the beginning of the slot.
2404 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2405 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2406 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2407 MachinePointerInfo(FuncArg),
2411 MemOps.push_back(Store);
2414 // Whether we copied from a register or not, advance the offset
2415 // into the parameter save area by a full doubleword.
2416 ArgOffset += PtrByteSize;
2420 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2421 // Store whatever pieces of the object are in registers
2422 // to memory. ArgOffset will be the address of the beginning
2424 if (GPR_idx != Num_GPR_Regs) {
2426 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2427 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2428 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2429 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2430 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2431 MachinePointerInfo(FuncArg, j),
2433 MemOps.push_back(Store);
2435 ArgOffset += PtrByteSize;
2437 ArgOffset += ArgSize - j;
2444 switch (ObjectVT.getSimpleVT().SimpleTy) {
2445 default: llvm_unreachable("Unhandled argument type!");
2449 if (GPR_idx != Num_GPR_Regs) {
2450 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2451 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2453 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2454 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2455 // value to MVT::i64 and then truncate to the correct register size.
2456 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2461 ArgSize = PtrByteSize;
2468 // Every 8 bytes of argument space consumes one of the GPRs available for
2469 // argument passing.
2470 if (GPR_idx != Num_GPR_Regs) {
2473 if (FPR_idx != Num_FPR_Regs) {
2476 if (ObjectVT == MVT::f32)
2477 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2479 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2481 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2485 ArgSize = PtrByteSize;
2494 // Note that vector arguments in registers don't reserve stack space,
2495 // except in varargs functions.
2496 if (VR_idx != Num_VR_Regs) {
2497 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2498 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2500 while ((ArgOffset % 16) != 0) {
2501 ArgOffset += PtrByteSize;
2502 if (GPR_idx != Num_GPR_Regs)
2506 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2510 // Vectors are aligned.
2511 ArgOffset = ((ArgOffset+15)/16)*16;
2512 CurArgOffset = ArgOffset;
2519 // We need to load the argument to a virtual register if we determined
2520 // above that we ran out of physical registers of the appropriate type.
2522 int FI = MFI->CreateFixedObject(ObjSize,
2523 CurArgOffset + (ArgSize - ObjSize),
2525 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2526 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2527 false, false, false, 0);
2530 InVals.push_back(ArgVal);
2533 // Set the size that is at least reserved in caller of this function. Tail
2534 // call optimized functions' reserved stack space needs to be aligned so that
2535 // taking the difference between two stack areas will result in an aligned
2537 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2539 // If the function takes variable number of arguments, make a frame index for
2540 // the start of the first vararg value... for expansion of llvm.va_start.
2542 int Depth = ArgOffset;
2544 FuncInfo->setVarArgsFrameIndex(
2545 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2546 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2548 // If this function is vararg, store any remaining integer argument regs
2549 // to their spots on the stack so that they may be loaded by deferencing the
2550 // result of va_next.
2551 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2552 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2553 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2554 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2555 MachinePointerInfo(), false, false, 0);
2556 MemOps.push_back(Store);
2557 // Increment the address by four for the next argument to store
2558 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2559 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2563 if (!MemOps.empty())
2564 Chain = DAG.getNode(ISD::TokenFactor, dl,
2565 MVT::Other, &MemOps[0], MemOps.size());
2571 PPCTargetLowering::LowerFormalArguments_Darwin(
2573 CallingConv::ID CallConv, bool isVarArg,
2574 const SmallVectorImpl<ISD::InputArg>
2576 SDLoc dl, SelectionDAG &DAG,
2577 SmallVectorImpl<SDValue> &InVals) const {
2578 // TODO: add description of PPC stack frame format, or at least some docs.
2580 MachineFunction &MF = DAG.getMachineFunction();
2581 MachineFrameInfo *MFI = MF.getFrameInfo();
2582 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2584 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2585 bool isPPC64 = PtrVT == MVT::i64;
2586 // Potential tail calls could cause overwriting of argument stack slots.
2587 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2588 (CallConv == CallingConv::Fast));
2589 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2591 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2592 // Area that is at least reserved in caller of this function.
2593 unsigned MinReservedArea = ArgOffset;
2595 static const uint16_t GPR_32[] = { // 32-bit registers.
2596 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2597 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2599 static const uint16_t GPR_64[] = { // 64-bit registers.
2600 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2601 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2604 static const uint16_t *FPR = GetFPR();
2606 static const uint16_t VR[] = {
2607 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2608 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2611 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2612 const unsigned Num_FPR_Regs = 13;
2613 const unsigned Num_VR_Regs = array_lengthof( VR);
2615 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2617 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2619 // In 32-bit non-varargs functions, the stack space for vectors is after the
2620 // stack space for non-vectors. We do not use this space unless we have
2621 // too many vectors to fit in registers, something that only occurs in
2622 // constructed examples:), but we have to walk the arglist to figure
2623 // that out...for the pathological case, compute VecArgOffset as the
2624 // start of the vector parameter area. Computing VecArgOffset is the
2625 // entire point of the following loop.
2626 unsigned VecArgOffset = ArgOffset;
2627 if (!isVarArg && !isPPC64) {
2628 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2630 EVT ObjectVT = Ins[ArgNo].VT;
2631 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2633 if (Flags.isByVal()) {
2634 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2635 unsigned ObjSize = Flags.getByValSize();
2637 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2638 VecArgOffset += ArgSize;
2642 switch(ObjectVT.getSimpleVT().SimpleTy) {
2643 default: llvm_unreachable("Unhandled argument type!");
2649 case MVT::i64: // PPC64
2651 // FIXME: We are guaranteed to be !isPPC64 at this point.
2652 // Does MVT::i64 apply?
2659 // Nothing to do, we're only looking at Nonvector args here.
2664 // We've found where the vector parameter area in memory is. Skip the
2665 // first 12 parameters; these don't use that memory.
2666 VecArgOffset = ((VecArgOffset+15)/16)*16;
2667 VecArgOffset += 12*16;
2669 // Add DAG nodes to load the arguments or copy them out of registers. On
2670 // entry to a function on PPC, the arguments start after the linkage area,
2671 // although the first ones are often in registers.
2673 SmallVector<SDValue, 8> MemOps;
2674 unsigned nAltivecParamsAtEnd = 0;
2675 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2676 unsigned CurArgIdx = 0;
2677 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2679 bool needsLoad = false;
2680 EVT ObjectVT = Ins[ArgNo].VT;
2681 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2682 unsigned ArgSize = ObjSize;
2683 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2684 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2685 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2687 unsigned CurArgOffset = ArgOffset;
2689 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2690 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2691 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2692 if (isVarArg || isPPC64) {
2693 MinReservedArea = ((MinReservedArea+15)/16)*16;
2694 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2697 } else nAltivecParamsAtEnd++;
2699 // Calculate min reserved area.
2700 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2704 // FIXME the codegen can be much improved in some cases.
2705 // We do not have to keep everything in memory.
2706 if (Flags.isByVal()) {
2707 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2708 ObjSize = Flags.getByValSize();
2709 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2710 // Objects of size 1 and 2 are right justified, everything else is
2711 // left justified. This means the memory address is adjusted forwards.
2712 if (ObjSize==1 || ObjSize==2) {
2713 CurArgOffset = CurArgOffset + (4 - ObjSize);
2715 // The value of the object is its address.
2716 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2717 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2718 InVals.push_back(FIN);
2719 if (ObjSize==1 || ObjSize==2) {
2720 if (GPR_idx != Num_GPR_Regs) {
2723 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2725 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2726 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2727 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2728 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2729 MachinePointerInfo(FuncArg),
2730 ObjType, false, false, 0);
2731 MemOps.push_back(Store);
2735 ArgOffset += PtrByteSize;
2739 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2740 // Store whatever pieces of the object are in registers
2741 // to memory. ArgOffset will be the address of the beginning
2743 if (GPR_idx != Num_GPR_Regs) {
2746 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2748 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2749 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2750 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2751 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2752 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2753 MachinePointerInfo(FuncArg, j),
2755 MemOps.push_back(Store);
2757 ArgOffset += PtrByteSize;
2759 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2766 switch (ObjectVT.getSimpleVT().SimpleTy) {
2767 default: llvm_unreachable("Unhandled argument type!");
2771 if (GPR_idx != Num_GPR_Regs) {
2772 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2773 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2777 ArgSize = PtrByteSize;
2779 // All int arguments reserve stack space in the Darwin ABI.
2780 ArgOffset += PtrByteSize;
2784 case MVT::i64: // PPC64
2785 if (GPR_idx != Num_GPR_Regs) {
2786 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2787 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2789 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2790 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2791 // value to MVT::i64 and then truncate to the correct register size.
2792 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2797 ArgSize = PtrByteSize;
2799 // All int arguments reserve stack space in the Darwin ABI.
2805 // Every 4 bytes of argument space consumes one of the GPRs available for
2806 // argument passing.
2807 if (GPR_idx != Num_GPR_Regs) {
2809 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2812 if (FPR_idx != Num_FPR_Regs) {
2815 if (ObjectVT == MVT::f32)
2816 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2818 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2820 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2826 // All FP arguments reserve stack space in the Darwin ABI.
2827 ArgOffset += isPPC64 ? 8 : ObjSize;
2833 // Note that vector arguments in registers don't reserve stack space,
2834 // except in varargs functions.
2835 if (VR_idx != Num_VR_Regs) {
2836 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2837 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2839 while ((ArgOffset % 16) != 0) {
2840 ArgOffset += PtrByteSize;
2841 if (GPR_idx != Num_GPR_Regs)
2845 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2849 if (!isVarArg && !isPPC64) {
2850 // Vectors go after all the nonvectors.
2851 CurArgOffset = VecArgOffset;
2854 // Vectors are aligned.
2855 ArgOffset = ((ArgOffset+15)/16)*16;
2856 CurArgOffset = ArgOffset;
2864 // We need to load the argument to a virtual register if we determined above
2865 // that we ran out of physical registers of the appropriate type.
2867 int FI = MFI->CreateFixedObject(ObjSize,
2868 CurArgOffset + (ArgSize - ObjSize),
2870 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2871 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2872 false, false, false, 0);
2875 InVals.push_back(ArgVal);
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 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2884 // If the function takes variable number of arguments, make a frame index for
2885 // the start of the first vararg value... for expansion of llvm.va_start.
2887 int Depth = ArgOffset;
2889 FuncInfo->setVarArgsFrameIndex(
2890 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
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 != Num_GPR_Regs; ++GPR_idx) {
2901 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2903 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2905 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2906 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2907 MachinePointerInfo(), false, false, 0);
2908 MemOps.push_back(Store);
2909 // Increment the address by four for the next argument to store
2910 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2911 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2915 if (!MemOps.empty())
2916 Chain = DAG.getNode(ISD::TokenFactor, dl,
2917 MVT::Other, &MemOps[0], MemOps.size());
2922 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2923 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2925 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2929 const SmallVectorImpl<ISD::OutputArg>
2931 const SmallVectorImpl<SDValue> &OutVals,
2932 unsigned &nAltivecParamsAtEnd) {
2933 // Count how many bytes are to be pushed on the stack, including the linkage
2934 // area, and parameter passing area. We start with 24/48 bytes, which is
2935 // prereserved space for [SP][CR][LR][3 x unused].
2936 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2937 unsigned NumOps = Outs.size();
2938 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2940 // Add up all the space actually used.
2941 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2942 // they all go in registers, but we must reserve stack space for them for
2943 // possible use by the caller. In varargs or 64-bit calls, parameters are
2944 // assigned stack space in order, with padding so Altivec parameters are
2946 nAltivecParamsAtEnd = 0;
2947 for (unsigned i = 0; i != NumOps; ++i) {
2948 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2949 EVT ArgVT = Outs[i].VT;
2950 // Varargs Altivec parameters are padded to a 16 byte boundary.
2951 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2952 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2953 if (!isVarArg && !isPPC64) {
2954 // Non-varargs Altivec parameters go after all the non-Altivec
2955 // parameters; handle those later so we know how much padding we need.
2956 nAltivecParamsAtEnd++;
2959 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2960 NumBytes = ((NumBytes+15)/16)*16;
2962 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2965 // Allow for Altivec parameters at the end, if needed.
2966 if (nAltivecParamsAtEnd) {
2967 NumBytes = ((NumBytes+15)/16)*16;
2968 NumBytes += 16*nAltivecParamsAtEnd;
2971 // The prolog code of the callee may store up to 8 GPR argument registers to
2972 // the stack, allowing va_start to index over them in memory if its varargs.
2973 // Because we cannot tell if this is needed on the caller side, we have to
2974 // conservatively assume that it is needed. As such, make sure we have at
2975 // least enough stack space for the caller to store the 8 GPRs.
2976 NumBytes = std::max(NumBytes,
2977 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2979 // Tail call needs the stack to be aligned.
2980 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2981 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2982 getFrameLowering()->getStackAlignment();
2983 unsigned AlignMask = TargetAlign-1;
2984 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2990 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2991 /// adjusted to accommodate the arguments for the tailcall.
2992 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2993 unsigned ParamSize) {
2995 if (!isTailCall) return 0;
2997 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2998 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2999 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3000 // Remember only if the new adjustement is bigger.
3001 if (SPDiff < FI->getTailCallSPDelta())
3002 FI->setTailCallSPDelta(SPDiff);
3007 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3008 /// for tail call optimization. Targets which want to do tail call
3009 /// optimization should implement this function.
3011 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3012 CallingConv::ID CalleeCC,
3014 const SmallVectorImpl<ISD::InputArg> &Ins,
3015 SelectionDAG& DAG) const {
3016 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3019 // Variable argument functions are not supported.
3023 MachineFunction &MF = DAG.getMachineFunction();
3024 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3025 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3026 // Functions containing by val parameters are not supported.
3027 for (unsigned i = 0; i != Ins.size(); i++) {
3028 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3029 if (Flags.isByVal()) return false;
3032 // Non-PIC/GOT tail calls are supported.
3033 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3036 // At the moment we can only do local tail calls (in same module, hidden
3037 // or protected) if we are generating PIC.
3038 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3039 return G->getGlobal()->hasHiddenVisibility()
3040 || G->getGlobal()->hasProtectedVisibility();
3046 /// isCallCompatibleAddress - Return the immediate to use if the specified
3047 /// 32-bit value is representable in the immediate field of a BxA instruction.
3048 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3049 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3052 int Addr = C->getZExtValue();
3053 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3054 SignExtend32<26>(Addr) != Addr)
3055 return 0; // Top 6 bits have to be sext of immediate.
3057 return DAG.getConstant((int)C->getZExtValue() >> 2,
3058 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3063 struct TailCallArgumentInfo {
3068 TailCallArgumentInfo() : FrameIdx(0) {}
3073 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3075 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3077 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3078 SmallVectorImpl<SDValue> &MemOpChains,
3080 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3081 SDValue Arg = TailCallArgs[i].Arg;
3082 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3083 int FI = TailCallArgs[i].FrameIdx;
3084 // Store relative to framepointer.
3085 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3086 MachinePointerInfo::getFixedStack(FI),
3091 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3092 /// the appropriate stack slot for the tail call optimized function call.
3093 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3094 MachineFunction &MF,
3103 // Calculate the new stack slot for the return address.
3104 int SlotSize = isPPC64 ? 8 : 4;
3105 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3107 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3108 NewRetAddrLoc, true);
3109 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3110 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3111 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3112 MachinePointerInfo::getFixedStack(NewRetAddr),
3115 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3116 // slot as the FP is never overwritten.
3119 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3120 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3122 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3123 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3124 MachinePointerInfo::getFixedStack(NewFPIdx),
3131 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3132 /// the position of the argument.
3134 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3135 SDValue Arg, int SPDiff, unsigned ArgOffset,
3136 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3137 int Offset = ArgOffset + SPDiff;
3138 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3139 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3140 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3141 SDValue FIN = DAG.getFrameIndex(FI, VT);
3142 TailCallArgumentInfo Info;
3144 Info.FrameIdxOp = FIN;
3146 TailCallArguments.push_back(Info);
3149 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3150 /// stack slot. Returns the chain as result and the loaded frame pointers in
3151 /// LROpOut/FPOpout. Used when tail calling.
3152 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3160 // Load the LR and FP stack slot for later adjusting.
3161 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3162 LROpOut = getReturnAddrFrameIndex(DAG);
3163 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3164 false, false, false, 0);
3165 Chain = SDValue(LROpOut.getNode(), 1);
3167 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3168 // slot as the FP is never overwritten.
3170 FPOpOut = getFramePointerFrameIndex(DAG);
3171 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3172 false, false, false, 0);
3173 Chain = SDValue(FPOpOut.getNode(), 1);
3179 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3180 /// by "Src" to address "Dst" of size "Size". Alignment information is
3181 /// specified by the specific parameter attribute. The copy will be passed as
3182 /// a byval function parameter.
3183 /// Sometimes what we are copying is the end of a larger object, the part that
3184 /// does not fit in registers.
3186 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3187 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3189 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3190 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3191 false, false, MachinePointerInfo(0),
3192 MachinePointerInfo(0));
3195 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3198 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3199 SDValue Arg, SDValue PtrOff, int SPDiff,
3200 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3201 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3202 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3204 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3209 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3211 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3212 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3213 DAG.getConstant(ArgOffset, PtrVT));
3215 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3216 MachinePointerInfo(), false, false, 0));
3217 // Calculate and remember argument location.
3218 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3223 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3224 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3225 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3226 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3227 MachineFunction &MF = DAG.getMachineFunction();
3229 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3230 // might overwrite each other in case of tail call optimization.
3231 SmallVector<SDValue, 8> MemOpChains2;
3232 // Do not flag preceding copytoreg stuff together with the following stuff.
3234 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3236 if (!MemOpChains2.empty())
3237 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3238 &MemOpChains2[0], MemOpChains2.size());
3240 // Store the return address to the appropriate stack slot.
3241 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3242 isPPC64, isDarwinABI, dl);
3244 // Emit callseq_end just before tailcall node.
3245 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3246 DAG.getIntPtrConstant(0, true), InFlag, dl);
3247 InFlag = Chain.getValue(1);
3251 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3252 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3253 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3254 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3255 const PPCSubtarget &PPCSubTarget) {
3257 bool isPPC64 = PPCSubTarget.isPPC64();
3258 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3260 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3261 NodeTys.push_back(MVT::Other); // Returns a chain
3262 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3264 unsigned CallOpc = PPCISD::CALL;
3266 bool needIndirectCall = true;
3267 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3268 // If this is an absolute destination address, use the munged value.
3269 Callee = SDValue(Dest, 0);
3270 needIndirectCall = false;
3273 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3274 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3275 // Use indirect calls for ALL functions calls in JIT mode, since the
3276 // far-call stubs may be outside relocation limits for a BL instruction.
3277 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3278 unsigned OpFlags = 0;
3279 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3280 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3281 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3282 (G->getGlobal()->isDeclaration() ||
3283 G->getGlobal()->isWeakForLinker())) {
3284 // PC-relative references to external symbols should go through $stub,
3285 // unless we're building with the leopard linker or later, which
3286 // automatically synthesizes these stubs.
3287 OpFlags = PPCII::MO_DARWIN_STUB;
3290 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3291 // every direct call is) turn it into a TargetGlobalAddress /
3292 // TargetExternalSymbol node so that legalize doesn't hack it.
3293 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3294 Callee.getValueType(),
3296 needIndirectCall = false;
3300 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3301 unsigned char OpFlags = 0;
3303 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3304 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3305 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3306 // PC-relative references to external symbols should go through $stub,
3307 // unless we're building with the leopard linker or later, which
3308 // automatically synthesizes these stubs.
3309 OpFlags = PPCII::MO_DARWIN_STUB;
3312 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3314 needIndirectCall = false;
3317 if (needIndirectCall) {
3318 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3319 // to do the call, we can't use PPCISD::CALL.
3320 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3322 if (isSVR4ABI && isPPC64) {
3323 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3324 // entry point, but to the function descriptor (the function entry point
3325 // address is part of the function descriptor though).
3326 // The function descriptor is a three doubleword structure with the
3327 // following fields: function entry point, TOC base address and
3328 // environment pointer.
3329 // Thus for a call through a function pointer, the following actions need
3331 // 1. Save the TOC of the caller in the TOC save area of its stack
3332 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3333 // 2. Load the address of the function entry point from the function
3335 // 3. Load the TOC of the callee from the function descriptor into r2.
3336 // 4. Load the environment pointer from the function descriptor into
3338 // 5. Branch to the function entry point address.
3339 // 6. On return of the callee, the TOC of the caller needs to be
3340 // restored (this is done in FinishCall()).
3342 // All those operations are flagged together to ensure that no other
3343 // operations can be scheduled in between. E.g. without flagging the
3344 // operations together, a TOC access in the caller could be scheduled
3345 // between the load of the callee TOC and the branch to the callee, which
3346 // results in the TOC access going through the TOC of the callee instead
3347 // of going through the TOC of the caller, which leads to incorrect code.
3349 // Load the address of the function entry point from the function
3351 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3352 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3353 InFlag.getNode() ? 3 : 2);
3354 Chain = LoadFuncPtr.getValue(1);
3355 InFlag = LoadFuncPtr.getValue(2);
3357 // Load environment pointer into r11.
3358 // Offset of the environment pointer within the function descriptor.
3359 SDValue PtrOff = DAG.getIntPtrConstant(16);
3361 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3362 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3364 Chain = LoadEnvPtr.getValue(1);
3365 InFlag = LoadEnvPtr.getValue(2);
3367 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3369 Chain = EnvVal.getValue(0);
3370 InFlag = EnvVal.getValue(1);
3372 // Load TOC of the callee into r2. We are using a target-specific load
3373 // with r2 hard coded, because the result of a target-independent load
3374 // would never go directly into r2, since r2 is a reserved register (which
3375 // prevents the register allocator from allocating it), resulting in an
3376 // additional register being allocated and an unnecessary move instruction
3378 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3379 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3381 Chain = LoadTOCPtr.getValue(0);
3382 InFlag = LoadTOCPtr.getValue(1);
3384 MTCTROps[0] = Chain;
3385 MTCTROps[1] = LoadFuncPtr;
3386 MTCTROps[2] = InFlag;
3389 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3390 2 + (InFlag.getNode() != 0));
3391 InFlag = Chain.getValue(1);
3394 NodeTys.push_back(MVT::Other);
3395 NodeTys.push_back(MVT::Glue);
3396 Ops.push_back(Chain);
3397 CallOpc = PPCISD::BCTRL;
3399 // Add use of X11 (holding environment pointer)
3400 if (isSVR4ABI && isPPC64)
3401 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3402 // Add CTR register as callee so a bctr can be emitted later.
3404 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3407 // If this is a direct call, pass the chain and the callee.
3408 if (Callee.getNode()) {
3409 Ops.push_back(Chain);
3410 Ops.push_back(Callee);
3412 // If this is a tail call add stack pointer delta.
3414 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3416 // Add argument registers to the end of the list so that they are known live
3418 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3419 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3420 RegsToPass[i].second.getValueType()));
3426 bool isLocalCall(const SDValue &Callee)
3428 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3429 return !G->getGlobal()->isDeclaration() &&
3430 !G->getGlobal()->isWeakForLinker();
3435 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3436 CallingConv::ID CallConv, bool isVarArg,
3437 const SmallVectorImpl<ISD::InputArg> &Ins,
3438 SDLoc dl, SelectionDAG &DAG,
3439 SmallVectorImpl<SDValue> &InVals) const {
3441 SmallVector<CCValAssign, 16> RVLocs;
3442 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3443 getTargetMachine(), RVLocs, *DAG.getContext());
3444 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3446 // Copy all of the result registers out of their specified physreg.
3447 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3448 CCValAssign &VA = RVLocs[i];
3449 assert(VA.isRegLoc() && "Can only return in registers!");
3451 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3452 VA.getLocReg(), VA.getLocVT(), InFlag);
3453 Chain = Val.getValue(1);
3454 InFlag = Val.getValue(2);
3456 switch (VA.getLocInfo()) {
3457 default: llvm_unreachable("Unknown loc info!");
3458 case CCValAssign::Full: break;
3459 case CCValAssign::AExt:
3460 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3462 case CCValAssign::ZExt:
3463 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3464 DAG.getValueType(VA.getValVT()));
3465 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3467 case CCValAssign::SExt:
3468 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3469 DAG.getValueType(VA.getValVT()));
3470 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3474 InVals.push_back(Val);
3481 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3482 bool isTailCall, bool isVarArg,
3484 SmallVector<std::pair<unsigned, SDValue>, 8>
3486 SDValue InFlag, SDValue Chain,
3488 int SPDiff, unsigned NumBytes,
3489 const SmallVectorImpl<ISD::InputArg> &Ins,
3490 SmallVectorImpl<SDValue> &InVals) const {
3491 std::vector<EVT> NodeTys;
3492 SmallVector<SDValue, 8> Ops;
3493 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3494 isTailCall, RegsToPass, Ops, NodeTys,
3497 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3498 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3499 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3501 // When performing tail call optimization the callee pops its arguments off
3502 // the stack. Account for this here so these bytes can be pushed back on in
3503 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3504 int BytesCalleePops =
3505 (CallConv == CallingConv::Fast &&
3506 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3508 // Add a register mask operand representing the call-preserved registers.
3509 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3510 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3511 assert(Mask && "Missing call preserved mask for calling convention");
3512 Ops.push_back(DAG.getRegisterMask(Mask));
3514 if (InFlag.getNode())
3515 Ops.push_back(InFlag);
3519 assert(((Callee.getOpcode() == ISD::Register &&
3520 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3521 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3522 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3523 isa<ConstantSDNode>(Callee)) &&
3524 "Expecting an global address, external symbol, absolute value or register");
3526 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3529 // Add a NOP immediately after the branch instruction when using the 64-bit
3530 // SVR4 ABI. At link time, if caller and callee are in a different module and
3531 // thus have a different TOC, the call will be replaced with a call to a stub
3532 // function which saves the current TOC, loads the TOC of the callee and
3533 // branches to the callee. The NOP will be replaced with a load instruction
3534 // which restores the TOC of the caller from the TOC save slot of the current
3535 // stack frame. If caller and callee belong to the same module (and have the
3536 // same TOC), the NOP will remain unchanged.
3538 bool needsTOCRestore = false;
3539 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3540 if (CallOpc == PPCISD::BCTRL) {
3541 // This is a call through a function pointer.
3542 // Restore the caller TOC from the save area into R2.
3543 // See PrepareCall() for more information about calls through function
3544 // pointers in the 64-bit SVR4 ABI.
3545 // We are using a target-specific load with r2 hard coded, because the
3546 // result of a target-independent load would never go directly into r2,
3547 // since r2 is a reserved register (which prevents the register allocator
3548 // from allocating it), resulting in an additional register being
3549 // allocated and an unnecessary move instruction being generated.
3550 needsTOCRestore = true;
3551 } else if ((CallOpc == PPCISD::CALL) &&
3552 (!isLocalCall(Callee) ||
3553 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3554 // Otherwise insert NOP for non-local calls.
3555 CallOpc = PPCISD::CALL_NOP;
3559 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3560 InFlag = Chain.getValue(1);
3562 if (needsTOCRestore) {
3563 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3564 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3565 InFlag = Chain.getValue(1);
3568 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3569 DAG.getIntPtrConstant(BytesCalleePops, true),
3572 InFlag = Chain.getValue(1);
3574 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3575 Ins, dl, DAG, InVals);
3579 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3580 SmallVectorImpl<SDValue> &InVals) const {
3581 SelectionDAG &DAG = CLI.DAG;
3583 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3584 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3585 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3586 SDValue Chain = CLI.Chain;
3587 SDValue Callee = CLI.Callee;
3588 bool &isTailCall = CLI.IsTailCall;
3589 CallingConv::ID CallConv = CLI.CallConv;
3590 bool isVarArg = CLI.IsVarArg;
3593 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3596 if (PPCSubTarget.isSVR4ABI()) {
3597 if (PPCSubTarget.isPPC64())
3598 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3599 isTailCall, Outs, OutVals, Ins,
3602 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3603 isTailCall, Outs, OutVals, Ins,
3607 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3608 isTailCall, Outs, OutVals, Ins,
3613 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3614 CallingConv::ID CallConv, bool isVarArg,
3616 const SmallVectorImpl<ISD::OutputArg> &Outs,
3617 const SmallVectorImpl<SDValue> &OutVals,
3618 const SmallVectorImpl<ISD::InputArg> &Ins,
3619 SDLoc dl, SelectionDAG &DAG,
3620 SmallVectorImpl<SDValue> &InVals) const {
3621 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3622 // of the 32-bit SVR4 ABI stack frame layout.
3624 assert((CallConv == CallingConv::C ||
3625 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3627 unsigned PtrByteSize = 4;
3629 MachineFunction &MF = DAG.getMachineFunction();
3631 // Mark this function as potentially containing a function that contains a
3632 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3633 // and restoring the callers stack pointer in this functions epilog. This is
3634 // done because by tail calling the called function might overwrite the value
3635 // in this function's (MF) stack pointer stack slot 0(SP).
3636 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3637 CallConv == CallingConv::Fast)
3638 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3640 // Count how many bytes are to be pushed on the stack, including the linkage
3641 // area, parameter list area and the part of the local variable space which
3642 // contains copies of aggregates which are passed by value.
3644 // Assign locations to all of the outgoing arguments.
3645 SmallVector<CCValAssign, 16> ArgLocs;
3646 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3647 getTargetMachine(), ArgLocs, *DAG.getContext());
3649 // Reserve space for the linkage area on the stack.
3650 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3653 // Handle fixed and variable vector arguments differently.
3654 // Fixed vector arguments go into registers as long as registers are
3655 // available. Variable vector arguments always go into memory.
3656 unsigned NumArgs = Outs.size();
3658 for (unsigned i = 0; i != NumArgs; ++i) {
3659 MVT ArgVT = Outs[i].VT;
3660 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3663 if (Outs[i].IsFixed) {
3664 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3667 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3673 errs() << "Call operand #" << i << " has unhandled type "
3674 << EVT(ArgVT).getEVTString() << "\n";
3676 llvm_unreachable(0);
3680 // All arguments are treated the same.
3681 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3684 // Assign locations to all of the outgoing aggregate by value arguments.
3685 SmallVector<CCValAssign, 16> ByValArgLocs;
3686 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3687 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3689 // Reserve stack space for the allocations in CCInfo.
3690 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3692 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3694 // Size of the linkage area, parameter list area and the part of the local
3695 // space variable where copies of aggregates which are passed by value are
3697 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3699 // Calculate by how many bytes the stack has to be adjusted in case of tail
3700 // call optimization.
3701 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3703 // Adjust the stack pointer for the new arguments...
3704 // These operations are automatically eliminated by the prolog/epilog pass
3705 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3707 SDValue CallSeqStart = Chain;
3709 // Load the return address and frame pointer so it can be moved somewhere else
3712 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3715 // Set up a copy of the stack pointer for use loading and storing any
3716 // arguments that may not fit in the registers available for argument
3718 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3720 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3721 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3722 SmallVector<SDValue, 8> MemOpChains;
3724 bool seenFloatArg = false;
3725 // Walk the register/memloc assignments, inserting copies/loads.
3726 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3729 CCValAssign &VA = ArgLocs[i];
3730 SDValue Arg = OutVals[i];
3731 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3733 if (Flags.isByVal()) {
3734 // Argument is an aggregate which is passed by value, thus we need to
3735 // create a copy of it in the local variable space of the current stack
3736 // frame (which is the stack frame of the caller) and pass the address of
3737 // this copy to the callee.
3738 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3739 CCValAssign &ByValVA = ByValArgLocs[j++];
3740 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3742 // Memory reserved in the local variable space of the callers stack frame.
3743 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3745 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3746 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3748 // Create a copy of the argument in the local area of the current
3750 SDValue MemcpyCall =
3751 CreateCopyOfByValArgument(Arg, PtrOff,
3752 CallSeqStart.getNode()->getOperand(0),
3755 // This must go outside the CALLSEQ_START..END.
3756 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3757 CallSeqStart.getNode()->getOperand(1),
3759 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3760 NewCallSeqStart.getNode());
3761 Chain = CallSeqStart = NewCallSeqStart;
3763 // Pass the address of the aggregate copy on the stack either in a
3764 // physical register or in the parameter list area of the current stack
3765 // frame to the callee.
3769 if (VA.isRegLoc()) {
3770 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3771 // Put argument in a physical register.
3772 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3774 // Put argument in the parameter list area of the current stack frame.
3775 assert(VA.isMemLoc());
3776 unsigned LocMemOffset = VA.getLocMemOffset();
3779 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3780 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3782 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3783 MachinePointerInfo(),
3786 // Calculate and remember argument location.
3787 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3793 if (!MemOpChains.empty())
3794 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3795 &MemOpChains[0], MemOpChains.size());
3797 // Build a sequence of copy-to-reg nodes chained together with token chain
3798 // and flag operands which copy the outgoing args into the appropriate regs.
3800 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3801 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3802 RegsToPass[i].second, InFlag);
3803 InFlag = Chain.getValue(1);
3806 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3809 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3810 SDValue Ops[] = { Chain, InFlag };
3812 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3813 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3815 InFlag = Chain.getValue(1);
3819 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3820 false, TailCallArguments);
3822 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3823 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3827 // Copy an argument into memory, being careful to do this outside the
3828 // call sequence for the call to which the argument belongs.
3830 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3831 SDValue CallSeqStart,
3832 ISD::ArgFlagsTy Flags,
3835 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3836 CallSeqStart.getNode()->getOperand(0),
3838 // The MEMCPY must go outside the CALLSEQ_START..END.
3839 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3840 CallSeqStart.getNode()->getOperand(1),
3842 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3843 NewCallSeqStart.getNode());
3844 return NewCallSeqStart;
3848 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3849 CallingConv::ID CallConv, bool isVarArg,
3851 const SmallVectorImpl<ISD::OutputArg> &Outs,
3852 const SmallVectorImpl<SDValue> &OutVals,
3853 const SmallVectorImpl<ISD::InputArg> &Ins,
3854 SDLoc dl, SelectionDAG &DAG,
3855 SmallVectorImpl<SDValue> &InVals) const {
3857 unsigned NumOps = Outs.size();
3859 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3860 unsigned PtrByteSize = 8;
3862 MachineFunction &MF = DAG.getMachineFunction();
3864 // Mark this function as potentially containing a function that contains a
3865 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3866 // and restoring the callers stack pointer in this functions epilog. This is
3867 // done because by tail calling the called function might overwrite the value
3868 // in this function's (MF) stack pointer stack slot 0(SP).
3869 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3870 CallConv == CallingConv::Fast)
3871 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3873 unsigned nAltivecParamsAtEnd = 0;
3875 // Count how many bytes are to be pushed on the stack, including the linkage
3876 // area, and parameter passing area. We start with at least 48 bytes, which
3877 // is reserved space for [SP][CR][LR][3 x unused].
3878 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3881 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3882 Outs, OutVals, nAltivecParamsAtEnd);
3884 // Calculate by how many bytes the stack has to be adjusted in case of tail
3885 // call optimization.
3886 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3888 // To protect arguments on the stack from being clobbered in a tail call,
3889 // force all the loads to happen before doing any other lowering.
3891 Chain = DAG.getStackArgumentTokenFactor(Chain);
3893 // Adjust the stack pointer for the new arguments...
3894 // These operations are automatically eliminated by the prolog/epilog pass
3895 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3897 SDValue CallSeqStart = Chain;
3899 // Load the return address and frame pointer so it can be move somewhere else
3902 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3905 // Set up a copy of the stack pointer for use loading and storing any
3906 // arguments that may not fit in the registers available for argument
3908 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3910 // Figure out which arguments are going to go in registers, and which in
3911 // memory. Also, if this is a vararg function, floating point operations
3912 // must be stored to our stack, and loaded into integer regs as well, if
3913 // any integer regs are available for argument passing.
3914 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3915 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3917 static const uint16_t GPR[] = {
3918 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3919 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3921 static const uint16_t *FPR = GetFPR();
3923 static const uint16_t VR[] = {
3924 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3925 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3927 const unsigned NumGPRs = array_lengthof(GPR);
3928 const unsigned NumFPRs = 13;
3929 const unsigned NumVRs = array_lengthof(VR);
3931 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3932 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3934 SmallVector<SDValue, 8> MemOpChains;
3935 for (unsigned i = 0; i != NumOps; ++i) {
3936 SDValue Arg = OutVals[i];
3937 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3939 // PtrOff will be used to store the current argument to the stack if a
3940 // register cannot be found for it.
3943 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3945 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3947 // Promote integers to 64-bit values.
3948 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
3949 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3950 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3951 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3954 // FIXME memcpy is used way more than necessary. Correctness first.
3955 // Note: "by value" is code for passing a structure by value, not
3957 if (Flags.isByVal()) {
3958 // Note: Size includes alignment padding, so
3959 // struct x { short a; char b; }
3960 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3961 // These are the proper values we need for right-justifying the
3962 // aggregate in a parameter register.
3963 unsigned Size = Flags.getByValSize();
3965 // An empty aggregate parameter takes up no storage and no
3970 unsigned BVAlign = Flags.getByValAlign();
3972 if (BVAlign % PtrByteSize != 0)
3974 "ByVal alignment is not a multiple of the pointer size");
3976 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
3979 // All aggregates smaller than 8 bytes must be passed right-justified.
3980 if (Size==1 || Size==2 || Size==4) {
3981 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3982 if (GPR_idx != NumGPRs) {
3983 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3984 MachinePointerInfo(), VT,
3986 MemOpChains.push_back(Load.getValue(1));
3987 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3989 ArgOffset += PtrByteSize;
3994 if (GPR_idx == NumGPRs && Size < 8) {
3995 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3996 PtrOff.getValueType());
3997 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3998 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4001 ArgOffset += PtrByteSize;
4004 // Copy entire object into memory. There are cases where gcc-generated
4005 // code assumes it is there, even if it could be put entirely into
4006 // registers. (This is not what the doc says.)
4008 // FIXME: The above statement is likely due to a misunderstanding of the
4009 // documents. All arguments must be copied into the parameter area BY
4010 // THE CALLEE in the event that the callee takes the address of any
4011 // formal argument. That has not yet been implemented. However, it is
4012 // reasonable to use the stack area as a staging area for the register
4015 // Skip this for small aggregates, as we will use the same slot for a
4016 // right-justified copy, below.
4018 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4022 // When a register is available, pass a small aggregate right-justified.
4023 if (Size < 8 && GPR_idx != NumGPRs) {
4024 // The easiest way to get this right-justified in a register
4025 // is to copy the structure into the rightmost portion of a
4026 // local variable slot, then load the whole slot into the
4028 // FIXME: The memcpy seems to produce pretty awful code for
4029 // small aggregates, particularly for packed ones.
4030 // FIXME: It would be preferable to use the slot in the
4031 // parameter save area instead of a new local variable.
4032 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4033 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4034 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4038 // Load the slot into the register.
4039 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4040 MachinePointerInfo(),
4041 false, false, false, 0);
4042 MemOpChains.push_back(Load.getValue(1));
4043 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4045 // Done with this argument.
4046 ArgOffset += PtrByteSize;
4050 // For aggregates larger than PtrByteSize, copy the pieces of the
4051 // object that fit into registers from the parameter save area.
4052 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4053 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4054 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4055 if (GPR_idx != NumGPRs) {
4056 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4057 MachinePointerInfo(),
4058 false, false, false, 0);
4059 MemOpChains.push_back(Load.getValue(1));
4060 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4061 ArgOffset += PtrByteSize;
4063 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4070 switch (Arg.getSimpleValueType().SimpleTy) {
4071 default: llvm_unreachable("Unexpected ValueType for argument!");
4075 if (GPR_idx != NumGPRs) {
4076 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4078 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4079 true, isTailCall, false, MemOpChains,
4080 TailCallArguments, dl);
4082 ArgOffset += PtrByteSize;
4086 if (FPR_idx != NumFPRs) {
4087 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4090 // A single float or an aggregate containing only a single float
4091 // must be passed right-justified in the stack doubleword, and
4092 // in the GPR, if one is available.
4094 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4095 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4096 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4100 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4101 MachinePointerInfo(), false, false, 0);
4102 MemOpChains.push_back(Store);
4104 // Float varargs are always shadowed in available integer registers
4105 if (GPR_idx != NumGPRs) {
4106 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4107 MachinePointerInfo(), false, false,
4109 MemOpChains.push_back(Load.getValue(1));
4110 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4112 } else if (GPR_idx != NumGPRs)
4113 // If we have any FPRs remaining, we may also have GPRs remaining.
4116 // Single-precision floating-point values are mapped to the
4117 // second (rightmost) word of the stack doubleword.
4118 if (Arg.getValueType() == MVT::f32) {
4119 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4120 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4123 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4124 true, isTailCall, false, MemOpChains,
4125 TailCallArguments, dl);
4134 // These go aligned on the stack, or in the corresponding R registers
4135 // when within range. The Darwin PPC ABI doc claims they also go in
4136 // V registers; in fact gcc does this only for arguments that are
4137 // prototyped, not for those that match the ... We do it for all
4138 // arguments, seems to work.
4139 while (ArgOffset % 16 !=0) {
4140 ArgOffset += PtrByteSize;
4141 if (GPR_idx != NumGPRs)
4144 // We could elide this store in the case where the object fits
4145 // entirely in R registers. Maybe later.
4146 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4147 DAG.getConstant(ArgOffset, PtrVT));
4148 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4149 MachinePointerInfo(), false, false, 0);
4150 MemOpChains.push_back(Store);
4151 if (VR_idx != NumVRs) {
4152 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4153 MachinePointerInfo(),
4154 false, false, false, 0);
4155 MemOpChains.push_back(Load.getValue(1));
4156 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4159 for (unsigned i=0; i<16; i+=PtrByteSize) {
4160 if (GPR_idx == NumGPRs)
4162 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4163 DAG.getConstant(i, PtrVT));
4164 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4165 false, false, false, 0);
4166 MemOpChains.push_back(Load.getValue(1));
4167 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4172 // Non-varargs Altivec params generally go in registers, but have
4173 // stack space allocated at the end.
4174 if (VR_idx != NumVRs) {
4175 // Doesn't have GPR space allocated.
4176 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4178 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4179 true, isTailCall, true, MemOpChains,
4180 TailCallArguments, dl);
4187 if (!MemOpChains.empty())
4188 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4189 &MemOpChains[0], MemOpChains.size());
4191 // Check if this is an indirect call (MTCTR/BCTRL).
4192 // See PrepareCall() for more information about calls through function
4193 // pointers in the 64-bit SVR4 ABI.
4195 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4196 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4197 !isBLACompatibleAddress(Callee, DAG)) {
4198 // Load r2 into a virtual register and store it to the TOC save area.
4199 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4200 // TOC save area offset.
4201 SDValue PtrOff = DAG.getIntPtrConstant(40);
4202 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4203 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4205 // R12 must contain the address of an indirect callee. This does not
4206 // mean the MTCTR instruction must use R12; it's easier to model this
4207 // as an extra parameter, so do that.
4208 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4211 // Build a sequence of copy-to-reg nodes chained together with token chain
4212 // and flag operands which copy the outgoing args into the appropriate regs.
4214 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4215 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4216 RegsToPass[i].second, InFlag);
4217 InFlag = Chain.getValue(1);
4221 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4222 FPOp, true, TailCallArguments);
4224 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4225 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4230 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4231 CallingConv::ID CallConv, bool isVarArg,
4233 const SmallVectorImpl<ISD::OutputArg> &Outs,
4234 const SmallVectorImpl<SDValue> &OutVals,
4235 const SmallVectorImpl<ISD::InputArg> &Ins,
4236 SDLoc dl, SelectionDAG &DAG,
4237 SmallVectorImpl<SDValue> &InVals) const {
4239 unsigned NumOps = Outs.size();
4241 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4242 bool isPPC64 = PtrVT == MVT::i64;
4243 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4245 MachineFunction &MF = DAG.getMachineFunction();
4247 // Mark this function as potentially containing a function that contains a
4248 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4249 // and restoring the callers stack pointer in this functions epilog. This is
4250 // done because by tail calling the called function might overwrite the value
4251 // in this function's (MF) stack pointer stack slot 0(SP).
4252 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4253 CallConv == CallingConv::Fast)
4254 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4256 unsigned nAltivecParamsAtEnd = 0;
4258 // Count how many bytes are to be pushed on the stack, including the linkage
4259 // area, and parameter passing area. We start with 24/48 bytes, which is
4260 // prereserved space for [SP][CR][LR][3 x unused].
4262 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4264 nAltivecParamsAtEnd);
4266 // Calculate by how many bytes the stack has to be adjusted in case of tail
4267 // call optimization.
4268 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4270 // To protect arguments on the stack from being clobbered in a tail call,
4271 // force all the loads to happen before doing any other lowering.
4273 Chain = DAG.getStackArgumentTokenFactor(Chain);
4275 // Adjust the stack pointer for the new arguments...
4276 // These operations are automatically eliminated by the prolog/epilog pass
4277 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4279 SDValue CallSeqStart = Chain;
4281 // Load the return address and frame pointer so it can be move somewhere else
4284 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4287 // Set up a copy of the stack pointer for use loading and storing any
4288 // arguments that may not fit in the registers available for argument
4292 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4294 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4296 // Figure out which arguments are going to go in registers, and which in
4297 // memory. Also, if this is a vararg function, floating point operations
4298 // must be stored to our stack, and loaded into integer regs as well, if
4299 // any integer regs are available for argument passing.
4300 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4301 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4303 static const uint16_t GPR_32[] = { // 32-bit registers.
4304 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4305 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4307 static const uint16_t GPR_64[] = { // 64-bit registers.
4308 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4309 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4311 static const uint16_t *FPR = GetFPR();
4313 static const uint16_t VR[] = {
4314 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4315 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4317 const unsigned NumGPRs = array_lengthof(GPR_32);
4318 const unsigned NumFPRs = 13;
4319 const unsigned NumVRs = array_lengthof(VR);
4321 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4323 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4324 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4326 SmallVector<SDValue, 8> MemOpChains;
4327 for (unsigned i = 0; i != NumOps; ++i) {
4328 SDValue Arg = OutVals[i];
4329 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4331 // PtrOff will be used to store the current argument to the stack if a
4332 // register cannot be found for it.
4335 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4337 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4339 // On PPC64, promote integers to 64-bit values.
4340 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4341 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4342 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4343 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4346 // FIXME memcpy is used way more than necessary. Correctness first.
4347 // Note: "by value" is code for passing a structure by value, not
4349 if (Flags.isByVal()) {
4350 unsigned Size = Flags.getByValSize();
4351 // Very small objects are passed right-justified. Everything else is
4352 // passed left-justified.
4353 if (Size==1 || Size==2) {
4354 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4355 if (GPR_idx != NumGPRs) {
4356 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4357 MachinePointerInfo(), VT,
4359 MemOpChains.push_back(Load.getValue(1));
4360 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4362 ArgOffset += PtrByteSize;
4364 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4365 PtrOff.getValueType());
4366 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4367 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4370 ArgOffset += PtrByteSize;
4374 // Copy entire object into memory. There are cases where gcc-generated
4375 // code assumes it is there, even if it could be put entirely into
4376 // registers. (This is not what the doc says.)
4377 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4381 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4382 // copy the pieces of the object that fit into registers from the
4383 // parameter save area.
4384 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4385 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4386 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4387 if (GPR_idx != NumGPRs) {
4388 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4389 MachinePointerInfo(),
4390 false, false, false, 0);
4391 MemOpChains.push_back(Load.getValue(1));
4392 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4393 ArgOffset += PtrByteSize;
4395 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4402 switch (Arg.getSimpleValueType().SimpleTy) {
4403 default: llvm_unreachable("Unexpected ValueType for argument!");
4407 if (GPR_idx != NumGPRs) {
4408 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4410 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4411 isPPC64, isTailCall, false, MemOpChains,
4412 TailCallArguments, dl);
4414 ArgOffset += PtrByteSize;
4418 if (FPR_idx != NumFPRs) {
4419 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4422 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4423 MachinePointerInfo(), false, false, 0);
4424 MemOpChains.push_back(Store);
4426 // Float varargs are always shadowed in available integer registers
4427 if (GPR_idx != NumGPRs) {
4428 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4429 MachinePointerInfo(), false, false,
4431 MemOpChains.push_back(Load.getValue(1));
4432 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4434 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4435 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4436 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4437 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4438 MachinePointerInfo(),
4439 false, false, false, 0);
4440 MemOpChains.push_back(Load.getValue(1));
4441 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4444 // If we have any FPRs remaining, we may also have GPRs remaining.
4445 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4447 if (GPR_idx != NumGPRs)
4449 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4450 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4454 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4455 isPPC64, isTailCall, false, MemOpChains,
4456 TailCallArguments, dl);
4460 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4467 // These go aligned on the stack, or in the corresponding R registers
4468 // when within range. The Darwin PPC ABI doc claims they also go in
4469 // V registers; in fact gcc does this only for arguments that are
4470 // prototyped, not for those that match the ... We do it for all
4471 // arguments, seems to work.
4472 while (ArgOffset % 16 !=0) {
4473 ArgOffset += PtrByteSize;
4474 if (GPR_idx != NumGPRs)
4477 // We could elide this store in the case where the object fits
4478 // entirely in R registers. Maybe later.
4479 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4480 DAG.getConstant(ArgOffset, PtrVT));
4481 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4482 MachinePointerInfo(), false, false, 0);
4483 MemOpChains.push_back(Store);
4484 if (VR_idx != NumVRs) {
4485 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4486 MachinePointerInfo(),
4487 false, false, false, 0);
4488 MemOpChains.push_back(Load.getValue(1));
4489 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4492 for (unsigned i=0; i<16; i+=PtrByteSize) {
4493 if (GPR_idx == NumGPRs)
4495 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4496 DAG.getConstant(i, PtrVT));
4497 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4498 false, false, false, 0);
4499 MemOpChains.push_back(Load.getValue(1));
4500 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4505 // Non-varargs Altivec params generally go in registers, but have
4506 // stack space allocated at the end.
4507 if (VR_idx != NumVRs) {
4508 // Doesn't have GPR space allocated.
4509 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4510 } else if (nAltivecParamsAtEnd==0) {
4511 // We are emitting Altivec params in order.
4512 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4513 isPPC64, isTailCall, true, MemOpChains,
4514 TailCallArguments, dl);
4520 // If all Altivec parameters fit in registers, as they usually do,
4521 // they get stack space following the non-Altivec parameters. We
4522 // don't track this here because nobody below needs it.
4523 // If there are more Altivec parameters than fit in registers emit
4525 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4527 // Offset is aligned; skip 1st 12 params which go in V registers.
4528 ArgOffset = ((ArgOffset+15)/16)*16;
4530 for (unsigned i = 0; i != NumOps; ++i) {
4531 SDValue Arg = OutVals[i];
4532 EVT ArgType = Outs[i].VT;
4533 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4534 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4537 // We are emitting Altivec params in order.
4538 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4539 isPPC64, isTailCall, true, MemOpChains,
4540 TailCallArguments, dl);
4547 if (!MemOpChains.empty())
4548 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4549 &MemOpChains[0], MemOpChains.size());
4551 // On Darwin, R12 must contain the address of an indirect callee. This does
4552 // not mean the MTCTR instruction must use R12; it's easier to model this as
4553 // an extra parameter, so do that.
4555 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4556 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4557 !isBLACompatibleAddress(Callee, DAG))
4558 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4559 PPC::R12), Callee));
4561 // Build a sequence of copy-to-reg nodes chained together with token chain
4562 // and flag operands which copy the outgoing args into the appropriate regs.
4564 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4565 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4566 RegsToPass[i].second, InFlag);
4567 InFlag = Chain.getValue(1);
4571 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4572 FPOp, true, TailCallArguments);
4574 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4575 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4580 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4581 MachineFunction &MF, bool isVarArg,
4582 const SmallVectorImpl<ISD::OutputArg> &Outs,
4583 LLVMContext &Context) const {
4584 SmallVector<CCValAssign, 16> RVLocs;
4585 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4587 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4591 PPCTargetLowering::LowerReturn(SDValue Chain,
4592 CallingConv::ID CallConv, bool isVarArg,
4593 const SmallVectorImpl<ISD::OutputArg> &Outs,
4594 const SmallVectorImpl<SDValue> &OutVals,
4595 SDLoc dl, SelectionDAG &DAG) const {
4597 SmallVector<CCValAssign, 16> RVLocs;
4598 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4599 getTargetMachine(), RVLocs, *DAG.getContext());
4600 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4603 SmallVector<SDValue, 4> RetOps(1, Chain);
4605 // Copy the result values into the output registers.
4606 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4607 CCValAssign &VA = RVLocs[i];
4608 assert(VA.isRegLoc() && "Can only return in registers!");
4610 SDValue Arg = OutVals[i];
4612 switch (VA.getLocInfo()) {
4613 default: llvm_unreachable("Unknown loc info!");
4614 case CCValAssign::Full: break;
4615 case CCValAssign::AExt:
4616 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4618 case CCValAssign::ZExt:
4619 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4621 case CCValAssign::SExt:
4622 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4626 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4627 Flag = Chain.getValue(1);
4628 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4631 RetOps[0] = Chain; // Update chain.
4633 // Add the flag if we have it.
4635 RetOps.push_back(Flag);
4637 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4638 &RetOps[0], RetOps.size());
4641 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4642 const PPCSubtarget &Subtarget) const {
4643 // When we pop the dynamic allocation we need to restore the SP link.
4646 // Get the corect type for pointers.
4647 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4649 // Construct the stack pointer operand.
4650 bool isPPC64 = Subtarget.isPPC64();
4651 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4652 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4654 // Get the operands for the STACKRESTORE.
4655 SDValue Chain = Op.getOperand(0);
4656 SDValue SaveSP = Op.getOperand(1);
4658 // Load the old link SP.
4659 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4660 MachinePointerInfo(),
4661 false, false, false, 0);
4663 // Restore the stack pointer.
4664 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4666 // Store the old link SP.
4667 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4674 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4675 MachineFunction &MF = DAG.getMachineFunction();
4676 bool isPPC64 = PPCSubTarget.isPPC64();
4677 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4678 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4680 // Get current frame pointer save index. The users of this index will be
4681 // primarily DYNALLOC instructions.
4682 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4683 int RASI = FI->getReturnAddrSaveIndex();
4685 // If the frame pointer save index hasn't been defined yet.
4687 // Find out what the fix offset of the frame pointer save area.
4688 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4689 // Allocate the frame index for frame pointer save area.
4690 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4692 FI->setReturnAddrSaveIndex(RASI);
4694 return DAG.getFrameIndex(RASI, PtrVT);
4698 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4699 MachineFunction &MF = DAG.getMachineFunction();
4700 bool isPPC64 = PPCSubTarget.isPPC64();
4701 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4702 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4704 // Get current frame pointer save index. The users of this index will be
4705 // primarily DYNALLOC instructions.
4706 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4707 int FPSI = FI->getFramePointerSaveIndex();
4709 // If the frame pointer save index hasn't been defined yet.
4711 // Find out what the fix offset of the frame pointer save area.
4712 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4715 // Allocate the frame index for frame pointer save area.
4716 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4718 FI->setFramePointerSaveIndex(FPSI);
4720 return DAG.getFrameIndex(FPSI, PtrVT);
4723 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4725 const PPCSubtarget &Subtarget) const {
4727 SDValue Chain = Op.getOperand(0);
4728 SDValue Size = Op.getOperand(1);
4731 // Get the corect type for pointers.
4732 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4734 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4735 DAG.getConstant(0, PtrVT), Size);
4736 // Construct a node for the frame pointer save index.
4737 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4738 // Build a DYNALLOC node.
4739 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4740 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4741 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4744 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4745 SelectionDAG &DAG) const {
4747 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4748 DAG.getVTList(MVT::i32, MVT::Other),
4749 Op.getOperand(0), Op.getOperand(1));
4752 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4753 SelectionDAG &DAG) const {
4755 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4756 Op.getOperand(0), Op.getOperand(1));
4759 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4760 assert(Op.getValueType() == MVT::i1 &&
4761 "Custom lowering only for i1 loads");
4763 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4766 LoadSDNode *LD = cast<LoadSDNode>(Op);
4768 SDValue Chain = LD->getChain();
4769 SDValue BasePtr = LD->getBasePtr();
4770 MachineMemOperand *MMO = LD->getMemOperand();
4772 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4773 BasePtr, MVT::i8, MMO);
4774 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4776 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4777 return DAG.getMergeValues(Ops, 2, dl);
4780 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4781 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4782 "Custom lowering only for i1 stores");
4784 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4787 StoreSDNode *ST = cast<StoreSDNode>(Op);
4789 SDValue Chain = ST->getChain();
4790 SDValue BasePtr = ST->getBasePtr();
4791 SDValue Value = ST->getValue();
4792 MachineMemOperand *MMO = ST->getMemOperand();
4794 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4795 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4798 // FIXME: Remove this once the ANDI glue bug is fixed:
4799 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4800 assert(Op.getValueType() == MVT::i1 &&
4801 "Custom lowering only for i1 results");
4804 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4808 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4810 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4811 // Not FP? Not a fsel.
4812 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4813 !Op.getOperand(2).getValueType().isFloatingPoint())
4816 // We might be able to do better than this under some circumstances, but in
4817 // general, fsel-based lowering of select is a finite-math-only optimization.
4818 // For more information, see section F.3 of the 2.06 ISA specification.
4819 if (!DAG.getTarget().Options.NoInfsFPMath ||
4820 !DAG.getTarget().Options.NoNaNsFPMath)
4823 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4825 EVT ResVT = Op.getValueType();
4826 EVT CmpVT = Op.getOperand(0).getValueType();
4827 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4828 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4831 // If the RHS of the comparison is a 0.0, we don't need to do the
4832 // subtraction at all.
4834 if (isFloatingPointZero(RHS))
4836 default: break; // SETUO etc aren't handled by fsel.
4840 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4841 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4842 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4843 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4844 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4845 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4846 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4849 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4852 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4853 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4854 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4857 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4860 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4861 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4862 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4863 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4868 default: break; // SETUO etc aren't handled by fsel.
4872 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4873 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4874 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4875 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4876 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4877 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4878 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4879 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
4882 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4883 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4884 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4885 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4888 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4889 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4890 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4891 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4894 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4895 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4896 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4897 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4900 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4901 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4902 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4903 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4908 // FIXME: Split this code up when LegalizeDAGTypes lands.
4909 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4911 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4912 SDValue Src = Op.getOperand(0);
4913 if (Src.getValueType() == MVT::f32)
4914 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4917 switch (Op.getSimpleValueType().SimpleTy) {
4918 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4920 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4921 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
4926 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
4927 "i64 FP_TO_UINT is supported only with FPCVT");
4928 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
4934 // Convert the FP value to an int value through memory.
4935 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
4936 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
4937 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
4938 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
4939 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
4941 // Emit a store to the stack slot.
4944 MachineFunction &MF = DAG.getMachineFunction();
4945 MachineMemOperand *MMO =
4946 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
4947 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
4948 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
4949 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
4952 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4953 MPI, false, false, 0);
4955 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4957 if (Op.getValueType() == MVT::i32 && !i32Stack) {
4958 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4959 DAG.getConstant(4, FIPtr.getValueType()));
4960 MPI = MachinePointerInfo();
4963 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
4964 false, false, false, 0);
4967 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
4968 SelectionDAG &DAG) const {
4970 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4971 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4974 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
4975 "UINT_TO_FP is supported only with FPCVT");
4977 // If we have FCFIDS, then use it when converting to single-precision.
4978 // Otherwise, convert to double-precision and then round.
4979 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4980 (Op.getOpcode() == ISD::UINT_TO_FP ?
4981 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
4982 (Op.getOpcode() == ISD::UINT_TO_FP ?
4983 PPCISD::FCFIDU : PPCISD::FCFID);
4984 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4985 MVT::f32 : MVT::f64;
4987 if (Op.getOperand(0).getValueType() == MVT::i64) {
4988 SDValue SINT = Op.getOperand(0);
4989 // When converting to single-precision, we actually need to convert
4990 // to double-precision first and then round to single-precision.
4991 // To avoid double-rounding effects during that operation, we have
4992 // to prepare the input operand. Bits that might be truncated when
4993 // converting to double-precision are replaced by a bit that won't
4994 // be lost at this stage, but is below the single-precision rounding
4997 // However, if -enable-unsafe-fp-math is in effect, accept double
4998 // rounding to avoid the extra overhead.
4999 if (Op.getValueType() == MVT::f32 &&
5000 !PPCSubTarget.hasFPCVT() &&
5001 !DAG.getTarget().Options.UnsafeFPMath) {
5003 // Twiddle input to make sure the low 11 bits are zero. (If this
5004 // is the case, we are guaranteed the value will fit into the 53 bit
5005 // mantissa of an IEEE double-precision value without rounding.)
5006 // If any of those low 11 bits were not zero originally, make sure
5007 // bit 12 (value 2048) is set instead, so that the final rounding
5008 // to single-precision gets the correct result.
5009 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5010 SINT, DAG.getConstant(2047, MVT::i64));
5011 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5012 Round, DAG.getConstant(2047, MVT::i64));
5013 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5014 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5015 Round, DAG.getConstant(-2048, MVT::i64));
5017 // However, we cannot use that value unconditionally: if the magnitude
5018 // of the input value is small, the bit-twiddling we did above might
5019 // end up visibly changing the output. Fortunately, in that case, we
5020 // don't need to twiddle bits since the original input will convert
5021 // exactly to double-precision floating-point already. Therefore,
5022 // construct a conditional to use the original value if the top 11
5023 // bits are all sign-bit copies, and use the rounded value computed
5025 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5026 SINT, DAG.getConstant(53, MVT::i32));
5027 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5028 Cond, DAG.getConstant(1, MVT::i64));
5029 Cond = DAG.getSetCC(dl, MVT::i32,
5030 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5032 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5035 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5036 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5038 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5039 FP = DAG.getNode(ISD::FP_ROUND, dl,
5040 MVT::f32, FP, DAG.getIntPtrConstant(0));
5044 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5045 "Unhandled INT_TO_FP type in custom expander!");
5046 // Since we only generate this in 64-bit mode, we can take advantage of
5047 // 64-bit registers. In particular, sign extend the input value into the
5048 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5049 // then lfd it and fcfid it.
5050 MachineFunction &MF = DAG.getMachineFunction();
5051 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5052 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5055 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5056 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5057 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5059 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5060 MachinePointerInfo::getFixedStack(FrameIdx),
5063 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5064 "Expected an i32 store");
5065 MachineMemOperand *MMO =
5066 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5067 MachineMemOperand::MOLoad, 4, 4);
5068 SDValue Ops[] = { Store, FIdx };
5069 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5070 PPCISD::LFIWZX : PPCISD::LFIWAX,
5071 dl, DAG.getVTList(MVT::f64, MVT::Other),
5072 Ops, 2, MVT::i32, MMO);
5074 assert(PPCSubTarget.isPPC64() &&
5075 "i32->FP without LFIWAX supported only on PPC64");
5077 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5078 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5080 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5083 // STD the extended value into the stack slot.
5084 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5085 MachinePointerInfo::getFixedStack(FrameIdx),
5088 // Load the value as a double.
5089 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5090 MachinePointerInfo::getFixedStack(FrameIdx),
5091 false, false, false, 0);
5094 // FCFID it and return it.
5095 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5096 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5097 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5101 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5102 SelectionDAG &DAG) const {
5105 The rounding mode is in bits 30:31 of FPSR, and has the following
5112 FLT_ROUNDS, on the other hand, expects the following:
5119 To perform the conversion, we do:
5120 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5123 MachineFunction &MF = DAG.getMachineFunction();
5124 EVT VT = Op.getValueType();
5125 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5126 SDValue MFFSreg, InFlag;
5128 // Save FP Control Word to register
5130 MVT::f64, // return register
5131 MVT::Glue // unused in this context
5133 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5135 // Save FP register to stack slot
5136 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5137 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5138 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5139 StackSlot, MachinePointerInfo(), false, false,0);
5141 // Load FP Control Word from low 32 bits of stack slot.
5142 SDValue Four = DAG.getConstant(4, PtrVT);
5143 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5144 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5145 false, false, false, 0);
5147 // Transform as necessary
5149 DAG.getNode(ISD::AND, dl, MVT::i32,
5150 CWD, DAG.getConstant(3, MVT::i32));
5152 DAG.getNode(ISD::SRL, dl, MVT::i32,
5153 DAG.getNode(ISD::AND, dl, MVT::i32,
5154 DAG.getNode(ISD::XOR, dl, MVT::i32,
5155 CWD, DAG.getConstant(3, MVT::i32)),
5156 DAG.getConstant(3, MVT::i32)),
5157 DAG.getConstant(1, MVT::i32));
5160 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5162 return DAG.getNode((VT.getSizeInBits() < 16 ?
5163 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5166 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5167 EVT VT = Op.getValueType();
5168 unsigned BitWidth = VT.getSizeInBits();
5170 assert(Op.getNumOperands() == 3 &&
5171 VT == Op.getOperand(1).getValueType() &&
5174 // Expand into a bunch of logical ops. Note that these ops
5175 // depend on the PPC behavior for oversized shift amounts.
5176 SDValue Lo = Op.getOperand(0);
5177 SDValue Hi = Op.getOperand(1);
5178 SDValue Amt = Op.getOperand(2);
5179 EVT AmtVT = Amt.getValueType();
5181 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5182 DAG.getConstant(BitWidth, AmtVT), Amt);
5183 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5184 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5185 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5186 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5187 DAG.getConstant(-BitWidth, AmtVT));
5188 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5189 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5190 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5191 SDValue OutOps[] = { OutLo, OutHi };
5192 return DAG.getMergeValues(OutOps, 2, dl);
5195 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5196 EVT VT = Op.getValueType();
5198 unsigned BitWidth = VT.getSizeInBits();
5199 assert(Op.getNumOperands() == 3 &&
5200 VT == Op.getOperand(1).getValueType() &&
5203 // Expand into a bunch of logical ops. Note that these ops
5204 // depend on the PPC behavior for oversized shift amounts.
5205 SDValue Lo = Op.getOperand(0);
5206 SDValue Hi = Op.getOperand(1);
5207 SDValue Amt = Op.getOperand(2);
5208 EVT AmtVT = Amt.getValueType();
5210 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5211 DAG.getConstant(BitWidth, AmtVT), Amt);
5212 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5213 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5214 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5215 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5216 DAG.getConstant(-BitWidth, AmtVT));
5217 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5218 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5219 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5220 SDValue OutOps[] = { OutLo, OutHi };
5221 return DAG.getMergeValues(OutOps, 2, dl);
5224 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5226 EVT VT = Op.getValueType();
5227 unsigned BitWidth = VT.getSizeInBits();
5228 assert(Op.getNumOperands() == 3 &&
5229 VT == Op.getOperand(1).getValueType() &&
5232 // Expand into a bunch of logical ops, followed by a select_cc.
5233 SDValue Lo = Op.getOperand(0);
5234 SDValue Hi = Op.getOperand(1);
5235 SDValue Amt = Op.getOperand(2);
5236 EVT AmtVT = Amt.getValueType();
5238 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5239 DAG.getConstant(BitWidth, AmtVT), Amt);
5240 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5241 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5242 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5243 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5244 DAG.getConstant(-BitWidth, AmtVT));
5245 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5246 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5247 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5248 Tmp4, Tmp6, ISD::SETLE);
5249 SDValue OutOps[] = { OutLo, OutHi };
5250 return DAG.getMergeValues(OutOps, 2, dl);
5253 //===----------------------------------------------------------------------===//
5254 // Vector related lowering.
5257 /// BuildSplatI - Build a canonical splati of Val with an element size of
5258 /// SplatSize. Cast the result to VT.
5259 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5260 SelectionDAG &DAG, SDLoc dl) {
5261 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5263 static const EVT VTys[] = { // canonical VT to use for each size.
5264 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5267 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5269 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5273 EVT CanonicalVT = VTys[SplatSize-1];
5275 // Build a canonical splat for this value.
5276 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5277 SmallVector<SDValue, 8> Ops;
5278 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5279 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5280 &Ops[0], Ops.size());
5281 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5284 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5285 /// specified intrinsic ID.
5286 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5287 SelectionDAG &DAG, SDLoc dl,
5288 EVT DestVT = MVT::Other) {
5289 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5290 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5291 DAG.getConstant(IID, MVT::i32), Op);
5294 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5295 /// specified intrinsic ID.
5296 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5297 SelectionDAG &DAG, SDLoc dl,
5298 EVT DestVT = MVT::Other) {
5299 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5300 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5301 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5304 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5305 /// specified intrinsic ID.
5306 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5307 SDValue Op2, SelectionDAG &DAG,
5308 SDLoc dl, EVT DestVT = MVT::Other) {
5309 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5310 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5311 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5315 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5316 /// amount. The result has the specified value type.
5317 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5318 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5319 // Force LHS/RHS to be the right type.
5320 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5321 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5324 for (unsigned i = 0; i != 16; ++i)
5326 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5327 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5330 // If this is a case we can't handle, return null and let the default
5331 // expansion code take care of it. If we CAN select this case, and if it
5332 // selects to a single instruction, return Op. Otherwise, if we can codegen
5333 // this case more efficiently than a constant pool load, lower it to the
5334 // sequence of ops that should be used.
5335 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5336 SelectionDAG &DAG) const {
5338 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5339 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5341 // Check if this is a splat of a constant value.
5342 APInt APSplatBits, APSplatUndef;
5343 unsigned SplatBitSize;
5345 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5346 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5349 unsigned SplatBits = APSplatBits.getZExtValue();
5350 unsigned SplatUndef = APSplatUndef.getZExtValue();
5351 unsigned SplatSize = SplatBitSize / 8;
5353 // First, handle single instruction cases.
5356 if (SplatBits == 0) {
5357 // Canonicalize all zero vectors to be v4i32.
5358 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5359 SDValue Z = DAG.getConstant(0, MVT::i32);
5360 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5361 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5366 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5367 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5369 if (SextVal >= -16 && SextVal <= 15)
5370 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5373 // Two instruction sequences.
5375 // If this value is in the range [-32,30] and is even, use:
5376 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5377 // If this value is in the range [17,31] and is odd, use:
5378 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5379 // If this value is in the range [-31,-17] and is odd, use:
5380 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5381 // Note the last two are three-instruction sequences.
5382 if (SextVal >= -32 && SextVal <= 31) {
5383 // To avoid having these optimizations undone by constant folding,
5384 // we convert to a pseudo that will be expanded later into one of
5386 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5387 EVT VT = Op.getValueType();
5388 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5389 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5390 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5393 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5394 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5396 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5397 // Make -1 and vspltisw -1:
5398 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5400 // Make the VSLW intrinsic, computing 0x8000_0000.
5401 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5404 // xor by OnesV to invert it.
5405 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5406 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5409 // Check to see if this is a wide variety of vsplti*, binop self cases.
5410 static const signed char SplatCsts[] = {
5411 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5412 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5415 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5416 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5417 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5418 int i = SplatCsts[idx];
5420 // Figure out what shift amount will be used by altivec if shifted by i in
5422 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5424 // vsplti + shl self.
5425 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5426 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5427 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5428 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5429 Intrinsic::ppc_altivec_vslw
5431 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5432 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5435 // vsplti + srl self.
5436 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5437 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5438 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5439 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5440 Intrinsic::ppc_altivec_vsrw
5442 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5443 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5446 // vsplti + sra self.
5447 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5448 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5449 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5450 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5451 Intrinsic::ppc_altivec_vsraw
5453 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5454 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5457 // vsplti + rol self.
5458 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5459 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5460 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5461 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5462 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5463 Intrinsic::ppc_altivec_vrlw
5465 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5466 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5469 // t = vsplti c, result = vsldoi t, t, 1
5470 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5471 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5472 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5474 // t = vsplti c, result = vsldoi t, t, 2
5475 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5476 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5477 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5479 // t = vsplti c, result = vsldoi t, t, 3
5480 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5481 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5482 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5489 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5490 /// the specified operations to build the shuffle.
5491 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5492 SDValue RHS, SelectionDAG &DAG,
5494 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5495 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5496 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5499 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5511 if (OpNum == OP_COPY) {
5512 if (LHSID == (1*9+2)*9+3) return LHS;
5513 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5517 SDValue OpLHS, OpRHS;
5518 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5519 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5523 default: llvm_unreachable("Unknown i32 permute!");
5525 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5526 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5527 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5528 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5531 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5532 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5533 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5534 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5537 for (unsigned i = 0; i != 16; ++i)
5538 ShufIdxs[i] = (i&3)+0;
5541 for (unsigned i = 0; i != 16; ++i)
5542 ShufIdxs[i] = (i&3)+4;
5545 for (unsigned i = 0; i != 16; ++i)
5546 ShufIdxs[i] = (i&3)+8;
5549 for (unsigned i = 0; i != 16; ++i)
5550 ShufIdxs[i] = (i&3)+12;
5553 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5555 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5557 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5559 EVT VT = OpLHS.getValueType();
5560 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5561 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5562 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5563 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5566 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5567 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5568 /// return the code it can be lowered into. Worst case, it can always be
5569 /// lowered into a vperm.
5570 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5571 SelectionDAG &DAG) const {
5573 SDValue V1 = Op.getOperand(0);
5574 SDValue V2 = Op.getOperand(1);
5575 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5576 EVT VT = Op.getValueType();
5578 // Cases that are handled by instructions that take permute immediates
5579 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5580 // selected by the instruction selector.
5581 if (V2.getOpcode() == ISD::UNDEF) {
5582 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5583 PPC::isSplatShuffleMask(SVOp, 2) ||
5584 PPC::isSplatShuffleMask(SVOp, 4) ||
5585 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5586 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5587 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5588 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5589 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5590 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5591 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5592 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5593 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5598 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5599 // and produce a fixed permutation. If any of these match, do not lower to
5601 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5602 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5603 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5604 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5605 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5606 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5607 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5608 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5609 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5612 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5613 // perfect shuffle table to emit an optimal matching sequence.
5614 ArrayRef<int> PermMask = SVOp->getMask();
5616 unsigned PFIndexes[4];
5617 bool isFourElementShuffle = true;
5618 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5619 unsigned EltNo = 8; // Start out undef.
5620 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5621 if (PermMask[i*4+j] < 0)
5622 continue; // Undef, ignore it.
5624 unsigned ByteSource = PermMask[i*4+j];
5625 if ((ByteSource & 3) != j) {
5626 isFourElementShuffle = false;
5631 EltNo = ByteSource/4;
5632 } else if (EltNo != ByteSource/4) {
5633 isFourElementShuffle = false;
5637 PFIndexes[i] = EltNo;
5640 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5641 // perfect shuffle vector to determine if it is cost effective to do this as
5642 // discrete instructions, or whether we should use a vperm.
5643 if (isFourElementShuffle) {
5644 // Compute the index in the perfect shuffle table.
5645 unsigned PFTableIndex =
5646 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5648 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5649 unsigned Cost = (PFEntry >> 30);
5651 // Determining when to avoid vperm is tricky. Many things affect the cost
5652 // of vperm, particularly how many times the perm mask needs to be computed.
5653 // For example, if the perm mask can be hoisted out of a loop or is already
5654 // used (perhaps because there are multiple permutes with the same shuffle
5655 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5656 // the loop requires an extra register.
5658 // As a compromise, we only emit discrete instructions if the shuffle can be
5659 // generated in 3 or fewer operations. When we have loop information
5660 // available, if this block is within a loop, we should avoid using vperm
5661 // for 3-operation perms and use a constant pool load instead.
5663 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5666 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5667 // vector that will get spilled to the constant pool.
5668 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5670 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5671 // that it is in input element units, not in bytes. Convert now.
5672 EVT EltVT = V1.getValueType().getVectorElementType();
5673 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5675 SmallVector<SDValue, 16> ResultMask;
5676 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5677 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5679 for (unsigned j = 0; j != BytesPerElement; ++j)
5680 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5684 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5685 &ResultMask[0], ResultMask.size());
5686 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5689 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5690 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5691 /// information about the intrinsic.
5692 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5694 unsigned IntrinsicID =
5695 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5698 switch (IntrinsicID) {
5699 default: return false;
5700 // Comparison predicates.
5701 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5702 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5703 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5704 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5705 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5706 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5707 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5708 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5709 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5710 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5711 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5712 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5713 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5715 // Normal Comparisons.
5716 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5717 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5718 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5719 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5720 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5721 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5722 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5723 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5724 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5725 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5726 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5727 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5728 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5733 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5734 /// lower, do it, otherwise return null.
5735 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5736 SelectionDAG &DAG) const {
5737 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5738 // opcode number of the comparison.
5742 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5743 return SDValue(); // Don't custom lower most intrinsics.
5745 // If this is a non-dot comparison, make the VCMP node and we are done.
5747 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5748 Op.getOperand(1), Op.getOperand(2),
5749 DAG.getConstant(CompareOpc, MVT::i32));
5750 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5753 // Create the PPCISD altivec 'dot' comparison node.
5755 Op.getOperand(2), // LHS
5756 Op.getOperand(3), // RHS
5757 DAG.getConstant(CompareOpc, MVT::i32)
5759 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5760 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5762 // Now that we have the comparison, emit a copy from the CR to a GPR.
5763 // This is flagged to the above dot comparison.
5764 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5765 DAG.getRegister(PPC::CR6, MVT::i32),
5766 CompNode.getValue(1));
5768 // Unpack the result based on how the target uses it.
5769 unsigned BitNo; // Bit # of CR6.
5770 bool InvertBit; // Invert result?
5771 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5772 default: // Can't happen, don't crash on invalid number though.
5773 case 0: // Return the value of the EQ bit of CR6.
5774 BitNo = 0; InvertBit = false;
5776 case 1: // Return the inverted value of the EQ bit of CR6.
5777 BitNo = 0; InvertBit = true;
5779 case 2: // Return the value of the LT bit of CR6.
5780 BitNo = 2; InvertBit = false;
5782 case 3: // Return the inverted value of the LT bit of CR6.
5783 BitNo = 2; InvertBit = true;
5787 // Shift the bit into the low position.
5788 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5789 DAG.getConstant(8-(3-BitNo), MVT::i32));
5791 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5792 DAG.getConstant(1, MVT::i32));
5794 // If we are supposed to, toggle the bit.
5796 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5797 DAG.getConstant(1, MVT::i32));
5801 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5802 SelectionDAG &DAG) const {
5804 // Create a stack slot that is 16-byte aligned.
5805 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5806 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5807 EVT PtrVT = getPointerTy();
5808 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5810 // Store the input value into Value#0 of the stack slot.
5811 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5812 Op.getOperand(0), FIdx, MachinePointerInfo(),
5815 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5816 false, false, false, 0);
5819 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5821 if (Op.getValueType() == MVT::v4i32) {
5822 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5824 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5825 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5827 SDValue RHSSwap = // = vrlw RHS, 16
5828 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5830 // Shrinkify inputs to v8i16.
5831 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5832 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5833 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5835 // Low parts multiplied together, generating 32-bit results (we ignore the
5837 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5838 LHS, RHS, DAG, dl, MVT::v4i32);
5840 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5841 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5842 // Shift the high parts up 16 bits.
5843 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5845 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5846 } else if (Op.getValueType() == MVT::v8i16) {
5847 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5849 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5851 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5852 LHS, RHS, Zero, DAG, dl);
5853 } else if (Op.getValueType() == MVT::v16i8) {
5854 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5856 // Multiply the even 8-bit parts, producing 16-bit sums.
5857 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5858 LHS, RHS, DAG, dl, MVT::v8i16);
5859 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5861 // Multiply the odd 8-bit parts, producing 16-bit sums.
5862 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5863 LHS, RHS, DAG, dl, MVT::v8i16);
5864 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5866 // Merge the results together.
5868 for (unsigned i = 0; i != 8; ++i) {
5870 Ops[i*2+1] = 2*i+1+16;
5872 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5874 llvm_unreachable("Unknown mul to lower!");
5878 /// LowerOperation - Provide custom lowering hooks for some operations.
5880 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5881 switch (Op.getOpcode()) {
5882 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5883 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5884 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5885 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5886 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5887 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5888 case ISD::SETCC: return LowerSETCC(Op, DAG);
5889 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5890 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5892 return LowerVASTART(Op, DAG, PPCSubTarget);
5895 return LowerVAARG(Op, DAG, PPCSubTarget);
5898 return LowerVACOPY(Op, DAG, PPCSubTarget);
5900 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5901 case ISD::DYNAMIC_STACKALLOC:
5902 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5904 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5905 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5907 case ISD::LOAD: return LowerLOAD(Op, DAG);
5908 case ISD::STORE: return LowerSTORE(Op, DAG);
5909 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
5910 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5911 case ISD::FP_TO_UINT:
5912 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5914 case ISD::UINT_TO_FP:
5915 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5916 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5918 // Lower 64-bit shifts.
5919 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5920 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5921 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5923 // Vector-related lowering.
5924 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5925 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5926 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5927 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5928 case ISD::MUL: return LowerMUL(Op, DAG);
5930 // For counter-based loop handling.
5931 case ISD::INTRINSIC_W_CHAIN: return SDValue();
5933 // Frame & Return address.
5934 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5935 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5939 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5940 SmallVectorImpl<SDValue>&Results,
5941 SelectionDAG &DAG) const {
5942 const TargetMachine &TM = getTargetMachine();
5944 switch (N->getOpcode()) {
5946 llvm_unreachable("Do not know how to custom type legalize this operation!");
5947 case ISD::INTRINSIC_W_CHAIN: {
5948 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
5949 Intrinsic::ppc_is_decremented_ctr_nonzero)
5952 assert(N->getValueType(0) == MVT::i1 &&
5953 "Unexpected result type for CTR decrement intrinsic");
5954 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
5955 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
5956 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
5959 Results.push_back(NewInt);
5960 Results.push_back(NewInt.getValue(1));
5964 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5965 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5968 EVT VT = N->getValueType(0);
5970 if (VT == MVT::i64) {
5971 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5973 Results.push_back(NewNode);
5974 Results.push_back(NewNode.getValue(1));
5978 case ISD::FP_ROUND_INREG: {
5979 assert(N->getValueType(0) == MVT::ppcf128);
5980 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5981 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5982 MVT::f64, N->getOperand(0),
5983 DAG.getIntPtrConstant(0));
5984 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5985 MVT::f64, N->getOperand(0),
5986 DAG.getIntPtrConstant(1));
5988 // Add the two halves of the long double in round-to-zero mode.
5989 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
5991 // We know the low half is about to be thrown away, so just use something
5993 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5997 case ISD::FP_TO_SINT:
5998 // LowerFP_TO_INT() can only handle f32 and f64.
5999 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6001 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6007 //===----------------------------------------------------------------------===//
6008 // Other Lowering Code
6009 //===----------------------------------------------------------------------===//
6012 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6013 bool is64bit, unsigned BinOpcode) const {
6014 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6015 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6017 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6018 MachineFunction *F = BB->getParent();
6019 MachineFunction::iterator It = BB;
6022 unsigned dest = MI->getOperand(0).getReg();
6023 unsigned ptrA = MI->getOperand(1).getReg();
6024 unsigned ptrB = MI->getOperand(2).getReg();
6025 unsigned incr = MI->getOperand(3).getReg();
6026 DebugLoc dl = MI->getDebugLoc();
6028 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6029 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6030 F->insert(It, loopMBB);
6031 F->insert(It, exitMBB);
6032 exitMBB->splice(exitMBB->begin(), BB,
6033 llvm::next(MachineBasicBlock::iterator(MI)),
6035 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6037 MachineRegisterInfo &RegInfo = F->getRegInfo();
6038 unsigned TmpReg = (!BinOpcode) ? incr :
6039 RegInfo.createVirtualRegister(
6040 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6041 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6045 // fallthrough --> loopMBB
6046 BB->addSuccessor(loopMBB);
6049 // l[wd]arx dest, ptr
6050 // add r0, dest, incr
6051 // st[wd]cx. r0, ptr
6053 // fallthrough --> exitMBB
6055 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6056 .addReg(ptrA).addReg(ptrB);
6058 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6059 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6060 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6061 BuildMI(BB, dl, TII->get(PPC::BCC))
6062 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6063 BB->addSuccessor(loopMBB);
6064 BB->addSuccessor(exitMBB);
6073 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6074 MachineBasicBlock *BB,
6075 bool is8bit, // operation
6076 unsigned BinOpcode) const {
6077 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6078 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6079 // In 64 bit mode we have to use 64 bits for addresses, even though the
6080 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6081 // registers without caring whether they're 32 or 64, but here we're
6082 // doing actual arithmetic on the addresses.
6083 bool is64bit = PPCSubTarget.isPPC64();
6084 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6086 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6087 MachineFunction *F = BB->getParent();
6088 MachineFunction::iterator It = BB;
6091 unsigned dest = MI->getOperand(0).getReg();
6092 unsigned ptrA = MI->getOperand(1).getReg();
6093 unsigned ptrB = MI->getOperand(2).getReg();
6094 unsigned incr = MI->getOperand(3).getReg();
6095 DebugLoc dl = MI->getDebugLoc();
6097 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6098 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6099 F->insert(It, loopMBB);
6100 F->insert(It, exitMBB);
6101 exitMBB->splice(exitMBB->begin(), BB,
6102 llvm::next(MachineBasicBlock::iterator(MI)),
6104 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6106 MachineRegisterInfo &RegInfo = F->getRegInfo();
6107 const TargetRegisterClass *RC =
6108 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6109 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6110 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6111 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6112 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6113 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6114 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6115 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6116 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6117 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6118 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6119 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6120 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6122 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6126 // fallthrough --> loopMBB
6127 BB->addSuccessor(loopMBB);
6129 // The 4-byte load must be aligned, while a char or short may be
6130 // anywhere in the word. Hence all this nasty bookkeeping code.
6131 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6132 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6133 // xori shift, shift1, 24 [16]
6134 // rlwinm ptr, ptr1, 0, 0, 29
6135 // slw incr2, incr, shift
6136 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6137 // slw mask, mask2, shift
6139 // lwarx tmpDest, ptr
6140 // add tmp, tmpDest, incr2
6141 // andc tmp2, tmpDest, mask
6142 // and tmp3, tmp, mask
6143 // or tmp4, tmp3, tmp2
6146 // fallthrough --> exitMBB
6147 // srw dest, tmpDest, shift
6148 if (ptrA != ZeroReg) {
6149 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6150 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6151 .addReg(ptrA).addReg(ptrB);
6155 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6156 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6157 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6158 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6160 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6161 .addReg(Ptr1Reg).addImm(0).addImm(61);
6163 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6164 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6165 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6166 .addReg(incr).addReg(ShiftReg);
6168 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6170 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6171 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6173 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6174 .addReg(Mask2Reg).addReg(ShiftReg);
6177 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6178 .addReg(ZeroReg).addReg(PtrReg);
6180 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6181 .addReg(Incr2Reg).addReg(TmpDestReg);
6182 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6183 .addReg(TmpDestReg).addReg(MaskReg);
6184 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6185 .addReg(TmpReg).addReg(MaskReg);
6186 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6187 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6188 BuildMI(BB, dl, TII->get(PPC::STWCX))
6189 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6190 BuildMI(BB, dl, TII->get(PPC::BCC))
6191 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6192 BB->addSuccessor(loopMBB);
6193 BB->addSuccessor(exitMBB);
6198 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6203 llvm::MachineBasicBlock*
6204 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6205 MachineBasicBlock *MBB) const {
6206 DebugLoc DL = MI->getDebugLoc();
6207 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6209 MachineFunction *MF = MBB->getParent();
6210 MachineRegisterInfo &MRI = MF->getRegInfo();
6212 const BasicBlock *BB = MBB->getBasicBlock();
6213 MachineFunction::iterator I = MBB;
6217 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6218 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6220 unsigned DstReg = MI->getOperand(0).getReg();
6221 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6222 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6223 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6224 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6226 MVT PVT = getPointerTy();
6227 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6228 "Invalid Pointer Size!");
6229 // For v = setjmp(buf), we generate
6232 // SjLjSetup mainMBB
6238 // buf[LabelOffset] = LR
6242 // v = phi(main, restore)
6245 MachineBasicBlock *thisMBB = MBB;
6246 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6247 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6248 MF->insert(I, mainMBB);
6249 MF->insert(I, sinkMBB);
6251 MachineInstrBuilder MIB;
6253 // Transfer the remainder of BB and its successor edges to sinkMBB.
6254 sinkMBB->splice(sinkMBB->begin(), MBB,
6255 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
6256 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6258 // Note that the structure of the jmp_buf used here is not compatible
6259 // with that used by libc, and is not designed to be. Specifically, it
6260 // stores only those 'reserved' registers that LLVM does not otherwise
6261 // understand how to spill. Also, by convention, by the time this
6262 // intrinsic is called, Clang has already stored the frame address in the
6263 // first slot of the buffer and stack address in the third. Following the
6264 // X86 target code, we'll store the jump address in the second slot. We also
6265 // need to save the TOC pointer (R2) to handle jumps between shared
6266 // libraries, and that will be stored in the fourth slot. The thread
6267 // identifier (R13) is not affected.
6270 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6271 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6272 const int64_t BPOffset = 4 * PVT.getStoreSize();
6274 // Prepare IP either in reg.
6275 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6276 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6277 unsigned BufReg = MI->getOperand(1).getReg();
6279 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6280 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6284 MIB.setMemRefs(MMOBegin, MMOEnd);
6287 // Naked functions never have a base pointer, and so we use r1. For all
6288 // other functions, this decision must be delayed until during PEI.
6290 if (MF->getFunction()->getAttributes().hasAttribute(
6291 AttributeSet::FunctionIndex, Attribute::Naked))
6292 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6294 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6296 MIB = BuildMI(*thisMBB, MI, DL,
6297 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6301 MIB.setMemRefs(MMOBegin, MMOEnd);
6304 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6305 const PPCRegisterInfo *TRI =
6306 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6307 MIB.addRegMask(TRI->getNoPreservedMask());
6309 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6311 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6313 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6315 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6316 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6320 MIB = BuildMI(mainMBB, DL,
6321 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6324 if (PPCSubTarget.isPPC64()) {
6325 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6327 .addImm(LabelOffset)
6330 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6332 .addImm(LabelOffset)
6336 MIB.setMemRefs(MMOBegin, MMOEnd);
6338 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6339 mainMBB->addSuccessor(sinkMBB);
6342 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6343 TII->get(PPC::PHI), DstReg)
6344 .addReg(mainDstReg).addMBB(mainMBB)
6345 .addReg(restoreDstReg).addMBB(thisMBB);
6347 MI->eraseFromParent();
6352 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6353 MachineBasicBlock *MBB) const {
6354 DebugLoc DL = MI->getDebugLoc();
6355 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6357 MachineFunction *MF = MBB->getParent();
6358 MachineRegisterInfo &MRI = MF->getRegInfo();
6361 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6362 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6364 MVT PVT = getPointerTy();
6365 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6366 "Invalid Pointer Size!");
6368 const TargetRegisterClass *RC =
6369 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6370 unsigned Tmp = MRI.createVirtualRegister(RC);
6371 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6372 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6373 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6374 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6376 MachineInstrBuilder MIB;
6378 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6379 const int64_t SPOffset = 2 * PVT.getStoreSize();
6380 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6381 const int64_t BPOffset = 4 * PVT.getStoreSize();
6383 unsigned BufReg = MI->getOperand(0).getReg();
6385 // Reload FP (the jumped-to function may not have had a
6386 // frame pointer, and if so, then its r31 will be restored
6388 if (PVT == MVT::i64) {
6389 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6393 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6397 MIB.setMemRefs(MMOBegin, MMOEnd);
6400 if (PVT == MVT::i64) {
6401 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6402 .addImm(LabelOffset)
6405 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6406 .addImm(LabelOffset)
6409 MIB.setMemRefs(MMOBegin, MMOEnd);
6412 if (PVT == MVT::i64) {
6413 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6417 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6421 MIB.setMemRefs(MMOBegin, MMOEnd);
6424 if (PVT == MVT::i64) {
6425 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6429 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6433 MIB.setMemRefs(MMOBegin, MMOEnd);
6436 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6437 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6441 MIB.setMemRefs(MMOBegin, MMOEnd);
6445 BuildMI(*MBB, MI, DL,
6446 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6447 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6449 MI->eraseFromParent();
6454 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6455 MachineBasicBlock *BB) const {
6456 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6457 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6458 return emitEHSjLjSetJmp(MI, BB);
6459 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6460 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6461 return emitEHSjLjLongJmp(MI, BB);
6464 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6466 // To "insert" these instructions we actually have to insert their
6467 // control-flow patterns.
6468 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6469 MachineFunction::iterator It = BB;
6472 MachineFunction *F = BB->getParent();
6474 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6475 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6476 MI->getOpcode() == PPC::SELECT_I4 ||
6477 MI->getOpcode() == PPC::SELECT_I8)) {
6478 SmallVector<MachineOperand, 2> Cond;
6479 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6480 MI->getOpcode() == PPC::SELECT_CC_I8)
6481 Cond.push_back(MI->getOperand(4));
6483 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6484 Cond.push_back(MI->getOperand(1));
6486 DebugLoc dl = MI->getDebugLoc();
6487 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6488 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6489 Cond, MI->getOperand(2).getReg(),
6490 MI->getOperand(3).getReg());
6491 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6492 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6493 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6494 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6495 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6496 MI->getOpcode() == PPC::SELECT_I4 ||
6497 MI->getOpcode() == PPC::SELECT_I8 ||
6498 MI->getOpcode() == PPC::SELECT_F4 ||
6499 MI->getOpcode() == PPC::SELECT_F8 ||
6500 MI->getOpcode() == PPC::SELECT_VRRC) {
6501 // The incoming instruction knows the destination vreg to set, the
6502 // condition code register to branch on, the true/false values to
6503 // select between, and a branch opcode to use.
6508 // cmpTY ccX, r1, r2
6510 // fallthrough --> copy0MBB
6511 MachineBasicBlock *thisMBB = BB;
6512 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6513 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6514 DebugLoc dl = MI->getDebugLoc();
6515 F->insert(It, copy0MBB);
6516 F->insert(It, sinkMBB);
6518 // Transfer the remainder of BB and its successor edges to sinkMBB.
6519 sinkMBB->splice(sinkMBB->begin(), BB,
6520 llvm::next(MachineBasicBlock::iterator(MI)),
6522 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6524 // Next, add the true and fallthrough blocks as its successors.
6525 BB->addSuccessor(copy0MBB);
6526 BB->addSuccessor(sinkMBB);
6528 if (MI->getOpcode() == PPC::SELECT_I4 ||
6529 MI->getOpcode() == PPC::SELECT_I8 ||
6530 MI->getOpcode() == PPC::SELECT_F4 ||
6531 MI->getOpcode() == PPC::SELECT_F8 ||
6532 MI->getOpcode() == PPC::SELECT_VRRC) {
6533 BuildMI(BB, dl, TII->get(PPC::BC))
6534 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6536 unsigned SelectPred = MI->getOperand(4).getImm();
6537 BuildMI(BB, dl, TII->get(PPC::BCC))
6538 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6542 // %FalseValue = ...
6543 // # fallthrough to sinkMBB
6546 // Update machine-CFG edges
6547 BB->addSuccessor(sinkMBB);
6550 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6553 BuildMI(*BB, BB->begin(), dl,
6554 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6555 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6556 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6558 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6559 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6560 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6561 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6562 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6563 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6564 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6565 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6567 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6568 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6569 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6570 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6571 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6572 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6573 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6574 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6576 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6577 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6578 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6579 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6580 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6581 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6582 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6583 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6585 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6586 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6587 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6588 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6589 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6590 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6591 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6592 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6594 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6595 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6596 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6597 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6598 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6599 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6600 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6601 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6603 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6604 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6605 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6606 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6607 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6608 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6609 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6610 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6612 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6613 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6614 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6615 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6616 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6617 BB = EmitAtomicBinary(MI, BB, false, 0);
6618 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6619 BB = EmitAtomicBinary(MI, BB, true, 0);
6621 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6622 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6623 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6625 unsigned dest = MI->getOperand(0).getReg();
6626 unsigned ptrA = MI->getOperand(1).getReg();
6627 unsigned ptrB = MI->getOperand(2).getReg();
6628 unsigned oldval = MI->getOperand(3).getReg();
6629 unsigned newval = MI->getOperand(4).getReg();
6630 DebugLoc dl = MI->getDebugLoc();
6632 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6633 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6634 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6635 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6636 F->insert(It, loop1MBB);
6637 F->insert(It, loop2MBB);
6638 F->insert(It, midMBB);
6639 F->insert(It, exitMBB);
6640 exitMBB->splice(exitMBB->begin(), BB,
6641 llvm::next(MachineBasicBlock::iterator(MI)),
6643 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6647 // fallthrough --> loopMBB
6648 BB->addSuccessor(loop1MBB);
6651 // l[wd]arx dest, ptr
6652 // cmp[wd] dest, oldval
6655 // st[wd]cx. newval, ptr
6659 // st[wd]cx. dest, ptr
6662 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6663 .addReg(ptrA).addReg(ptrB);
6664 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6665 .addReg(oldval).addReg(dest);
6666 BuildMI(BB, dl, TII->get(PPC::BCC))
6667 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6668 BB->addSuccessor(loop2MBB);
6669 BB->addSuccessor(midMBB);
6672 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6673 .addReg(newval).addReg(ptrA).addReg(ptrB);
6674 BuildMI(BB, dl, TII->get(PPC::BCC))
6675 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6676 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6677 BB->addSuccessor(loop1MBB);
6678 BB->addSuccessor(exitMBB);
6681 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6682 .addReg(dest).addReg(ptrA).addReg(ptrB);
6683 BB->addSuccessor(exitMBB);
6688 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6689 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6690 // We must use 64-bit registers for addresses when targeting 64-bit,
6691 // since we're actually doing arithmetic on them. Other registers
6693 bool is64bit = PPCSubTarget.isPPC64();
6694 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6696 unsigned dest = MI->getOperand(0).getReg();
6697 unsigned ptrA = MI->getOperand(1).getReg();
6698 unsigned ptrB = MI->getOperand(2).getReg();
6699 unsigned oldval = MI->getOperand(3).getReg();
6700 unsigned newval = MI->getOperand(4).getReg();
6701 DebugLoc dl = MI->getDebugLoc();
6703 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6704 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6705 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6706 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6707 F->insert(It, loop1MBB);
6708 F->insert(It, loop2MBB);
6709 F->insert(It, midMBB);
6710 F->insert(It, exitMBB);
6711 exitMBB->splice(exitMBB->begin(), BB,
6712 llvm::next(MachineBasicBlock::iterator(MI)),
6714 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6716 MachineRegisterInfo &RegInfo = F->getRegInfo();
6717 const TargetRegisterClass *RC =
6718 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6719 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6720 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6721 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6722 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6723 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6724 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6725 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6726 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6727 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6728 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6729 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6730 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6731 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6732 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6734 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6735 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6738 // fallthrough --> loopMBB
6739 BB->addSuccessor(loop1MBB);
6741 // The 4-byte load must be aligned, while a char or short may be
6742 // anywhere in the word. Hence all this nasty bookkeeping code.
6743 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6744 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6745 // xori shift, shift1, 24 [16]
6746 // rlwinm ptr, ptr1, 0, 0, 29
6747 // slw newval2, newval, shift
6748 // slw oldval2, oldval,shift
6749 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6750 // slw mask, mask2, shift
6751 // and newval3, newval2, mask
6752 // and oldval3, oldval2, mask
6754 // lwarx tmpDest, ptr
6755 // and tmp, tmpDest, mask
6756 // cmpw tmp, oldval3
6759 // andc tmp2, tmpDest, mask
6760 // or tmp4, tmp2, newval3
6765 // stwcx. tmpDest, ptr
6767 // srw dest, tmpDest, shift
6768 if (ptrA != ZeroReg) {
6769 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6770 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6771 .addReg(ptrA).addReg(ptrB);
6775 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6776 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6777 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6778 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6780 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6781 .addReg(Ptr1Reg).addImm(0).addImm(61);
6783 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6784 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6785 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6786 .addReg(newval).addReg(ShiftReg);
6787 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6788 .addReg(oldval).addReg(ShiftReg);
6790 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6792 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6793 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6794 .addReg(Mask3Reg).addImm(65535);
6796 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6797 .addReg(Mask2Reg).addReg(ShiftReg);
6798 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6799 .addReg(NewVal2Reg).addReg(MaskReg);
6800 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6801 .addReg(OldVal2Reg).addReg(MaskReg);
6804 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6805 .addReg(ZeroReg).addReg(PtrReg);
6806 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6807 .addReg(TmpDestReg).addReg(MaskReg);
6808 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6809 .addReg(TmpReg).addReg(OldVal3Reg);
6810 BuildMI(BB, dl, TII->get(PPC::BCC))
6811 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6812 BB->addSuccessor(loop2MBB);
6813 BB->addSuccessor(midMBB);
6816 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6817 .addReg(TmpDestReg).addReg(MaskReg);
6818 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6819 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6820 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6821 .addReg(ZeroReg).addReg(PtrReg);
6822 BuildMI(BB, dl, TII->get(PPC::BCC))
6823 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6824 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6825 BB->addSuccessor(loop1MBB);
6826 BB->addSuccessor(exitMBB);
6829 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6830 .addReg(ZeroReg).addReg(PtrReg);
6831 BB->addSuccessor(exitMBB);
6836 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6838 } else if (MI->getOpcode() == PPC::FADDrtz) {
6839 // This pseudo performs an FADD with rounding mode temporarily forced
6840 // to round-to-zero. We emit this via custom inserter since the FPSCR
6841 // is not modeled at the SelectionDAG level.
6842 unsigned Dest = MI->getOperand(0).getReg();
6843 unsigned Src1 = MI->getOperand(1).getReg();
6844 unsigned Src2 = MI->getOperand(2).getReg();
6845 DebugLoc dl = MI->getDebugLoc();
6847 MachineRegisterInfo &RegInfo = F->getRegInfo();
6848 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6850 // Save FPSCR value.
6851 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6853 // Set rounding mode to round-to-zero.
6854 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6855 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6857 // Perform addition.
6858 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6860 // Restore FPSCR value.
6861 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6862 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6863 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
6864 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6865 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
6866 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6867 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
6868 PPC::ANDIo8 : PPC::ANDIo;
6869 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6870 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
6872 MachineRegisterInfo &RegInfo = F->getRegInfo();
6873 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
6874 &PPC::GPRCRegClass :
6875 &PPC::G8RCRegClass);
6877 DebugLoc dl = MI->getDebugLoc();
6878 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
6879 .addReg(MI->getOperand(1).getReg()).addImm(1);
6880 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
6881 MI->getOperand(0).getReg())
6882 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
6884 llvm_unreachable("Unexpected instr type to insert");
6887 MI->eraseFromParent(); // The pseudo instruction is gone now.
6891 //===----------------------------------------------------------------------===//
6892 // Target Optimization Hooks
6893 //===----------------------------------------------------------------------===//
6895 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6896 DAGCombinerInfo &DCI) const {
6897 if (DCI.isAfterLegalizeVectorOps())
6900 EVT VT = Op.getValueType();
6902 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6903 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6904 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6906 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6907 // For the reciprocal, we need to find the zero of the function:
6908 // F(X) = A X - 1 [which has a zero at X = 1/A]
6910 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
6911 // does not require additional intermediate precision]
6913 // Convergence is quadratic, so we essentially double the number of digits
6914 // correct after every iteration. The minimum architected relative
6915 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6916 // 23 digits and double has 52 digits.
6917 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6918 if (VT.getScalarType() == MVT::f64)
6921 SelectionDAG &DAG = DCI.DAG;
6925 DAG.getConstantFP(1.0, VT.getScalarType());
6926 if (VT.isVector()) {
6927 assert(VT.getVectorNumElements() == 4 &&
6928 "Unknown vector type");
6929 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6930 FPOne, FPOne, FPOne, FPOne);
6933 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
6934 DCI.AddToWorklist(Est.getNode());
6936 // Newton iterations: Est = Est + Est (1 - Arg * Est)
6937 for (int i = 0; i < Iterations; ++i) {
6938 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
6939 DCI.AddToWorklist(NewEst.getNode());
6941 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
6942 DCI.AddToWorklist(NewEst.getNode());
6944 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6945 DCI.AddToWorklist(NewEst.getNode());
6947 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
6948 DCI.AddToWorklist(Est.getNode());
6957 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
6958 DAGCombinerInfo &DCI) const {
6959 if (DCI.isAfterLegalizeVectorOps())
6962 EVT VT = Op.getValueType();
6964 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
6965 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
6966 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6968 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6969 // For the reciprocal sqrt, we need to find the zero of the function:
6970 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
6972 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
6973 // As a result, we precompute A/2 prior to the iteration loop.
6975 // Convergence is quadratic, so we essentially double the number of digits
6976 // correct after every iteration. The minimum architected relative
6977 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6978 // 23 digits and double has 52 digits.
6979 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6980 if (VT.getScalarType() == MVT::f64)
6983 SelectionDAG &DAG = DCI.DAG;
6986 SDValue FPThreeHalves =
6987 DAG.getConstantFP(1.5, VT.getScalarType());
6988 if (VT.isVector()) {
6989 assert(VT.getVectorNumElements() == 4 &&
6990 "Unknown vector type");
6991 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6992 FPThreeHalves, FPThreeHalves,
6993 FPThreeHalves, FPThreeHalves);
6996 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
6997 DCI.AddToWorklist(Est.getNode());
6999 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7000 // this entire sequence requires only one FP constant.
7001 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7002 DCI.AddToWorklist(HalfArg.getNode());
7004 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7005 DCI.AddToWorklist(HalfArg.getNode());
7007 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7008 for (int i = 0; i < Iterations; ++i) {
7009 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7010 DCI.AddToWorklist(NewEst.getNode());
7012 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7013 DCI.AddToWorklist(NewEst.getNode());
7015 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7016 DCI.AddToWorklist(NewEst.getNode());
7018 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7019 DCI.AddToWorklist(Est.getNode());
7028 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7029 // not enforce equality of the chain operands.
7030 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7031 unsigned Bytes, int Dist,
7032 SelectionDAG &DAG) {
7033 EVT VT = LS->getMemoryVT();
7034 if (VT.getSizeInBits() / 8 != Bytes)
7037 SDValue Loc = LS->getBasePtr();
7038 SDValue BaseLoc = Base->getBasePtr();
7039 if (Loc.getOpcode() == ISD::FrameIndex) {
7040 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7042 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7043 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7044 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7045 int FS = MFI->getObjectSize(FI);
7046 int BFS = MFI->getObjectSize(BFI);
7047 if (FS != BFS || FS != (int)Bytes) return false;
7048 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7052 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7053 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7056 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7057 const GlobalValue *GV1 = NULL;
7058 const GlobalValue *GV2 = NULL;
7059 int64_t Offset1 = 0;
7060 int64_t Offset2 = 0;
7061 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7062 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7063 if (isGA1 && isGA2 && GV1 == GV2)
7064 return Offset1 == (Offset2 + Dist*Bytes);
7068 // Return true is there is a nearyby consecutive load to the one provided
7069 // (regardless of alignment). We search up and down the chain, looking though
7070 // token factors and other loads (but nothing else). As a result, a true
7071 // results indicates that it is safe to create a new consecutive load adjacent
7072 // to the load provided.
7073 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7074 SDValue Chain = LD->getChain();
7075 EVT VT = LD->getMemoryVT();
7077 SmallSet<SDNode *, 16> LoadRoots;
7078 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7079 SmallSet<SDNode *, 16> Visited;
7081 // First, search up the chain, branching to follow all token-factor operands.
7082 // If we find a consecutive load, then we're done, otherwise, record all
7083 // nodes just above the top-level loads and token factors.
7084 while (!Queue.empty()) {
7085 SDNode *ChainNext = Queue.pop_back_val();
7086 if (!Visited.insert(ChainNext))
7089 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7090 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7093 if (!Visited.count(ChainLD->getChain().getNode()))
7094 Queue.push_back(ChainLD->getChain().getNode());
7095 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7096 for (SDNode::op_iterator O = ChainNext->op_begin(),
7097 OE = ChainNext->op_end(); O != OE; ++O)
7098 if (!Visited.count(O->getNode()))
7099 Queue.push_back(O->getNode());
7101 LoadRoots.insert(ChainNext);
7104 // Second, search down the chain, starting from the top-level nodes recorded
7105 // in the first phase. These top-level nodes are the nodes just above all
7106 // loads and token factors. Starting with their uses, recursively look though
7107 // all loads (just the chain uses) and token factors to find a consecutive
7112 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7113 IE = LoadRoots.end(); I != IE; ++I) {
7114 Queue.push_back(*I);
7116 while (!Queue.empty()) {
7117 SDNode *LoadRoot = Queue.pop_back_val();
7118 if (!Visited.insert(LoadRoot))
7121 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7122 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7125 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7126 UE = LoadRoot->use_end(); UI != UE; ++UI)
7127 if (((isa<LoadSDNode>(*UI) &&
7128 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7129 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7130 Queue.push_back(*UI);
7137 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7138 DAGCombinerInfo &DCI) const {
7139 SelectionDAG &DAG = DCI.DAG;
7142 assert(PPCSubTarget.useCRBits() &&
7143 "Expecting to be tracking CR bits");
7144 // If we're tracking CR bits, we need to be careful that we don't have:
7145 // trunc(binary-ops(zext(x), zext(y)))
7147 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7148 // such that we're unnecessarily moving things into GPRs when it would be
7149 // better to keep them in CR bits.
7151 // Note that trunc here can be an actual i1 trunc, or can be the effective
7152 // truncation that comes from a setcc or select_cc.
7153 if (N->getOpcode() == ISD::TRUNCATE &&
7154 N->getValueType(0) != MVT::i1)
7157 if (N->getOperand(0).getValueType() != MVT::i32 &&
7158 N->getOperand(0).getValueType() != MVT::i64)
7161 if (N->getOpcode() == ISD::SETCC ||
7162 N->getOpcode() == ISD::SELECT_CC) {
7163 // If we're looking at a comparison, then we need to make sure that the
7164 // high bits (all except for the first) don't matter the result.
7166 cast<CondCodeSDNode>(N->getOperand(
7167 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7168 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7170 if (ISD::isSignedIntSetCC(CC)) {
7171 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7172 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7174 } else if (ISD::isUnsignedIntSetCC(CC)) {
7175 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7176 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7177 !DAG.MaskedValueIsZero(N->getOperand(1),
7178 APInt::getHighBitsSet(OpBits, OpBits-1)))
7181 // This is neither a signed nor an unsigned comparison, just make sure
7182 // that the high bits are equal.
7183 APInt Op1Zero, Op1One;
7184 APInt Op2Zero, Op2One;
7185 DAG.ComputeMaskedBits(N->getOperand(0), Op1Zero, Op1One);
7186 DAG.ComputeMaskedBits(N->getOperand(1), Op2Zero, Op2One);
7188 // We don't really care about what is known about the first bit (if
7189 // anything), so clear it in all masks prior to comparing them.
7190 Op1Zero.clearBit(0); Op1One.clearBit(0);
7191 Op2Zero.clearBit(0); Op2One.clearBit(0);
7193 if (Op1Zero != Op2Zero || Op1One != Op2One)
7198 // We now know that the higher-order bits are irrelevant, we just need to
7199 // make sure that all of the intermediate operations are bit operations, and
7200 // all inputs are extensions.
7201 if (N->getOperand(0).getOpcode() != ISD::AND &&
7202 N->getOperand(0).getOpcode() != ISD::OR &&
7203 N->getOperand(0).getOpcode() != ISD::XOR &&
7204 N->getOperand(0).getOpcode() != ISD::SELECT &&
7205 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7206 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7207 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7208 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7209 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7212 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7213 N->getOperand(1).getOpcode() != ISD::AND &&
7214 N->getOperand(1).getOpcode() != ISD::OR &&
7215 N->getOperand(1).getOpcode() != ISD::XOR &&
7216 N->getOperand(1).getOpcode() != ISD::SELECT &&
7217 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7218 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7219 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7220 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7221 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7224 SmallVector<SDValue, 4> Inputs;
7225 SmallVector<SDValue, 8> BinOps, PromOps;
7226 SmallPtrSet<SDNode *, 16> Visited;
7228 for (unsigned i = 0; i < 2; ++i) {
7229 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7230 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7231 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7232 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7233 isa<ConstantSDNode>(N->getOperand(i)))
7234 Inputs.push_back(N->getOperand(i));
7236 BinOps.push_back(N->getOperand(i));
7238 if (N->getOpcode() == ISD::TRUNCATE)
7242 // Visit all inputs, collect all binary operations (and, or, xor and
7243 // select) that are all fed by extensions.
7244 while (!BinOps.empty()) {
7245 SDValue BinOp = BinOps.back();
7248 if (!Visited.insert(BinOp.getNode()))
7251 PromOps.push_back(BinOp);
7253 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7254 // The condition of the select is not promoted.
7255 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7257 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7260 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7261 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7262 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7263 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7264 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7265 Inputs.push_back(BinOp.getOperand(i));
7266 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7267 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7268 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7269 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7270 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7271 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7272 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7273 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7274 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7275 BinOps.push_back(BinOp.getOperand(i));
7277 // We have an input that is not an extension or another binary
7278 // operation; we'll abort this transformation.
7284 // Make sure that this is a self-contained cluster of operations (which
7285 // is not quite the same thing as saying that everything has only one
7287 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7288 if (isa<ConstantSDNode>(Inputs[i]))
7291 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7292 UE = Inputs[i].getNode()->use_end();
7295 if (User != N && !Visited.count(User))
7300 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7301 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7302 UE = PromOps[i].getNode()->use_end();
7305 if (User != N && !Visited.count(User))
7310 // Replace all inputs with the extension operand.
7311 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7312 // Constants may have users outside the cluster of to-be-promoted nodes,
7313 // and so we need to replace those as we do the promotions.
7314 if (isa<ConstantSDNode>(Inputs[i]))
7317 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7320 // Replace all operations (these are all the same, but have a different
7321 // (i1) return type). DAG.getNode will validate that the types of
7322 // a binary operator match, so go through the list in reverse so that
7323 // we've likely promoted both operands first. Any intermediate truncations or
7324 // extensions disappear.
7325 while (!PromOps.empty()) {
7326 SDValue PromOp = PromOps.back();
7329 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7330 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7331 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7332 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7333 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7334 PromOp.getOperand(0).getValueType() != MVT::i1) {
7335 // The operand is not yet ready (see comment below).
7336 PromOps.insert(PromOps.begin(), PromOp);
7340 SDValue RepValue = PromOp.getOperand(0);
7341 if (isa<ConstantSDNode>(RepValue))
7342 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7344 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7349 switch (PromOp.getOpcode()) {
7350 default: C = 0; break;
7351 case ISD::SELECT: C = 1; break;
7352 case ISD::SELECT_CC: C = 2; break;
7355 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7356 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7357 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7358 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7359 // The to-be-promoted operands of this node have not yet been
7360 // promoted (this should be rare because we're going through the
7361 // list backward, but if one of the operands has several users in
7362 // this cluster of to-be-promoted nodes, it is possible).
7363 PromOps.insert(PromOps.begin(), PromOp);
7367 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7368 PromOp.getNode()->op_end());
7370 // If there are any constant inputs, make sure they're replaced now.
7371 for (unsigned i = 0; i < 2; ++i)
7372 if (isa<ConstantSDNode>(Ops[C+i]))
7373 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7375 DAG.ReplaceAllUsesOfValueWith(PromOp,
7376 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1,
7377 Ops.data(), Ops.size()));
7380 // Now we're left with the initial truncation itself.
7381 if (N->getOpcode() == ISD::TRUNCATE)
7382 return N->getOperand(0);
7384 // Otherwise, this is a comparison. The operands to be compared have just
7385 // changed type (to i1), but everything else is the same.
7386 return SDValue(N, 0);
7389 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7390 DAGCombinerInfo &DCI) const {
7391 SelectionDAG &DAG = DCI.DAG;
7394 assert(PPCSubTarget.useCRBits() &&
7395 "Expecting to be tracking CR bits");
7396 // If we're tracking CR bits, we need to be careful that we don't have:
7397 // zext(binary-ops(trunc(x), trunc(y)))
7399 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7400 // such that we're unnecessarily moving things into CR bits that can more
7401 // efficiently stay in GPRs. Note that if we're not certain that the high
7402 // bits are set as required by the final extension, we still may need to do
7403 // some masking to get the proper behavior.
7405 if (N->getValueType(0) != MVT::i32 &&
7406 N->getValueType(0) != MVT::i64)
7409 if (N->getOperand(0).getValueType() != MVT::i1)
7412 if (N->getOperand(0).getOpcode() != ISD::AND &&
7413 N->getOperand(0).getOpcode() != ISD::OR &&
7414 N->getOperand(0).getOpcode() != ISD::XOR &&
7415 N->getOperand(0).getOpcode() != ISD::SELECT &&
7416 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7419 SmallVector<SDValue, 4> Inputs;
7420 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7421 SmallPtrSet<SDNode *, 16> Visited;
7423 // Visit all inputs, collect all binary operations (and, or, xor and
7424 // select) that are all fed by truncations.
7425 while (!BinOps.empty()) {
7426 SDValue BinOp = BinOps.back();
7429 if (!Visited.insert(BinOp.getNode()))
7432 PromOps.push_back(BinOp);
7434 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7435 // The condition of the select is not promoted.
7436 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7438 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7441 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7442 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7443 Inputs.push_back(BinOp.getOperand(i));
7444 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7445 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7446 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7447 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7448 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7449 BinOps.push_back(BinOp.getOperand(i));
7451 // We have an input that is not a truncation or another binary
7452 // operation; we'll abort this transformation.
7458 // Make sure that this is a self-contained cluster of operations (which
7459 // is not quite the same thing as saying that everything has only one
7461 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7462 if (isa<ConstantSDNode>(Inputs[i]))
7465 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7466 UE = Inputs[i].getNode()->use_end();
7469 if (User != N && !Visited.count(User))
7474 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7475 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7476 UE = PromOps[i].getNode()->use_end();
7479 if (User != N && !Visited.count(User))
7484 bool ReallyNeedsExt = false;
7485 if (N->getOpcode() != ISD::ANY_EXTEND) {
7486 // If all of the inputs are not already sign/zero extended, then
7487 // we'll still need to do that at the end.
7488 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7489 if (isa<ConstantSDNode>(Inputs[i]))
7493 Inputs[i].getOperand(0).getValueSizeInBits();
7494 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7495 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7496 APInt::getHighBitsSet(OpBits,
7498 (N->getOpcode() == ISD::SIGN_EXTEND &&
7499 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) != OpBits)) {
7500 ReallyNeedsExt = true;
7506 // Replace all inputs, either with the truncation operand, or a
7507 // truncation or extension to the final output type.
7508 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7509 // Constant inputs need to be replaced with the to-be-promoted nodes that
7510 // use them because they might have users outside of the cluster of
7512 if (isa<ConstantSDNode>(Inputs[i]))
7515 SDValue InSrc = Inputs[i].getOperand(0);
7516 if (Inputs[i].getValueType() == N->getValueType(0))
7517 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7518 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7519 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7520 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7521 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7522 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7523 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7525 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7526 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7529 // Replace all operations (these are all the same, but have a different
7530 // (promoted) return type). DAG.getNode will validate that the types of
7531 // a binary operator match, so go through the list in reverse so that
7532 // we've likely promoted both operands first.
7533 while (!PromOps.empty()) {
7534 SDValue PromOp = PromOps.back();
7538 switch (PromOp.getOpcode()) {
7539 default: C = 0; break;
7540 case ISD::SELECT: C = 1; break;
7541 case ISD::SELECT_CC: C = 2; break;
7544 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7545 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7546 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7547 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7548 // The to-be-promoted operands of this node have not yet been
7549 // promoted (this should be rare because we're going through the
7550 // list backward, but if one of the operands has several users in
7551 // this cluster of to-be-promoted nodes, it is possible).
7552 PromOps.insert(PromOps.begin(), PromOp);
7556 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7557 PromOp.getNode()->op_end());
7559 // If this node has constant inputs, then they'll need to be promoted here.
7560 for (unsigned i = 0; i < 2; ++i) {
7561 if (!isa<ConstantSDNode>(Ops[C+i]))
7563 if (Ops[C+i].getValueType() == N->getValueType(0))
7566 if (N->getOpcode() == ISD::SIGN_EXTEND)
7567 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7568 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7569 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7571 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7574 DAG.ReplaceAllUsesOfValueWith(PromOp,
7575 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0),
7576 Ops.data(), Ops.size()));
7579 // Now we're left with the initial extension itself.
7580 if (!ReallyNeedsExt)
7581 return N->getOperand(0);
7583 // To zero extend, just mask off everything except for the first bit.
7584 if (N->getOpcode() == ISD::ZERO_EXTEND)
7585 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7586 DAG.getConstant(1, N->getValueType(0)));
7588 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7589 "Invalid extension type");
7590 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7592 DAG.getConstant(N->getValueSizeInBits(0)-1, ShiftAmountTy);
7593 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7594 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7595 N->getOperand(0), ShiftCst), ShiftCst);
7598 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7599 DAGCombinerInfo &DCI) const {
7600 const TargetMachine &TM = getTargetMachine();
7601 SelectionDAG &DAG = DCI.DAG;
7603 switch (N->getOpcode()) {
7606 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7607 if (C->isNullValue()) // 0 << V -> 0.
7608 return N->getOperand(0);
7612 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7613 if (C->isNullValue()) // 0 >>u V -> 0.
7614 return N->getOperand(0);
7618 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7619 if (C->isNullValue() || // 0 >>s V -> 0.
7620 C->isAllOnesValue()) // -1 >>s V -> -1.
7621 return N->getOperand(0);
7624 case ISD::SIGN_EXTEND:
7625 case ISD::ZERO_EXTEND:
7626 case ISD::ANY_EXTEND:
7627 return DAGCombineExtBoolTrunc(N, DCI);
7630 case ISD::SELECT_CC:
7631 return DAGCombineTruncBoolExt(N, DCI);
7633 assert(TM.Options.UnsafeFPMath &&
7634 "Reciprocal estimates require UnsafeFPMath");
7636 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7638 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7639 if (RV.getNode() != 0) {
7640 DCI.AddToWorklist(RV.getNode());
7641 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7642 N->getOperand(0), RV);
7644 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7645 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7647 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7649 if (RV.getNode() != 0) {
7650 DCI.AddToWorklist(RV.getNode());
7651 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7652 N->getValueType(0), RV);
7653 DCI.AddToWorklist(RV.getNode());
7654 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7655 N->getOperand(0), RV);
7657 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7658 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7660 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7662 if (RV.getNode() != 0) {
7663 DCI.AddToWorklist(RV.getNode());
7664 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7665 N->getValueType(0), RV,
7666 N->getOperand(1).getOperand(1));
7667 DCI.AddToWorklist(RV.getNode());
7668 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7669 N->getOperand(0), RV);
7673 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7674 if (RV.getNode() != 0) {
7675 DCI.AddToWorklist(RV.getNode());
7676 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7677 N->getOperand(0), RV);
7683 assert(TM.Options.UnsafeFPMath &&
7684 "Reciprocal estimates require UnsafeFPMath");
7686 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7688 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7689 if (RV.getNode() != 0) {
7690 DCI.AddToWorklist(RV.getNode());
7691 RV = DAGCombineFastRecip(RV, DCI);
7692 if (RV.getNode() != 0) {
7693 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7694 // this case and force the answer to 0.
7696 EVT VT = RV.getValueType();
7698 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7699 if (VT.isVector()) {
7700 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7701 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7705 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7706 N->getOperand(0), Zero, ISD::SETEQ);
7707 DCI.AddToWorklist(ZeroCmp.getNode());
7708 DCI.AddToWorklist(RV.getNode());
7710 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7718 case ISD::SINT_TO_FP:
7719 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7720 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7721 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7722 // We allow the src/dst to be either f32/f64, but the intermediate
7723 // type must be i64.
7724 if (N->getOperand(0).getValueType() == MVT::i64 &&
7725 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7726 SDValue Val = N->getOperand(0).getOperand(0);
7727 if (Val.getValueType() == MVT::f32) {
7728 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7729 DCI.AddToWorklist(Val.getNode());
7732 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7733 DCI.AddToWorklist(Val.getNode());
7734 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7735 DCI.AddToWorklist(Val.getNode());
7736 if (N->getValueType(0) == MVT::f32) {
7737 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7738 DAG.getIntPtrConstant(0));
7739 DCI.AddToWorklist(Val.getNode());
7742 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7743 // If the intermediate type is i32, we can avoid the load/store here
7750 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7751 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7752 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7753 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7754 N->getOperand(1).getValueType() == MVT::i32 &&
7755 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7756 SDValue Val = N->getOperand(1).getOperand(0);
7757 if (Val.getValueType() == MVT::f32) {
7758 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7759 DCI.AddToWorklist(Val.getNode());
7761 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7762 DCI.AddToWorklist(Val.getNode());
7765 N->getOperand(0), Val, N->getOperand(2),
7766 DAG.getValueType(N->getOperand(1).getValueType())
7769 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7770 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7771 cast<StoreSDNode>(N)->getMemoryVT(),
7772 cast<StoreSDNode>(N)->getMemOperand());
7773 DCI.AddToWorklist(Val.getNode());
7777 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7778 if (cast<StoreSDNode>(N)->isUnindexed() &&
7779 N->getOperand(1).getOpcode() == ISD::BSWAP &&
7780 N->getOperand(1).getNode()->hasOneUse() &&
7781 (N->getOperand(1).getValueType() == MVT::i32 ||
7782 N->getOperand(1).getValueType() == MVT::i16 ||
7783 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7784 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7785 N->getOperand(1).getValueType() == MVT::i64))) {
7786 SDValue BSwapOp = N->getOperand(1).getOperand(0);
7787 // Do an any-extend to 32-bits if this is a half-word input.
7788 if (BSwapOp.getValueType() == MVT::i16)
7789 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7792 N->getOperand(0), BSwapOp, N->getOperand(2),
7793 DAG.getValueType(N->getOperand(1).getValueType())
7796 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7797 Ops, array_lengthof(Ops),
7798 cast<StoreSDNode>(N)->getMemoryVT(),
7799 cast<StoreSDNode>(N)->getMemOperand());
7803 LoadSDNode *LD = cast<LoadSDNode>(N);
7804 EVT VT = LD->getValueType(0);
7805 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
7806 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
7807 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
7808 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
7809 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
7810 VT == MVT::v4i32 || VT == MVT::v4f32) &&
7811 LD->getAlignment() < ABIAlignment) {
7812 // This is a type-legal unaligned Altivec load.
7813 SDValue Chain = LD->getChain();
7814 SDValue Ptr = LD->getBasePtr();
7816 // This implements the loading of unaligned vectors as described in
7817 // the venerable Apple Velocity Engine overview. Specifically:
7818 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
7819 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
7821 // The general idea is to expand a sequence of one or more unaligned
7822 // loads into a alignment-based permutation-control instruction (lvsl),
7823 // a series of regular vector loads (which always truncate their
7824 // input address to an aligned address), and a series of permutations.
7825 // The results of these permutations are the requested loaded values.
7826 // The trick is that the last "extra" load is not taken from the address
7827 // you might suspect (sizeof(vector) bytes after the last requested
7828 // load), but rather sizeof(vector) - 1 bytes after the last
7829 // requested vector. The point of this is to avoid a page fault if the
7830 // base address happened to be aligned. This works because if the base
7831 // address is aligned, then adding less than a full vector length will
7832 // cause the last vector in the sequence to be (re)loaded. Otherwise,
7833 // the next vector will be fetched as you might suspect was necessary.
7835 // We might be able to reuse the permutation generation from
7836 // a different base address offset from this one by an aligned amount.
7837 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
7838 // optimization later.
7839 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
7840 DAG, dl, MVT::v16i8);
7842 // Refine the alignment of the original load (a "new" load created here
7843 // which was identical to the first except for the alignment would be
7844 // merged with the existing node regardless).
7845 MachineFunction &MF = DAG.getMachineFunction();
7846 MachineMemOperand *MMO =
7847 MF.getMachineMemOperand(LD->getPointerInfo(),
7848 LD->getMemOperand()->getFlags(),
7849 LD->getMemoryVT().getStoreSize(),
7851 LD->refineAlignment(MMO);
7852 SDValue BaseLoad = SDValue(LD, 0);
7854 // Note that the value of IncOffset (which is provided to the next
7855 // load's pointer info offset value, and thus used to calculate the
7856 // alignment), and the value of IncValue (which is actually used to
7857 // increment the pointer value) are different! This is because we
7858 // require the next load to appear to be aligned, even though it
7859 // is actually offset from the base pointer by a lesser amount.
7860 int IncOffset = VT.getSizeInBits() / 8;
7861 int IncValue = IncOffset;
7863 // Walk (both up and down) the chain looking for another load at the real
7864 // (aligned) offset (the alignment of the other load does not matter in
7865 // this case). If found, then do not use the offset reduction trick, as
7866 // that will prevent the loads from being later combined (as they would
7867 // otherwise be duplicates).
7868 if (!findConsecutiveLoad(LD, DAG))
7871 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
7872 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
7875 DAG.getLoad(VT, dl, Chain, Ptr,
7876 LD->getPointerInfo().getWithOffset(IncOffset),
7877 LD->isVolatile(), LD->isNonTemporal(),
7878 LD->isInvariant(), ABIAlignment);
7880 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7881 BaseLoad.getValue(1), ExtraLoad.getValue(1));
7883 if (BaseLoad.getValueType() != MVT::v4i32)
7884 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
7886 if (ExtraLoad.getValueType() != MVT::v4i32)
7887 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
7889 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
7890 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
7892 if (VT != MVT::v4i32)
7893 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
7895 // Now we need to be really careful about how we update the users of the
7896 // original load. We cannot just call DCI.CombineTo (or
7897 // DAG.ReplaceAllUsesWith for that matter), because the load still has
7898 // uses created here (the permutation for example) that need to stay.
7899 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7901 SDUse &Use = UI.getUse();
7903 // Note: BaseLoad is checked here because it might not be N, but a
7905 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
7906 User == TF.getNode() || Use.getResNo() > 1) {
7911 SDValue To = Use.getResNo() ? TF : Perm;
7914 SmallVector<SDValue, 8> Ops;
7915 for (SDNode::op_iterator O = User->op_begin(),
7916 OE = User->op_end(); O != OE; ++O) {
7923 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
7926 return SDValue(N, 0);
7930 case ISD::INTRINSIC_WO_CHAIN:
7931 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
7932 Intrinsic::ppc_altivec_lvsl &&
7933 N->getOperand(1)->getOpcode() == ISD::ADD) {
7934 SDValue Add = N->getOperand(1);
7936 if (DAG.MaskedValueIsZero(Add->getOperand(1),
7937 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
7938 Add.getValueType().getScalarType().getSizeInBits()))) {
7939 SDNode *BasePtr = Add->getOperand(0).getNode();
7940 for (SDNode::use_iterator UI = BasePtr->use_begin(),
7941 UE = BasePtr->use_end(); UI != UE; ++UI) {
7942 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
7943 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
7944 Intrinsic::ppc_altivec_lvsl) {
7945 // We've found another LVSL, and this address if an aligned
7946 // multiple of that one. The results will be the same, so use the
7947 // one we've just found instead.
7949 return SDValue(*UI, 0);
7957 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
7958 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
7959 N->getOperand(0).hasOneUse() &&
7960 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
7961 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7962 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7963 N->getValueType(0) == MVT::i64))) {
7964 SDValue Load = N->getOperand(0);
7965 LoadSDNode *LD = cast<LoadSDNode>(Load);
7966 // Create the byte-swapping load.
7968 LD->getChain(), // Chain
7969 LD->getBasePtr(), // Ptr
7970 DAG.getValueType(N->getValueType(0)) // VT
7973 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
7974 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
7975 MVT::i64 : MVT::i32, MVT::Other),
7976 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
7978 // If this is an i16 load, insert the truncate.
7979 SDValue ResVal = BSLoad;
7980 if (N->getValueType(0) == MVT::i16)
7981 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
7983 // First, combine the bswap away. This makes the value produced by the
7985 DCI.CombineTo(N, ResVal);
7987 // Next, combine the load away, we give it a bogus result value but a real
7988 // chain result. The result value is dead because the bswap is dead.
7989 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
7991 // Return N so it doesn't get rechecked!
7992 return SDValue(N, 0);
7996 case PPCISD::VCMP: {
7997 // If a VCMPo node already exists with exactly the same operands as this
7998 // node, use its result instead of this node (VCMPo computes both a CR6 and
7999 // a normal output).
8001 if (!N->getOperand(0).hasOneUse() &&
8002 !N->getOperand(1).hasOneUse() &&
8003 !N->getOperand(2).hasOneUse()) {
8005 // Scan all of the users of the LHS, looking for VCMPo's that match.
8006 SDNode *VCMPoNode = 0;
8008 SDNode *LHSN = N->getOperand(0).getNode();
8009 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8011 if (UI->getOpcode() == PPCISD::VCMPo &&
8012 UI->getOperand(1) == N->getOperand(1) &&
8013 UI->getOperand(2) == N->getOperand(2) &&
8014 UI->getOperand(0) == N->getOperand(0)) {
8019 // If there is no VCMPo node, or if the flag value has a single use, don't
8021 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8024 // Look at the (necessarily single) use of the flag value. If it has a
8025 // chain, this transformation is more complex. Note that multiple things
8026 // could use the value result, which we should ignore.
8027 SDNode *FlagUser = 0;
8028 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8029 FlagUser == 0; ++UI) {
8030 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8032 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8033 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8040 // If the user is a MFOCRF instruction, we know this is safe.
8041 // Otherwise we give up for right now.
8042 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8043 return SDValue(VCMPoNode, 0);
8048 SDValue Cond = N->getOperand(1);
8049 SDValue Target = N->getOperand(2);
8051 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8052 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8053 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8055 // We now need to make the intrinsic dead (it cannot be instruction
8057 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8058 assert(Cond.getNode()->hasOneUse() &&
8059 "Counter decrement has more than one use");
8061 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8062 N->getOperand(0), Target);
8067 // If this is a branch on an altivec predicate comparison, lower this so
8068 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8069 // lowering is done pre-legalize, because the legalizer lowers the predicate
8070 // compare down to code that is difficult to reassemble.
8071 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8072 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8074 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8075 // value. If so, pass-through the AND to get to the intrinsic.
8076 if (LHS.getOpcode() == ISD::AND &&
8077 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8078 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8079 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8080 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8081 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8083 LHS = LHS.getOperand(0);
8085 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8086 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8087 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8088 isa<ConstantSDNode>(RHS)) {
8089 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8090 "Counter decrement comparison is not EQ or NE");
8092 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8093 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8094 (CC == ISD::SETNE && !Val);
8096 // We now need to make the intrinsic dead (it cannot be instruction
8098 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8099 assert(LHS.getNode()->hasOneUse() &&
8100 "Counter decrement has more than one use");
8102 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8103 N->getOperand(0), N->getOperand(4));
8109 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8110 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8111 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8112 assert(isDot && "Can't compare against a vector result!");
8114 // If this is a comparison against something other than 0/1, then we know
8115 // that the condition is never/always true.
8116 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8117 if (Val != 0 && Val != 1) {
8118 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8119 return N->getOperand(0);
8120 // Always !=, turn it into an unconditional branch.
8121 return DAG.getNode(ISD::BR, dl, MVT::Other,
8122 N->getOperand(0), N->getOperand(4));
8125 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8127 // Create the PPCISD altivec 'dot' comparison node.
8129 LHS.getOperand(2), // LHS of compare
8130 LHS.getOperand(3), // RHS of compare
8131 DAG.getConstant(CompareOpc, MVT::i32)
8133 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8134 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
8136 // Unpack the result based on how the target uses it.
8137 PPC::Predicate CompOpc;
8138 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8139 default: // Can't happen, don't crash on invalid number though.
8140 case 0: // Branch on the value of the EQ bit of CR6.
8141 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8143 case 1: // Branch on the inverted value of the EQ bit of CR6.
8144 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8146 case 2: // Branch on the value of the LT bit of CR6.
8147 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8149 case 3: // Branch on the inverted value of the LT bit of CR6.
8150 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8154 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8155 DAG.getConstant(CompOpc, MVT::i32),
8156 DAG.getRegister(PPC::CR6, MVT::i32),
8157 N->getOperand(4), CompNode.getValue(1));
8166 //===----------------------------------------------------------------------===//
8167 // Inline Assembly Support
8168 //===----------------------------------------------------------------------===//
8170 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8173 const SelectionDAG &DAG,
8174 unsigned Depth) const {
8175 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8176 switch (Op.getOpcode()) {
8178 case PPCISD::LBRX: {
8179 // lhbrx is known to have the top bits cleared out.
8180 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8181 KnownZero = 0xFFFF0000;
8184 case ISD::INTRINSIC_WO_CHAIN: {
8185 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8187 case Intrinsic::ppc_altivec_vcmpbfp_p:
8188 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8189 case Intrinsic::ppc_altivec_vcmpequb_p:
8190 case Intrinsic::ppc_altivec_vcmpequh_p:
8191 case Intrinsic::ppc_altivec_vcmpequw_p:
8192 case Intrinsic::ppc_altivec_vcmpgefp_p:
8193 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8194 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8195 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8196 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8197 case Intrinsic::ppc_altivec_vcmpgtub_p:
8198 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8199 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8200 KnownZero = ~1U; // All bits but the low one are known to be zero.
8208 /// getConstraintType - Given a constraint, return the type of
8209 /// constraint it is for this target.
8210 PPCTargetLowering::ConstraintType
8211 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8212 if (Constraint.size() == 1) {
8213 switch (Constraint[0]) {
8220 return C_RegisterClass;
8222 // FIXME: While Z does indicate a memory constraint, it specifically
8223 // indicates an r+r address (used in conjunction with the 'y' modifier
8224 // in the replacement string). Currently, we're forcing the base
8225 // register to be r0 in the asm printer (which is interpreted as zero)
8226 // and forming the complete address in the second register. This is
8231 return TargetLowering::getConstraintType(Constraint);
8234 /// Examine constraint type and operand type and determine a weight value.
8235 /// This object must already have been set up with the operand type
8236 /// and the current alternative constraint selected.
8237 TargetLowering::ConstraintWeight
8238 PPCTargetLowering::getSingleConstraintMatchWeight(
8239 AsmOperandInfo &info, const char *constraint) const {
8240 ConstraintWeight weight = CW_Invalid;
8241 Value *CallOperandVal = info.CallOperandVal;
8242 // If we don't have a value, we can't do a match,
8243 // but allow it at the lowest weight.
8244 if (CallOperandVal == NULL)
8246 Type *type = CallOperandVal->getType();
8247 // Look at the constraint type.
8248 switch (*constraint) {
8250 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8253 if (type->isIntegerTy())
8254 weight = CW_Register;
8257 if (type->isFloatTy())
8258 weight = CW_Register;
8261 if (type->isDoubleTy())
8262 weight = CW_Register;
8265 if (type->isVectorTy())
8266 weight = CW_Register;
8269 weight = CW_Register;
8278 std::pair<unsigned, const TargetRegisterClass*>
8279 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8281 if (Constraint.size() == 1) {
8282 // GCC RS6000 Constraint Letters
8283 switch (Constraint[0]) {
8285 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8286 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8287 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8289 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8290 return std::make_pair(0U, &PPC::G8RCRegClass);
8291 return std::make_pair(0U, &PPC::GPRCRegClass);
8293 if (VT == MVT::f32 || VT == MVT::i32)
8294 return std::make_pair(0U, &PPC::F4RCRegClass);
8295 if (VT == MVT::f64 || VT == MVT::i64)
8296 return std::make_pair(0U, &PPC::F8RCRegClass);
8299 return std::make_pair(0U, &PPC::VRRCRegClass);
8301 return std::make_pair(0U, &PPC::CRRCRegClass);
8305 std::pair<unsigned, const TargetRegisterClass*> R =
8306 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8308 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8309 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8310 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8312 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8313 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8314 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8315 PPC::GPRCRegClass.contains(R.first)) {
8316 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8317 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8318 PPC::sub_32, &PPC::G8RCRegClass),
8319 &PPC::G8RCRegClass);
8326 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8327 /// vector. If it is invalid, don't add anything to Ops.
8328 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8329 std::string &Constraint,
8330 std::vector<SDValue>&Ops,
8331 SelectionDAG &DAG) const {
8332 SDValue Result(0,0);
8334 // Only support length 1 constraints.
8335 if (Constraint.length() > 1) return;
8337 char Letter = Constraint[0];
8348 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8349 if (!CST) return; // Must be an immediate to match.
8350 unsigned Value = CST->getZExtValue();
8352 default: llvm_unreachable("Unknown constraint letter!");
8353 case 'I': // "I" is a signed 16-bit constant.
8354 if ((short)Value == (int)Value)
8355 Result = DAG.getTargetConstant(Value, Op.getValueType());
8357 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8358 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8359 if ((short)Value == 0)
8360 Result = DAG.getTargetConstant(Value, Op.getValueType());
8362 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8363 if ((Value >> 16) == 0)
8364 Result = DAG.getTargetConstant(Value, Op.getValueType());
8366 case 'M': // "M" is a constant that is greater than 31.
8368 Result = DAG.getTargetConstant(Value, Op.getValueType());
8370 case 'N': // "N" is a positive constant that is an exact power of two.
8371 if ((int)Value > 0 && isPowerOf2_32(Value))
8372 Result = DAG.getTargetConstant(Value, Op.getValueType());
8374 case 'O': // "O" is the constant zero.
8376 Result = DAG.getTargetConstant(Value, Op.getValueType());
8378 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8379 if ((short)-Value == (int)-Value)
8380 Result = DAG.getTargetConstant(Value, Op.getValueType());
8387 if (Result.getNode()) {
8388 Ops.push_back(Result);
8392 // Handle standard constraint letters.
8393 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8396 // isLegalAddressingMode - Return true if the addressing mode represented
8397 // by AM is legal for this target, for a load/store of the specified type.
8398 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8400 // FIXME: PPC does not allow r+i addressing modes for vectors!
8402 // PPC allows a sign-extended 16-bit immediate field.
8403 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8406 // No global is ever allowed as a base.
8410 // PPC only support r+r,
8412 case 0: // "r+i" or just "i", depending on HasBaseReg.
8415 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8417 // Otherwise we have r+r or r+i.
8420 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8422 // Allow 2*r as r+r.
8425 // No other scales are supported.
8432 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8433 SelectionDAG &DAG) const {
8434 MachineFunction &MF = DAG.getMachineFunction();
8435 MachineFrameInfo *MFI = MF.getFrameInfo();
8436 MFI->setReturnAddressIsTaken(true);
8438 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8442 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8444 // Make sure the function does not optimize away the store of the RA to
8446 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8447 FuncInfo->setLRStoreRequired();
8448 bool isPPC64 = PPCSubTarget.isPPC64();
8449 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8452 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8455 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8456 isPPC64? MVT::i64 : MVT::i32);
8457 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8458 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8460 MachinePointerInfo(), false, false, false, 0);
8463 // Just load the return address off the stack.
8464 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8465 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8466 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8469 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8470 SelectionDAG &DAG) const {
8472 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8474 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8475 bool isPPC64 = PtrVT == MVT::i64;
8477 MachineFunction &MF = DAG.getMachineFunction();
8478 MachineFrameInfo *MFI = MF.getFrameInfo();
8479 MFI->setFrameAddressIsTaken(true);
8481 // Naked functions never have a frame pointer, and so we use r1. For all
8482 // other functions, this decision must be delayed until during PEI.
8484 if (MF.getFunction()->getAttributes().hasAttribute(
8485 AttributeSet::FunctionIndex, Attribute::Naked))
8486 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8488 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8490 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8493 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8494 FrameAddr, MachinePointerInfo(), false, false,
8500 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8501 // The PowerPC target isn't yet aware of offsets.
8505 /// getOptimalMemOpType - Returns the target specific optimal type for load
8506 /// and store operations as a result of memset, memcpy, and memmove
8507 /// lowering. If DstAlign is zero that means it's safe to destination
8508 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8509 /// means there isn't a need to check it against alignment requirement,
8510 /// probably because the source does not need to be loaded. If 'IsMemset' is
8511 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8512 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8513 /// source is constant so it does not need to be loaded.
8514 /// It returns EVT::Other if the type should be determined using generic
8515 /// target-independent logic.
8516 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8517 unsigned DstAlign, unsigned SrcAlign,
8518 bool IsMemset, bool ZeroMemset,
8520 MachineFunction &MF) const {
8521 if (this->PPCSubTarget.isPPC64()) {
8528 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8531 if (DisablePPCUnaligned)
8534 // PowerPC supports unaligned memory access for simple non-vector types.
8535 // Although accessing unaligned addresses is not as efficient as accessing
8536 // aligned addresses, it is generally more efficient than manual expansion,
8537 // and generally only traps for software emulation when crossing page
8543 if (VT.getSimpleVT().isVector())
8546 if (VT == MVT::ppcf128)
8555 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8556 VT = VT.getScalarType();
8561 switch (VT.getSimpleVT().SimpleTy) {
8572 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8573 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8574 return TargetLowering::getSchedulingPreference(N);
8579 // Create a fast isel object.
8581 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8582 const TargetLibraryInfo *LibInfo) const {
8583 return PPC::createFastISel(FuncInfo, LibInfo);