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 if (isPPC64 || Subtarget->hasFPCVT()) {
104 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
105 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
106 isPPC64 ? MVT::i64 : MVT::i32);
107 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
108 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
109 isPPC64 ? MVT::i64 : MVT::i32);
111 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
112 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
115 // PowerPC does not support direct load / store of condition registers
116 setOperationAction(ISD::LOAD, MVT::i1, Custom);
117 setOperationAction(ISD::STORE, MVT::i1, Custom);
119 // FIXME: Remove this once the ANDI glue bug is fixed:
121 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
126 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
127 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
128 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
133 // This is used in the ppcf128->int sequence. Note it has different semantics
134 // from FP_ROUND: that rounds to nearest, this rounds to zero.
135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137 // We do not currently implement these libm ops for PowerPC.
138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145 // PowerPC has no SREM/UREM instructions
146 setOperationAction(ISD::SREM, MVT::i32, Expand);
147 setOperationAction(ISD::UREM, MVT::i32, Expand);
148 setOperationAction(ISD::SREM, MVT::i64, Expand);
149 setOperationAction(ISD::UREM, MVT::i64, Expand);
151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161 // We don't support sin/cos/sqrt/fmod/pow
162 setOperationAction(ISD::FSIN , MVT::f64, Expand);
163 setOperationAction(ISD::FCOS , MVT::f64, Expand);
164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165 setOperationAction(ISD::FREM , MVT::f64, Expand);
166 setOperationAction(ISD::FPOW , MVT::f64, Expand);
167 setOperationAction(ISD::FMA , MVT::f64, Legal);
168 setOperationAction(ISD::FSIN , MVT::f32, Expand);
169 setOperationAction(ISD::FCOS , MVT::f32, Expand);
170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171 setOperationAction(ISD::FREM , MVT::f32, Expand);
172 setOperationAction(ISD::FPOW , MVT::f32, Expand);
173 setOperationAction(ISD::FMA , MVT::f32, Legal);
175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177 // If we're enabling GP optimizations, use hardware square root
178 if (!Subtarget->hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath &&
180 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
181 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183 if (!Subtarget->hasFSQRT() &&
184 !(TM.Options.UnsafeFPMath &&
185 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
186 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188 if (Subtarget->hasFCPSGN()) {
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
196 if (Subtarget->hasFPRND()) {
197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200 setOperationAction(ISD::FROUND, MVT::f64, Legal);
202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205 setOperationAction(ISD::FROUND, MVT::f32, Legal);
208 // PowerPC does not have BSWAP, CTPOP or CTTZ
209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218 if (Subtarget->hasPOPCNTD()) {
219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
226 // PowerPC does not have ROTR
227 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
228 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
230 if (!Subtarget->useCRBits()) {
231 // PowerPC does not have Select
232 setOperationAction(ISD::SELECT, MVT::i32, Expand);
233 setOperationAction(ISD::SELECT, MVT::i64, Expand);
234 setOperationAction(ISD::SELECT, MVT::f32, Expand);
235 setOperationAction(ISD::SELECT, MVT::f64, Expand);
238 // PowerPC wants to turn select_cc of FP into fsel when possible.
239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 // PowerPC wants to optimize integer setcc a bit
243 if (!Subtarget->useCRBits())
244 setOperationAction(ISD::SETCC, MVT::i32, Custom);
246 // PowerPC does not have BRCOND which requires SetCC
247 if (!Subtarget->useCRBits())
248 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 // PowerPC does not have [U|S]INT_TO_FP
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264 // We cannot sextinreg(i1). Expand to shifts.
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269 // support continuation, user-level threading, and etc.. As a result, no
270 // other SjLj exception interfaces are implemented and please don't build
271 // your own exception handling based on them.
272 // LLVM/Clang supports zero-cost DWARF exception handling.
273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276 // We want to legalize GlobalAddress and ConstantPool nodes into the
277 // appropriate instructions to materialize the address.
278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
287 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
292 // TRAMPOLINE is custom lowered.
293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 if (Subtarget->isSVR4ABI()) {
301 // VAARG always uses double-word chunks, so promote anything smaller.
302 setOperationAction(ISD::VAARG, MVT::i1, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i8, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i16, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i32, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::Other, Expand);
312 // VAARG is custom lowered with the 32-bit SVR4 ABI.
313 setOperationAction(ISD::VAARG, MVT::Other, Custom);
314 setOperationAction(ISD::VAARG, MVT::i64, Custom);
317 setOperationAction(ISD::VAARG, MVT::Other, Expand);
319 if (Subtarget->isSVR4ABI() && !isPPC64)
320 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
323 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
325 // Use the default implementation.
326 setOperationAction(ISD::VAEND , MVT::Other, Expand);
327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
332 // We want to custom lower some of our intrinsics.
333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335 // To handle counter-based loop conditions.
336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338 // Comparisons that require checking two conditions.
339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352 if (Subtarget->has64BitSupport()) {
353 // They also have instructions for converting between i64 and fp.
354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358 // This is just the low 32 bits of a (signed) fp->i64 conversion.
359 // We cannot do this with Promote because i64 is not a legal type.
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
369 // With the instructions enabled under FPCVT, we can do everything.
370 if (PPCSubTarget.hasFPCVT()) {
371 if (Subtarget->has64BitSupport()) {
372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
384 if (Subtarget->use64BitRegs()) {
385 // 64-bit PowerPC implementations can support i64 types directly
386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389 // 64-bit PowerPC wants to expand i128 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394 // 32-bit PowerPC wants to expand i64 shifts itself.
395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
400 if (Subtarget->hasAltivec()) {
401 // First set operation action for all vector types to expand. Then we
402 // will selectively turn on ones that can be effectively codegen'd.
403 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
405 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
407 // add/sub are legal for all supported vector VT's.
408 setOperationAction(ISD::ADD , VT, Legal);
409 setOperationAction(ISD::SUB , VT, Legal);
411 // We promote all shuffles to v16i8.
412 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
413 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
415 // We promote all non-typed operations to v4i32.
416 setOperationAction(ISD::AND , VT, Promote);
417 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
418 setOperationAction(ISD::OR , VT, Promote);
419 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
420 setOperationAction(ISD::XOR , VT, Promote);
421 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
422 setOperationAction(ISD::LOAD , VT, Promote);
423 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
424 setOperationAction(ISD::SELECT, VT, Promote);
425 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
426 setOperationAction(ISD::STORE, VT, Promote);
427 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
429 // No other operations are legal.
430 setOperationAction(ISD::MUL , VT, Expand);
431 setOperationAction(ISD::SDIV, VT, Expand);
432 setOperationAction(ISD::SREM, VT, Expand);
433 setOperationAction(ISD::UDIV, VT, Expand);
434 setOperationAction(ISD::UREM, VT, Expand);
435 setOperationAction(ISD::FDIV, VT, Expand);
436 setOperationAction(ISD::FREM, VT, Expand);
437 setOperationAction(ISD::FNEG, VT, Expand);
438 setOperationAction(ISD::FSQRT, VT, Expand);
439 setOperationAction(ISD::FLOG, VT, Expand);
440 setOperationAction(ISD::FLOG10, VT, Expand);
441 setOperationAction(ISD::FLOG2, VT, Expand);
442 setOperationAction(ISD::FEXP, VT, Expand);
443 setOperationAction(ISD::FEXP2, VT, Expand);
444 setOperationAction(ISD::FSIN, VT, Expand);
445 setOperationAction(ISD::FCOS, VT, Expand);
446 setOperationAction(ISD::FABS, VT, Expand);
447 setOperationAction(ISD::FPOWI, VT, Expand);
448 setOperationAction(ISD::FFLOOR, VT, Expand);
449 setOperationAction(ISD::FCEIL, VT, Expand);
450 setOperationAction(ISD::FTRUNC, VT, Expand);
451 setOperationAction(ISD::FRINT, VT, Expand);
452 setOperationAction(ISD::FNEARBYINT, VT, Expand);
453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
454 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
455 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
456 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
458 setOperationAction(ISD::UDIVREM, VT, Expand);
459 setOperationAction(ISD::SDIVREM, VT, Expand);
460 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
461 setOperationAction(ISD::FPOW, VT, Expand);
462 setOperationAction(ISD::CTPOP, VT, Expand);
463 setOperationAction(ISD::CTLZ, VT, Expand);
464 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
465 setOperationAction(ISD::CTTZ, VT, Expand);
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
467 setOperationAction(ISD::VSELECT, VT, Expand);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
470 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
471 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
472 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
473 setTruncStoreAction(VT, InnerVT, Expand);
475 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
476 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
477 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
480 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
481 // with merges, splats, etc.
482 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
484 setOperationAction(ISD::AND , MVT::v4i32, Legal);
485 setOperationAction(ISD::OR , MVT::v4i32, Legal);
486 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
487 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
488 setOperationAction(ISD::SELECT, MVT::v4i32,
489 Subtarget->useCRBits() ? Legal : Expand);
490 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
491 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
492 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
493 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
494 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
495 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
496 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
497 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
498 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
500 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
501 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
502 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
503 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
505 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
506 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
508 if (TM.Options.UnsafeFPMath || Subtarget->hasVSX()) {
509 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
510 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
513 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
514 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
515 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
517 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
518 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
520 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
521 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
522 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
523 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
525 // Altivec does not contain unordered floating-point compare instructions
526 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
527 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
528 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
529 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
530 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
531 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
533 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
534 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
536 if (Subtarget->hasVSX()) {
537 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
538 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
540 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
541 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
542 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
543 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
544 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
546 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
548 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
549 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
551 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
552 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
554 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
555 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
558 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
560 // Share the Altivec comparison restrictions.
561 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
562 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
563 setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
564 setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
566 setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
568 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
569 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
571 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
572 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
574 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
576 addRegisterClass(MVT::f64, &PPC::VSRCRegClass);
578 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
579 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
581 // VSX v2i64 only supports non-arithmetic operations.
582 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
583 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
585 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
586 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
587 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
589 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
590 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
591 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
592 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
594 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
596 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
597 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
598 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
599 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
601 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
605 if (Subtarget->has64BitSupport()) {
606 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
607 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
610 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
611 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
612 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
613 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
615 setBooleanContents(ZeroOrOneBooleanContent);
616 // Altivec instructions set fields to all zeros or all ones.
617 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
620 setStackPointerRegisterToSaveRestore(PPC::X1);
621 setExceptionPointerRegister(PPC::X3);
622 setExceptionSelectorRegister(PPC::X4);
624 setStackPointerRegisterToSaveRestore(PPC::R1);
625 setExceptionPointerRegister(PPC::R3);
626 setExceptionSelectorRegister(PPC::R4);
629 // We have target-specific dag combine patterns for the following nodes:
630 setTargetDAGCombine(ISD::SINT_TO_FP);
631 setTargetDAGCombine(ISD::LOAD);
632 setTargetDAGCombine(ISD::STORE);
633 setTargetDAGCombine(ISD::BR_CC);
634 if (Subtarget->useCRBits())
635 setTargetDAGCombine(ISD::BRCOND);
636 setTargetDAGCombine(ISD::BSWAP);
637 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
639 setTargetDAGCombine(ISD::SIGN_EXTEND);
640 setTargetDAGCombine(ISD::ZERO_EXTEND);
641 setTargetDAGCombine(ISD::ANY_EXTEND);
643 if (Subtarget->useCRBits()) {
644 setTargetDAGCombine(ISD::TRUNCATE);
645 setTargetDAGCombine(ISD::SETCC);
646 setTargetDAGCombine(ISD::SELECT_CC);
649 // Use reciprocal estimates.
650 if (TM.Options.UnsafeFPMath) {
651 setTargetDAGCombine(ISD::FDIV);
652 setTargetDAGCombine(ISD::FSQRT);
655 // Darwin long double math library functions have $LDBL128 appended.
656 if (Subtarget->isDarwin()) {
657 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
658 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
659 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
660 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
661 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
662 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
663 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
664 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
665 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
666 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
669 // With 32 condition bits, we don't need to sink (and duplicate) compares
670 // aggressively in CodeGenPrep.
671 if (Subtarget->useCRBits())
672 setHasMultipleConditionRegisters();
674 setMinFunctionAlignment(2);
675 if (PPCSubTarget.isDarwin())
676 setPrefFunctionAlignment(4);
678 if (isPPC64 && Subtarget->isJITCodeModel())
679 // Temporary workaround for the inability of PPC64 JIT to handle jump
681 setSupportJumpTables(false);
683 setInsertFencesForAtomic(true);
685 if (Subtarget->enableMachineScheduler())
686 setSchedulingPreference(Sched::Source);
688 setSchedulingPreference(Sched::Hybrid);
690 computeRegisterProperties();
692 // The Freescale cores does better with aggressive inlining of memcpy and
693 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
694 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
695 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
696 MaxStoresPerMemset = 32;
697 MaxStoresPerMemsetOptSize = 16;
698 MaxStoresPerMemcpy = 32;
699 MaxStoresPerMemcpyOptSize = 8;
700 MaxStoresPerMemmove = 32;
701 MaxStoresPerMemmoveOptSize = 8;
703 setPrefFunctionAlignment(4);
707 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
708 /// the desired ByVal argument alignment.
709 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
710 unsigned MaxMaxAlign) {
711 if (MaxAlign == MaxMaxAlign)
713 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
714 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
716 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
718 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
719 unsigned EltAlign = 0;
720 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
721 if (EltAlign > MaxAlign)
723 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
724 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
725 unsigned EltAlign = 0;
726 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
727 if (EltAlign > MaxAlign)
729 if (MaxAlign == MaxMaxAlign)
735 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
736 /// function arguments in the caller parameter area.
737 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
738 // Darwin passes everything on 4 byte boundary.
739 if (PPCSubTarget.isDarwin())
742 // 16byte and wider vectors are passed on 16byte boundary.
743 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
744 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
745 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
746 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
750 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
753 case PPCISD::FSEL: return "PPCISD::FSEL";
754 case PPCISD::FCFID: return "PPCISD::FCFID";
755 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
756 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
757 case PPCISD::FRE: return "PPCISD::FRE";
758 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
759 case PPCISD::STFIWX: return "PPCISD::STFIWX";
760 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
761 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
762 case PPCISD::VPERM: return "PPCISD::VPERM";
763 case PPCISD::Hi: return "PPCISD::Hi";
764 case PPCISD::Lo: return "PPCISD::Lo";
765 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
766 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
767 case PPCISD::LOAD: return "PPCISD::LOAD";
768 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
769 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
770 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
771 case PPCISD::SRL: return "PPCISD::SRL";
772 case PPCISD::SRA: return "PPCISD::SRA";
773 case PPCISD::SHL: return "PPCISD::SHL";
774 case PPCISD::CALL: return "PPCISD::CALL";
775 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
776 case PPCISD::MTCTR: return "PPCISD::MTCTR";
777 case PPCISD::BCTRL: return "PPCISD::BCTRL";
778 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
779 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
780 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
781 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
782 case PPCISD::VCMP: return "PPCISD::VCMP";
783 case PPCISD::VCMPo: return "PPCISD::VCMPo";
784 case PPCISD::LBRX: return "PPCISD::LBRX";
785 case PPCISD::STBRX: return "PPCISD::STBRX";
786 case PPCISD::LARX: return "PPCISD::LARX";
787 case PPCISD::STCX: return "PPCISD::STCX";
788 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
789 case PPCISD::BDNZ: return "PPCISD::BDNZ";
790 case PPCISD::BDZ: return "PPCISD::BDZ";
791 case PPCISD::MFFS: return "PPCISD::MFFS";
792 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
793 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
794 case PPCISD::CR6SET: return "PPCISD::CR6SET";
795 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
796 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
797 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
798 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
799 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
800 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
801 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
802 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
803 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
804 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
805 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
806 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
807 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
808 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
809 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
810 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
811 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
812 case PPCISD::SC: return "PPCISD::SC";
816 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
818 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
819 return VT.changeVectorElementTypeToInteger();
822 //===----------------------------------------------------------------------===//
823 // Node matching predicates, for use by the tblgen matching code.
824 //===----------------------------------------------------------------------===//
826 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
827 static bool isFloatingPointZero(SDValue Op) {
828 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
829 return CFP->getValueAPF().isZero();
830 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
831 // Maybe this has already been legalized into the constant pool?
832 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
833 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
834 return CFP->getValueAPF().isZero();
839 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
840 /// true if Op is undef or if it matches the specified value.
841 static bool isConstantOrUndef(int Op, int Val) {
842 return Op < 0 || Op == Val;
845 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
846 /// VPKUHUM instruction.
847 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
849 for (unsigned i = 0; i != 16; ++i)
850 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
853 for (unsigned i = 0; i != 8; ++i)
854 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
855 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
861 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
862 /// VPKUWUM instruction.
863 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
865 for (unsigned i = 0; i != 16; i += 2)
866 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
867 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
870 for (unsigned i = 0; i != 8; i += 2)
871 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
872 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
873 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
874 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
880 /// isVMerge - Common function, used to match vmrg* shuffles.
882 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
883 unsigned LHSStart, unsigned RHSStart) {
884 if (N->getValueType(0) != MVT::v16i8)
886 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
887 "Unsupported merge size!");
889 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
890 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
891 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
892 LHSStart+j+i*UnitSize) ||
893 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
894 RHSStart+j+i*UnitSize))
900 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
901 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
902 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
905 return isVMerge(N, UnitSize, 8, 24);
906 return isVMerge(N, UnitSize, 8, 8);
909 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
910 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
911 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
914 return isVMerge(N, UnitSize, 0, 16);
915 return isVMerge(N, UnitSize, 0, 0);
919 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
920 /// amount, otherwise return -1.
921 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
922 if (N->getValueType(0) != MVT::v16i8)
925 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
927 // Find the first non-undef value in the shuffle mask.
929 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
932 if (i == 16) return -1; // all undef.
934 // Otherwise, check to see if the rest of the elements are consecutively
935 // numbered from this value.
936 unsigned ShiftAmt = SVOp->getMaskElt(i);
937 if (ShiftAmt < i) return -1;
941 // Check the rest of the elements to see if they are consecutive.
942 for (++i; i != 16; ++i)
943 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
946 // Check the rest of the elements to see if they are consecutive.
947 for (++i; i != 16; ++i)
948 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
954 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
955 /// specifies a splat of a single element that is suitable for input to
956 /// VSPLTB/VSPLTH/VSPLTW.
957 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
958 assert(N->getValueType(0) == MVT::v16i8 &&
959 (EltSize == 1 || EltSize == 2 || EltSize == 4));
961 // This is a splat operation if each element of the permute is the same, and
962 // if the value doesn't reference the second vector.
963 unsigned ElementBase = N->getMaskElt(0);
965 // FIXME: Handle UNDEF elements too!
966 if (ElementBase >= 16)
969 // Check that the indices are consecutive, in the case of a multi-byte element
970 // splatted with a v16i8 mask.
971 for (unsigned i = 1; i != EltSize; ++i)
972 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
975 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
976 if (N->getMaskElt(i) < 0) continue;
977 for (unsigned j = 0; j != EltSize; ++j)
978 if (N->getMaskElt(i+j) != N->getMaskElt(j))
984 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
986 bool PPC::isAllNegativeZeroVector(SDNode *N) {
987 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
989 APInt APVal, APUndef;
993 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
994 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
995 return CFP->getValueAPF().isNegZero();
1000 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1001 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1002 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
1003 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1004 assert(isSplatShuffleMask(SVOp, EltSize));
1005 return SVOp->getMaskElt(0) / EltSize;
1008 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1009 /// by using a vspltis[bhw] instruction of the specified element size, return
1010 /// the constant being splatted. The ByteSize field indicates the number of
1011 /// bytes of each element [124] -> [bhw].
1012 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1013 SDValue OpVal(0, 0);
1015 // If ByteSize of the splat is bigger than the element size of the
1016 // build_vector, then we have a case where we are checking for a splat where
1017 // multiple elements of the buildvector are folded together into a single
1018 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1019 unsigned EltSize = 16/N->getNumOperands();
1020 if (EltSize < ByteSize) {
1021 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1022 SDValue UniquedVals[4];
1023 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1025 // See if all of the elements in the buildvector agree across.
1026 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1027 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1028 // If the element isn't a constant, bail fully out.
1029 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1032 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
1033 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1034 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1035 return SDValue(); // no match.
1038 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1039 // either constant or undef values that are identical for each chunk. See
1040 // if these chunks can form into a larger vspltis*.
1042 // Check to see if all of the leading entries are either 0 or -1. If
1043 // neither, then this won't fit into the immediate field.
1044 bool LeadingZero = true;
1045 bool LeadingOnes = true;
1046 for (unsigned i = 0; i != Multiple-1; ++i) {
1047 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
1049 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1050 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1052 // Finally, check the least significant entry.
1054 if (UniquedVals[Multiple-1].getNode() == 0)
1055 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1056 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1058 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1061 if (UniquedVals[Multiple-1].getNode() == 0)
1062 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1063 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1064 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1065 return DAG.getTargetConstant(Val, MVT::i32);
1071 // Check to see if this buildvec has a single non-undef value in its elements.
1072 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1073 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1074 if (OpVal.getNode() == 0)
1075 OpVal = N->getOperand(i);
1076 else if (OpVal != N->getOperand(i))
1080 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
1082 unsigned ValSizeInBytes = EltSize;
1084 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1085 Value = CN->getZExtValue();
1086 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1087 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1088 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1091 // If the splat value is larger than the element value, then we can never do
1092 // this splat. The only case that we could fit the replicated bits into our
1093 // immediate field for would be zero, and we prefer to use vxor for it.
1094 if (ValSizeInBytes < ByteSize) return SDValue();
1096 // If the element value is larger than the splat value, cut it in half and
1097 // check to see if the two halves are equal. Continue doing this until we
1098 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1099 while (ValSizeInBytes > ByteSize) {
1100 ValSizeInBytes >>= 1;
1102 // If the top half equals the bottom half, we're still ok.
1103 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1104 (Value & ((1 << (8*ValSizeInBytes))-1)))
1108 // Properly sign extend the value.
1109 int MaskVal = SignExtend32(Value, ByteSize * 8);
1111 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1112 if (MaskVal == 0) return SDValue();
1114 // Finally, if this value fits in a 5 bit sext field, return it
1115 if (SignExtend32<5>(MaskVal) == MaskVal)
1116 return DAG.getTargetConstant(MaskVal, MVT::i32);
1120 //===----------------------------------------------------------------------===//
1121 // Addressing Mode Selection
1122 //===----------------------------------------------------------------------===//
1124 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1125 /// or 64-bit immediate, and if the value can be accurately represented as a
1126 /// sign extension from a 16-bit value. If so, this returns true and the
1128 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1129 if (N->getOpcode() != ISD::Constant)
1132 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1133 if (N->getValueType(0) == MVT::i32)
1134 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1136 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1138 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1139 return isIntS16Immediate(Op.getNode(), Imm);
1143 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1144 /// can be represented as an indexed [r+r] operation. Returns false if it
1145 /// can be more efficiently represented with [r+imm].
1146 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1148 SelectionDAG &DAG) const {
1150 if (N.getOpcode() == ISD::ADD) {
1151 if (isIntS16Immediate(N.getOperand(1), imm))
1152 return false; // r+i
1153 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1154 return false; // r+i
1156 Base = N.getOperand(0);
1157 Index = N.getOperand(1);
1159 } else if (N.getOpcode() == ISD::OR) {
1160 if (isIntS16Immediate(N.getOperand(1), imm))
1161 return false; // r+i can fold it if we can.
1163 // If this is an or of disjoint bitfields, we can codegen this as an add
1164 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1166 APInt LHSKnownZero, LHSKnownOne;
1167 APInt RHSKnownZero, RHSKnownOne;
1168 DAG.ComputeMaskedBits(N.getOperand(0),
1169 LHSKnownZero, LHSKnownOne);
1171 if (LHSKnownZero.getBoolValue()) {
1172 DAG.ComputeMaskedBits(N.getOperand(1),
1173 RHSKnownZero, RHSKnownOne);
1174 // If all of the bits are known zero on the LHS or RHS, the add won't
1176 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1177 Base = N.getOperand(0);
1178 Index = N.getOperand(1);
1187 // If we happen to be doing an i64 load or store into a stack slot that has
1188 // less than a 4-byte alignment, then the frame-index elimination may need to
1189 // use an indexed load or store instruction (because the offset may not be a
1190 // multiple of 4). The extra register needed to hold the offset comes from the
1191 // register scavenger, and it is possible that the scavenger will need to use
1192 // an emergency spill slot. As a result, we need to make sure that a spill slot
1193 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1195 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1196 // FIXME: This does not handle the LWA case.
1200 // NOTE: We'll exclude negative FIs here, which come from argument
1201 // lowering, because there are no known test cases triggering this problem
1202 // using packed structures (or similar). We can remove this exclusion if
1203 // we find such a test case. The reason why this is so test-case driven is
1204 // because this entire 'fixup' is only to prevent crashes (from the
1205 // register scavenger) on not-really-valid inputs. For example, if we have:
1207 // %b = bitcast i1* %a to i64*
1208 // store i64* a, i64 b
1209 // then the store should really be marked as 'align 1', but is not. If it
1210 // were marked as 'align 1' then the indexed form would have been
1211 // instruction-selected initially, and the problem this 'fixup' is preventing
1212 // won't happen regardless.
1216 MachineFunction &MF = DAG.getMachineFunction();
1217 MachineFrameInfo *MFI = MF.getFrameInfo();
1219 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1223 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1224 FuncInfo->setHasNonRISpills();
1227 /// Returns true if the address N can be represented by a base register plus
1228 /// a signed 16-bit displacement [r+imm], and if it is not better
1229 /// represented as reg+reg. If Aligned is true, only accept displacements
1230 /// suitable for STD and friends, i.e. multiples of 4.
1231 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1234 bool Aligned) const {
1235 // FIXME dl should come from parent load or store, not from address
1237 // If this can be more profitably realized as r+r, fail.
1238 if (SelectAddressRegReg(N, Disp, Base, DAG))
1241 if (N.getOpcode() == ISD::ADD) {
1243 if (isIntS16Immediate(N.getOperand(1), imm) &&
1244 (!Aligned || (imm & 3) == 0)) {
1245 Disp = DAG.getTargetConstant(imm, N.getValueType());
1246 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1247 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1248 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1250 Base = N.getOperand(0);
1252 return true; // [r+i]
1253 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1254 // Match LOAD (ADD (X, Lo(G))).
1255 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1256 && "Cannot handle constant offsets yet!");
1257 Disp = N.getOperand(1).getOperand(0); // The global address.
1258 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1259 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1260 Disp.getOpcode() == ISD::TargetConstantPool ||
1261 Disp.getOpcode() == ISD::TargetJumpTable);
1262 Base = N.getOperand(0);
1263 return true; // [&g+r]
1265 } else if (N.getOpcode() == ISD::OR) {
1267 if (isIntS16Immediate(N.getOperand(1), imm) &&
1268 (!Aligned || (imm & 3) == 0)) {
1269 // If this is an or of disjoint bitfields, we can codegen this as an add
1270 // (for better address arithmetic) if the LHS and RHS of the OR are
1271 // provably disjoint.
1272 APInt LHSKnownZero, LHSKnownOne;
1273 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1275 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1276 // If all of the bits are known zero on the LHS or RHS, the add won't
1278 Base = N.getOperand(0);
1279 Disp = DAG.getTargetConstant(imm, N.getValueType());
1283 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1284 // Loading from a constant address.
1286 // If this address fits entirely in a 16-bit sext immediate field, codegen
1289 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1290 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1291 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1292 CN->getValueType(0));
1296 // Handle 32-bit sext immediates with LIS + addr mode.
1297 if ((CN->getValueType(0) == MVT::i32 ||
1298 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1299 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1300 int Addr = (int)CN->getZExtValue();
1302 // Otherwise, break this down into an LIS + disp.
1303 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1305 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1306 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1307 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1312 Disp = DAG.getTargetConstant(0, getPointerTy());
1313 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1314 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1315 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1318 return true; // [r+0]
1321 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1322 /// represented as an indexed [r+r] operation.
1323 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1325 SelectionDAG &DAG) const {
1326 // Check to see if we can easily represent this as an [r+r] address. This
1327 // will fail if it thinks that the address is more profitably represented as
1328 // reg+imm, e.g. where imm = 0.
1329 if (SelectAddressRegReg(N, Base, Index, DAG))
1332 // If the operand is an addition, always emit this as [r+r], since this is
1333 // better (for code size, and execution, as the memop does the add for free)
1334 // than emitting an explicit add.
1335 if (N.getOpcode() == ISD::ADD) {
1336 Base = N.getOperand(0);
1337 Index = N.getOperand(1);
1341 // Otherwise, do it the hard way, using R0 as the base register.
1342 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1348 /// getPreIndexedAddressParts - returns true by value, base pointer and
1349 /// offset pointer and addressing mode by reference if the node's address
1350 /// can be legally represented as pre-indexed load / store address.
1351 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1353 ISD::MemIndexedMode &AM,
1354 SelectionDAG &DAG) const {
1355 if (DisablePPCPreinc) return false;
1361 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1362 Ptr = LD->getBasePtr();
1363 VT = LD->getMemoryVT();
1364 Alignment = LD->getAlignment();
1365 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1366 Ptr = ST->getBasePtr();
1367 VT = ST->getMemoryVT();
1368 Alignment = ST->getAlignment();
1373 // PowerPC doesn't have preinc load/store instructions for vectors.
1377 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1379 // Common code will reject creating a pre-inc form if the base pointer
1380 // is a frame index, or if N is a store and the base pointer is either
1381 // the same as or a predecessor of the value being stored. Check for
1382 // those situations here, and try with swapped Base/Offset instead.
1385 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1388 SDValue Val = cast<StoreSDNode>(N)->getValue();
1389 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1394 std::swap(Base, Offset);
1400 // LDU/STU can only handle immediates that are a multiple of 4.
1401 if (VT != MVT::i64) {
1402 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1405 // LDU/STU need an address with at least 4-byte alignment.
1409 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1413 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1414 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1415 // sext i32 to i64 when addr mode is r+i.
1416 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1417 LD->getExtensionType() == ISD::SEXTLOAD &&
1418 isa<ConstantSDNode>(Offset))
1426 //===----------------------------------------------------------------------===//
1427 // LowerOperation implementation
1428 //===----------------------------------------------------------------------===//
1430 /// GetLabelAccessInfo - Return true if we should reference labels using a
1431 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1432 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1433 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1434 HiOpFlags = PPCII::MO_HA;
1435 LoOpFlags = PPCII::MO_LO;
1437 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1438 // non-darwin platform. We don't support PIC on other platforms yet.
1439 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1440 TM.getSubtarget<PPCSubtarget>().isDarwin();
1442 HiOpFlags |= PPCII::MO_PIC_FLAG;
1443 LoOpFlags |= PPCII::MO_PIC_FLAG;
1446 // If this is a reference to a global value that requires a non-lazy-ptr, make
1447 // sure that instruction lowering adds it.
1448 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1449 HiOpFlags |= PPCII::MO_NLP_FLAG;
1450 LoOpFlags |= PPCII::MO_NLP_FLAG;
1452 if (GV->hasHiddenVisibility()) {
1453 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1454 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1461 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1462 SelectionDAG &DAG) {
1463 EVT PtrVT = HiPart.getValueType();
1464 SDValue Zero = DAG.getConstant(0, PtrVT);
1467 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1468 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1470 // With PIC, the first instruction is actually "GR+hi(&G)".
1472 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1473 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1475 // Generate non-pic code that has direct accesses to the constant pool.
1476 // The address of the global is just (hi(&g)+lo(&g)).
1477 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1480 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1481 SelectionDAG &DAG) const {
1482 EVT PtrVT = Op.getValueType();
1483 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1484 const Constant *C = CP->getConstVal();
1486 // 64-bit SVR4 ABI code is always position-independent.
1487 // The actual address of the GlobalValue is stored in the TOC.
1488 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1489 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1490 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1491 DAG.getRegister(PPC::X2, MVT::i64));
1494 unsigned MOHiFlag, MOLoFlag;
1495 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1497 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1499 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1500 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1503 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1504 EVT PtrVT = Op.getValueType();
1505 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1507 // 64-bit SVR4 ABI code is always position-independent.
1508 // The actual address of the GlobalValue is stored in the TOC.
1509 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1510 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1511 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1512 DAG.getRegister(PPC::X2, MVT::i64));
1515 unsigned MOHiFlag, MOLoFlag;
1516 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1517 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1518 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1519 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1522 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1523 SelectionDAG &DAG) const {
1524 EVT PtrVT = Op.getValueType();
1526 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1528 unsigned MOHiFlag, MOLoFlag;
1529 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1530 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1531 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1532 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1535 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1536 SelectionDAG &DAG) const {
1538 // FIXME: TLS addresses currently use medium model code sequences,
1539 // which is the most useful form. Eventually support for small and
1540 // large models could be added if users need it, at the cost of
1541 // additional complexity.
1542 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1544 const GlobalValue *GV = GA->getGlobal();
1545 EVT PtrVT = getPointerTy();
1546 bool is64bit = PPCSubTarget.isPPC64();
1548 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1550 if (Model == TLSModel::LocalExec) {
1551 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1552 PPCII::MO_TPREL_HA);
1553 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1554 PPCII::MO_TPREL_LO);
1555 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1556 is64bit ? MVT::i64 : MVT::i32);
1557 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1558 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1561 if (Model == TLSModel::InitialExec) {
1562 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1563 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1567 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1568 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1569 PtrVT, GOTReg, TGA);
1571 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1572 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1573 PtrVT, TGA, GOTPtr);
1574 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1577 if (Model == TLSModel::GeneralDynamic) {
1578 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1579 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1580 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1582 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1585 // We need a chain node, and don't have one handy. The underlying
1586 // call has no side effects, so using the function entry node
1588 SDValue Chain = DAG.getEntryNode();
1589 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1590 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1591 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1592 PtrVT, ParmReg, TGA);
1593 // The return value from GET_TLS_ADDR really is in X3 already, but
1594 // some hacks are needed here to tie everything together. The extra
1595 // copies dissolve during subsequent transforms.
1596 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1597 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1600 if (Model == TLSModel::LocalDynamic) {
1601 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1602 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1603 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1605 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1608 // We need a chain node, and don't have one handy. The underlying
1609 // call has no side effects, so using the function entry node
1611 SDValue Chain = DAG.getEntryNode();
1612 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1613 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1614 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1615 PtrVT, ParmReg, TGA);
1616 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1617 // some hacks are needed here to tie everything together. The extra
1618 // copies dissolve during subsequent transforms.
1619 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1620 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1621 Chain, ParmReg, TGA);
1622 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1625 llvm_unreachable("Unknown TLS model!");
1628 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1629 SelectionDAG &DAG) const {
1630 EVT PtrVT = Op.getValueType();
1631 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1633 const GlobalValue *GV = GSDN->getGlobal();
1635 // 64-bit SVR4 ABI code is always position-independent.
1636 // The actual address of the GlobalValue is stored in the TOC.
1637 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1638 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1639 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1640 DAG.getRegister(PPC::X2, MVT::i64));
1643 unsigned MOHiFlag, MOLoFlag;
1644 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1647 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1649 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1651 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1653 // If the global reference is actually to a non-lazy-pointer, we have to do an
1654 // extra load to get the address of the global.
1655 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1656 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1657 false, false, false, 0);
1661 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1662 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1665 // If we're comparing for equality to zero, expose the fact that this is
1666 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1667 // fold the new nodes.
1668 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1669 if (C->isNullValue() && CC == ISD::SETEQ) {
1670 EVT VT = Op.getOperand(0).getValueType();
1671 SDValue Zext = Op.getOperand(0);
1672 if (VT.bitsLT(MVT::i32)) {
1674 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1676 unsigned Log2b = Log2_32(VT.getSizeInBits());
1677 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1678 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1679 DAG.getConstant(Log2b, MVT::i32));
1680 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1682 // Leave comparisons against 0 and -1 alone for now, since they're usually
1683 // optimized. FIXME: revisit this when we can custom lower all setcc
1685 if (C->isAllOnesValue() || C->isNullValue())
1689 // If we have an integer seteq/setne, turn it into a compare against zero
1690 // by xor'ing the rhs with the lhs, which is faster than setting a
1691 // condition register, reading it back out, and masking the correct bit. The
1692 // normal approach here uses sub to do this instead of xor. Using xor exposes
1693 // the result to other bit-twiddling opportunities.
1694 EVT LHSVT = Op.getOperand(0).getValueType();
1695 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1696 EVT VT = Op.getValueType();
1697 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1699 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1704 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1705 const PPCSubtarget &Subtarget) const {
1706 SDNode *Node = Op.getNode();
1707 EVT VT = Node->getValueType(0);
1708 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1709 SDValue InChain = Node->getOperand(0);
1710 SDValue VAListPtr = Node->getOperand(1);
1711 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1714 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1717 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1718 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1720 InChain = GprIndex.getValue(1);
1722 if (VT == MVT::i64) {
1723 // Check if GprIndex is even
1724 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1725 DAG.getConstant(1, MVT::i32));
1726 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1727 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1728 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1729 DAG.getConstant(1, MVT::i32));
1730 // Align GprIndex to be even if it isn't
1731 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1735 // fpr index is 1 byte after gpr
1736 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1737 DAG.getConstant(1, MVT::i32));
1740 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1741 FprPtr, MachinePointerInfo(SV), MVT::i8,
1743 InChain = FprIndex.getValue(1);
1745 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1746 DAG.getConstant(8, MVT::i32));
1748 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1749 DAG.getConstant(4, MVT::i32));
1752 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1753 MachinePointerInfo(), false, false,
1755 InChain = OverflowArea.getValue(1);
1757 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1758 MachinePointerInfo(), false, false,
1760 InChain = RegSaveArea.getValue(1);
1762 // select overflow_area if index > 8
1763 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1764 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1766 // adjustment constant gpr_index * 4/8
1767 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1768 VT.isInteger() ? GprIndex : FprIndex,
1769 DAG.getConstant(VT.isInteger() ? 4 : 8,
1772 // OurReg = RegSaveArea + RegConstant
1773 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1776 // Floating types are 32 bytes into RegSaveArea
1777 if (VT.isFloatingPoint())
1778 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1779 DAG.getConstant(32, MVT::i32));
1781 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1782 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1783 VT.isInteger() ? GprIndex : FprIndex,
1784 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1787 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1788 VT.isInteger() ? VAListPtr : FprPtr,
1789 MachinePointerInfo(SV),
1790 MVT::i8, false, false, 0);
1792 // determine if we should load from reg_save_area or overflow_area
1793 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1795 // increase overflow_area by 4/8 if gpr/fpr > 8
1796 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1797 DAG.getConstant(VT.isInteger() ? 4 : 8,
1800 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1803 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1805 MachinePointerInfo(),
1806 MVT::i32, false, false, 0);
1808 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1809 false, false, false, 0);
1812 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1813 const PPCSubtarget &Subtarget) const {
1814 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1816 // We have to copy the entire va_list struct:
1817 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1818 return DAG.getMemcpy(Op.getOperand(0), Op,
1819 Op.getOperand(1), Op.getOperand(2),
1820 DAG.getConstant(12, MVT::i32), 8, false, true,
1821 MachinePointerInfo(), MachinePointerInfo());
1824 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1825 SelectionDAG &DAG) const {
1826 return Op.getOperand(0);
1829 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1830 SelectionDAG &DAG) const {
1831 SDValue Chain = Op.getOperand(0);
1832 SDValue Trmp = Op.getOperand(1); // trampoline
1833 SDValue FPtr = Op.getOperand(2); // nested function
1834 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1837 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1838 bool isPPC64 = (PtrVT == MVT::i64);
1840 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1843 TargetLowering::ArgListTy Args;
1844 TargetLowering::ArgListEntry Entry;
1846 Entry.Ty = IntPtrTy;
1847 Entry.Node = Trmp; Args.push_back(Entry);
1849 // TrampSize == (isPPC64 ? 48 : 40);
1850 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1851 isPPC64 ? MVT::i64 : MVT::i32);
1852 Args.push_back(Entry);
1854 Entry.Node = FPtr; Args.push_back(Entry);
1855 Entry.Node = Nest; Args.push_back(Entry);
1857 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1858 TargetLowering::CallLoweringInfo CLI(Chain,
1859 Type::getVoidTy(*DAG.getContext()),
1860 false, false, false, false, 0,
1862 /*isTailCall=*/false,
1863 /*doesNotRet=*/false,
1864 /*isReturnValueUsed=*/true,
1865 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1867 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1869 return CallResult.second;
1872 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1873 const PPCSubtarget &Subtarget) const {
1874 MachineFunction &MF = DAG.getMachineFunction();
1875 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1879 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1880 // vastart just stores the address of the VarArgsFrameIndex slot into the
1881 // memory location argument.
1882 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1883 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1884 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1885 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1886 MachinePointerInfo(SV),
1890 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1891 // We suppose the given va_list is already allocated.
1894 // char gpr; /* index into the array of 8 GPRs
1895 // * stored in the register save area
1896 // * gpr=0 corresponds to r3,
1897 // * gpr=1 to r4, etc.
1899 // char fpr; /* index into the array of 8 FPRs
1900 // * stored in the register save area
1901 // * fpr=0 corresponds to f1,
1902 // * fpr=1 to f2, etc.
1904 // char *overflow_arg_area;
1905 // /* location on stack that holds
1906 // * the next overflow argument
1908 // char *reg_save_area;
1909 // /* where r3:r10 and f1:f8 (if saved)
1915 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1916 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1919 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1921 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1923 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1926 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1927 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1929 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1930 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1932 uint64_t FPROffset = 1;
1933 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1935 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1937 // Store first byte : number of int regs
1938 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1940 MachinePointerInfo(SV),
1941 MVT::i8, false, false, 0);
1942 uint64_t nextOffset = FPROffset;
1943 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1946 // Store second byte : number of float regs
1947 SDValue secondStore =
1948 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1949 MachinePointerInfo(SV, nextOffset), MVT::i8,
1951 nextOffset += StackOffset;
1952 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1954 // Store second word : arguments given on stack
1955 SDValue thirdStore =
1956 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1957 MachinePointerInfo(SV, nextOffset),
1959 nextOffset += FrameOffset;
1960 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1962 // Store third word : arguments given in registers
1963 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1964 MachinePointerInfo(SV, nextOffset),
1969 #include "PPCGenCallingConv.inc"
1971 // Function whose sole purpose is to kill compiler warnings
1972 // stemming from unused functions included from PPCGenCallingConv.inc.
1973 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
1974 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
1977 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1978 CCValAssign::LocInfo &LocInfo,
1979 ISD::ArgFlagsTy &ArgFlags,
1984 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1986 CCValAssign::LocInfo &LocInfo,
1987 ISD::ArgFlagsTy &ArgFlags,
1989 static const uint16_t ArgRegs[] = {
1990 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1991 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1993 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1995 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1997 // Skip one register if the first unallocated register has an even register
1998 // number and there are still argument registers available which have not been
1999 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2000 // need to skip a register if RegNum is odd.
2001 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2002 State.AllocateReg(ArgRegs[RegNum]);
2005 // Always return false here, as this function only makes sure that the first
2006 // unallocated register has an odd register number and does not actually
2007 // allocate a register for the current argument.
2011 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2013 CCValAssign::LocInfo &LocInfo,
2014 ISD::ArgFlagsTy &ArgFlags,
2016 static const uint16_t ArgRegs[] = {
2017 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2021 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2023 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2025 // If there is only one Floating-point register left we need to put both f64
2026 // values of a split ppc_fp128 value on the stack.
2027 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2028 State.AllocateReg(ArgRegs[RegNum]);
2031 // Always return false here, as this function only makes sure that the two f64
2032 // values a ppc_fp128 value is split into are both passed in registers or both
2033 // passed on the stack and does not actually allocate a register for the
2034 // current argument.
2038 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2040 static const uint16_t *GetFPR() {
2041 static const uint16_t FPR[] = {
2042 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2043 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2049 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2051 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2052 unsigned PtrByteSize) {
2053 unsigned ArgSize = ArgVT.getStoreSize();
2054 if (Flags.isByVal())
2055 ArgSize = Flags.getByValSize();
2056 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2062 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2063 CallingConv::ID CallConv, bool isVarArg,
2064 const SmallVectorImpl<ISD::InputArg>
2066 SDLoc dl, SelectionDAG &DAG,
2067 SmallVectorImpl<SDValue> &InVals)
2069 if (PPCSubTarget.isSVR4ABI()) {
2070 if (PPCSubTarget.isPPC64())
2071 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2074 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2077 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2083 PPCTargetLowering::LowerFormalArguments_32SVR4(
2085 CallingConv::ID CallConv, bool isVarArg,
2086 const SmallVectorImpl<ISD::InputArg>
2088 SDLoc dl, SelectionDAG &DAG,
2089 SmallVectorImpl<SDValue> &InVals) const {
2091 // 32-bit SVR4 ABI Stack Frame Layout:
2092 // +-----------------------------------+
2093 // +--> | Back chain |
2094 // | +-----------------------------------+
2095 // | | Floating-point register save area |
2096 // | +-----------------------------------+
2097 // | | General register save area |
2098 // | +-----------------------------------+
2099 // | | CR save word |
2100 // | +-----------------------------------+
2101 // | | VRSAVE save word |
2102 // | +-----------------------------------+
2103 // | | Alignment padding |
2104 // | +-----------------------------------+
2105 // | | Vector register save area |
2106 // | +-----------------------------------+
2107 // | | Local variable space |
2108 // | +-----------------------------------+
2109 // | | Parameter list area |
2110 // | +-----------------------------------+
2111 // | | LR save word |
2112 // | +-----------------------------------+
2113 // SP--> +--- | Back chain |
2114 // +-----------------------------------+
2117 // System V Application Binary Interface PowerPC Processor Supplement
2118 // AltiVec Technology Programming Interface Manual
2120 MachineFunction &MF = DAG.getMachineFunction();
2121 MachineFrameInfo *MFI = MF.getFrameInfo();
2122 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2124 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2125 // Potential tail calls could cause overwriting of argument stack slots.
2126 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2127 (CallConv == CallingConv::Fast));
2128 unsigned PtrByteSize = 4;
2130 // Assign locations to all of the incoming arguments.
2131 SmallVector<CCValAssign, 16> ArgLocs;
2132 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2133 getTargetMachine(), ArgLocs, *DAG.getContext());
2135 // Reserve space for the linkage area on the stack.
2136 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2138 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2140 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2141 CCValAssign &VA = ArgLocs[i];
2143 // Arguments stored in registers.
2144 if (VA.isRegLoc()) {
2145 const TargetRegisterClass *RC;
2146 EVT ValVT = VA.getValVT();
2148 switch (ValVT.getSimpleVT().SimpleTy) {
2150 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2153 RC = &PPC::GPRCRegClass;
2156 RC = &PPC::F4RCRegClass;
2159 RC = &PPC::F8RCRegClass;
2167 RC = &PPC::VRRCRegClass;
2171 // Transform the arguments stored in physical registers into virtual ones.
2172 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2173 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2174 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2176 if (ValVT == MVT::i1)
2177 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2179 InVals.push_back(ArgValue);
2181 // Argument stored in memory.
2182 assert(VA.isMemLoc());
2184 unsigned ArgSize = VA.getLocVT().getStoreSize();
2185 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2188 // Create load nodes to retrieve arguments from the stack.
2189 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2190 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2191 MachinePointerInfo(),
2192 false, false, false, 0));
2196 // Assign locations to all of the incoming aggregate by value arguments.
2197 // Aggregates passed by value are stored in the local variable space of the
2198 // caller's stack frame, right above the parameter list area.
2199 SmallVector<CCValAssign, 16> ByValArgLocs;
2200 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2201 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2203 // Reserve stack space for the allocations in CCInfo.
2204 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2206 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2208 // Area that is at least reserved in the caller of this function.
2209 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2211 // Set the size that is at least reserved in caller of this function. Tail
2212 // call optimized function's reserved stack space needs to be aligned so that
2213 // taking the difference between two stack areas will result in an aligned
2215 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2218 std::max(MinReservedArea,
2219 PPCFrameLowering::getMinCallFrameSize(false, false));
2221 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2222 getStackAlignment();
2223 unsigned AlignMask = TargetAlign-1;
2224 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2226 FI->setMinReservedArea(MinReservedArea);
2228 SmallVector<SDValue, 8> MemOps;
2230 // If the function takes variable number of arguments, make a frame index for
2231 // the start of the first vararg value... for expansion of llvm.va_start.
2233 static const uint16_t GPArgRegs[] = {
2234 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2235 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2237 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2239 static const uint16_t FPArgRegs[] = {
2240 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2243 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2245 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2247 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2250 // Make room for NumGPArgRegs and NumFPArgRegs.
2251 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2252 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2254 FuncInfo->setVarArgsStackOffset(
2255 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2256 CCInfo.getNextStackOffset(), true));
2258 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2259 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2261 // The fixed integer arguments of a variadic function are stored to the
2262 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2263 // the result of va_next.
2264 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2265 // Get an existing live-in vreg, or add a new one.
2266 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2268 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2270 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2271 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2272 MachinePointerInfo(), false, false, 0);
2273 MemOps.push_back(Store);
2274 // Increment the address by four for the next argument to store
2275 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2276 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2279 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2281 // The double arguments are stored to the VarArgsFrameIndex
2283 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2284 // Get an existing live-in vreg, or add a new one.
2285 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2287 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2289 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2290 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2291 MachinePointerInfo(), false, false, 0);
2292 MemOps.push_back(Store);
2293 // Increment the address by eight for the next argument to store
2294 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2296 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2300 if (!MemOps.empty())
2301 Chain = DAG.getNode(ISD::TokenFactor, dl,
2302 MVT::Other, &MemOps[0], MemOps.size());
2307 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2308 // value to MVT::i64 and then truncate to the correct register size.
2310 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2311 SelectionDAG &DAG, SDValue ArgVal,
2314 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2315 DAG.getValueType(ObjectVT));
2316 else if (Flags.isZExt())
2317 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2318 DAG.getValueType(ObjectVT));
2320 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2323 // Set the size that is at least reserved in caller of this function. Tail
2324 // call optimized functions' reserved stack space needs to be aligned so that
2325 // taking the difference between two stack areas will result in an aligned
2328 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2329 unsigned nAltivecParamsAtEnd,
2330 unsigned MinReservedArea,
2331 bool isPPC64) const {
2332 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2333 // Add the Altivec parameters at the end, if needed.
2334 if (nAltivecParamsAtEnd) {
2335 MinReservedArea = ((MinReservedArea+15)/16)*16;
2336 MinReservedArea += 16*nAltivecParamsAtEnd;
2339 std::max(MinReservedArea,
2340 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2341 unsigned TargetAlign
2342 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2343 getStackAlignment();
2344 unsigned AlignMask = TargetAlign-1;
2345 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2346 FI->setMinReservedArea(MinReservedArea);
2350 PPCTargetLowering::LowerFormalArguments_64SVR4(
2352 CallingConv::ID CallConv, bool isVarArg,
2353 const SmallVectorImpl<ISD::InputArg>
2355 SDLoc dl, SelectionDAG &DAG,
2356 SmallVectorImpl<SDValue> &InVals) const {
2357 // TODO: add description of PPC stack frame format, or at least some docs.
2359 MachineFunction &MF = DAG.getMachineFunction();
2360 MachineFrameInfo *MFI = MF.getFrameInfo();
2361 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2363 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2364 // Potential tail calls could cause overwriting of argument stack slots.
2365 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2366 (CallConv == CallingConv::Fast));
2367 unsigned PtrByteSize = 8;
2369 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2370 // Area that is at least reserved in caller of this function.
2371 unsigned MinReservedArea = ArgOffset;
2373 static const uint16_t GPR[] = {
2374 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2375 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2378 static const uint16_t *FPR = GetFPR();
2380 static const uint16_t VR[] = {
2381 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2382 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2385 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2386 const unsigned Num_FPR_Regs = 13;
2387 const unsigned Num_VR_Regs = array_lengthof(VR);
2389 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2391 // Add DAG nodes to load the arguments or copy them out of registers. On
2392 // entry to a function on PPC, the arguments start after the linkage area,
2393 // although the first ones are often in registers.
2395 SmallVector<SDValue, 8> MemOps;
2396 unsigned nAltivecParamsAtEnd = 0;
2397 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2398 unsigned CurArgIdx = 0;
2399 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2401 bool needsLoad = false;
2402 EVT ObjectVT = Ins[ArgNo].VT;
2403 unsigned ObjSize = ObjectVT.getStoreSize();
2404 unsigned ArgSize = ObjSize;
2405 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2406 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2407 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2409 unsigned CurArgOffset = ArgOffset;
2411 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2412 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2413 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8 ||
2414 ObjectVT==MVT::v2f64 || ObjectVT==MVT::v2i64) {
2416 MinReservedArea = ((MinReservedArea+15)/16)*16;
2417 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2421 nAltivecParamsAtEnd++;
2423 // Calculate min reserved area.
2424 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2428 // FIXME the codegen can be much improved in some cases.
2429 // We do not have to keep everything in memory.
2430 if (Flags.isByVal()) {
2431 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2432 ObjSize = Flags.getByValSize();
2433 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2434 // Empty aggregate parameters do not take up registers. Examples:
2438 // etc. However, we have to provide a place-holder in InVals, so
2439 // pretend we have an 8-byte item at the current address for that
2442 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2443 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2444 InVals.push_back(FIN);
2448 unsigned BVAlign = Flags.getByValAlign();
2450 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2451 CurArgOffset = ArgOffset;
2454 // All aggregates smaller than 8 bytes must be passed right-justified.
2455 if (ObjSize < PtrByteSize)
2456 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2457 // The value of the object is its address.
2458 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2459 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2460 InVals.push_back(FIN);
2463 if (GPR_idx != Num_GPR_Regs) {
2464 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2465 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2468 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2469 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2470 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2471 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2472 MachinePointerInfo(FuncArg),
2473 ObjType, false, false, 0);
2475 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2476 // store the whole register as-is to the parameter save area
2477 // slot. The address of the parameter was already calculated
2478 // above (InVals.push_back(FIN)) to be the right-justified
2479 // offset within the slot. For this store, we need a new
2480 // frame index that points at the beginning of the slot.
2481 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2482 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2483 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2484 MachinePointerInfo(FuncArg),
2488 MemOps.push_back(Store);
2491 // Whether we copied from a register or not, advance the offset
2492 // into the parameter save area by a full doubleword.
2493 ArgOffset += PtrByteSize;
2497 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2498 // Store whatever pieces of the object are in registers
2499 // to memory. ArgOffset will be the address of the beginning
2501 if (GPR_idx != Num_GPR_Regs) {
2503 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2504 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2505 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2506 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2507 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2508 MachinePointerInfo(FuncArg, j),
2510 MemOps.push_back(Store);
2512 ArgOffset += PtrByteSize;
2514 ArgOffset += ArgSize - j;
2521 switch (ObjectVT.getSimpleVT().SimpleTy) {
2522 default: llvm_unreachable("Unhandled argument type!");
2526 if (GPR_idx != Num_GPR_Regs) {
2527 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2528 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2530 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2531 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2532 // value to MVT::i64 and then truncate to the correct register size.
2533 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2538 ArgSize = PtrByteSize;
2545 // Every 8 bytes of argument space consumes one of the GPRs available for
2546 // argument passing.
2547 if (GPR_idx != Num_GPR_Regs) {
2550 if (FPR_idx != Num_FPR_Regs) {
2553 if (ObjectVT == MVT::f32)
2554 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2556 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2558 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2562 ArgSize = PtrByteSize;
2573 // Note that vector arguments in registers don't reserve stack space,
2574 // except in varargs functions.
2575 if (VR_idx != Num_VR_Regs) {
2576 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2577 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2579 while ((ArgOffset % 16) != 0) {
2580 ArgOffset += PtrByteSize;
2581 if (GPR_idx != Num_GPR_Regs)
2585 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2589 // Vectors are aligned.
2590 ArgOffset = ((ArgOffset+15)/16)*16;
2591 CurArgOffset = ArgOffset;
2598 // We need to load the argument to a virtual register if we determined
2599 // above that we ran out of physical registers of the appropriate type.
2601 int FI = MFI->CreateFixedObject(ObjSize,
2602 CurArgOffset + (ArgSize - ObjSize),
2604 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2605 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2606 false, false, false, 0);
2609 InVals.push_back(ArgVal);
2612 // Set the size that is at least reserved in caller of this function. Tail
2613 // call optimized functions' reserved stack space needs to be aligned so that
2614 // taking the difference between two stack areas will result in an aligned
2616 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2618 // If the function takes variable number of arguments, make a frame index for
2619 // the start of the first vararg value... for expansion of llvm.va_start.
2621 int Depth = ArgOffset;
2623 FuncInfo->setVarArgsFrameIndex(
2624 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2625 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2627 // If this function is vararg, store any remaining integer argument regs
2628 // to their spots on the stack so that they may be loaded by deferencing the
2629 // result of va_next.
2630 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2631 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2632 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2633 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2634 MachinePointerInfo(), false, false, 0);
2635 MemOps.push_back(Store);
2636 // Increment the address by four for the next argument to store
2637 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2638 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2642 if (!MemOps.empty())
2643 Chain = DAG.getNode(ISD::TokenFactor, dl,
2644 MVT::Other, &MemOps[0], MemOps.size());
2650 PPCTargetLowering::LowerFormalArguments_Darwin(
2652 CallingConv::ID CallConv, bool isVarArg,
2653 const SmallVectorImpl<ISD::InputArg>
2655 SDLoc dl, SelectionDAG &DAG,
2656 SmallVectorImpl<SDValue> &InVals) const {
2657 // TODO: add description of PPC stack frame format, or at least some docs.
2659 MachineFunction &MF = DAG.getMachineFunction();
2660 MachineFrameInfo *MFI = MF.getFrameInfo();
2661 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2663 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2664 bool isPPC64 = PtrVT == MVT::i64;
2665 // Potential tail calls could cause overwriting of argument stack slots.
2666 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2667 (CallConv == CallingConv::Fast));
2668 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2670 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2671 // Area that is at least reserved in caller of this function.
2672 unsigned MinReservedArea = ArgOffset;
2674 static const uint16_t GPR_32[] = { // 32-bit registers.
2675 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2676 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2678 static const uint16_t GPR_64[] = { // 64-bit registers.
2679 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2680 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2683 static const uint16_t *FPR = GetFPR();
2685 static const uint16_t VR[] = {
2686 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2687 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2690 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2691 const unsigned Num_FPR_Regs = 13;
2692 const unsigned Num_VR_Regs = array_lengthof( VR);
2694 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2696 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2698 // In 32-bit non-varargs functions, the stack space for vectors is after the
2699 // stack space for non-vectors. We do not use this space unless we have
2700 // too many vectors to fit in registers, something that only occurs in
2701 // constructed examples:), but we have to walk the arglist to figure
2702 // that out...for the pathological case, compute VecArgOffset as the
2703 // start of the vector parameter area. Computing VecArgOffset is the
2704 // entire point of the following loop.
2705 unsigned VecArgOffset = ArgOffset;
2706 if (!isVarArg && !isPPC64) {
2707 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2709 EVT ObjectVT = Ins[ArgNo].VT;
2710 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2712 if (Flags.isByVal()) {
2713 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2714 unsigned ObjSize = Flags.getByValSize();
2716 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2717 VecArgOffset += ArgSize;
2721 switch(ObjectVT.getSimpleVT().SimpleTy) {
2722 default: llvm_unreachable("Unhandled argument type!");
2728 case MVT::i64: // PPC64
2730 // FIXME: We are guaranteed to be !isPPC64 at this point.
2731 // Does MVT::i64 apply?
2738 // Nothing to do, we're only looking at Nonvector args here.
2743 // We've found where the vector parameter area in memory is. Skip the
2744 // first 12 parameters; these don't use that memory.
2745 VecArgOffset = ((VecArgOffset+15)/16)*16;
2746 VecArgOffset += 12*16;
2748 // Add DAG nodes to load the arguments or copy them out of registers. On
2749 // entry to a function on PPC, the arguments start after the linkage area,
2750 // although the first ones are often in registers.
2752 SmallVector<SDValue, 8> MemOps;
2753 unsigned nAltivecParamsAtEnd = 0;
2754 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2755 unsigned CurArgIdx = 0;
2756 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2758 bool needsLoad = false;
2759 EVT ObjectVT = Ins[ArgNo].VT;
2760 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2761 unsigned ArgSize = ObjSize;
2762 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2763 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2764 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2766 unsigned CurArgOffset = ArgOffset;
2768 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2769 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2770 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2771 if (isVarArg || isPPC64) {
2772 MinReservedArea = ((MinReservedArea+15)/16)*16;
2773 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2776 } else nAltivecParamsAtEnd++;
2778 // Calculate min reserved area.
2779 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2783 // FIXME the codegen can be much improved in some cases.
2784 // We do not have to keep everything in memory.
2785 if (Flags.isByVal()) {
2786 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2787 ObjSize = Flags.getByValSize();
2788 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2789 // Objects of size 1 and 2 are right justified, everything else is
2790 // left justified. This means the memory address is adjusted forwards.
2791 if (ObjSize==1 || ObjSize==2) {
2792 CurArgOffset = CurArgOffset + (4 - ObjSize);
2794 // The value of the object is its address.
2795 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2796 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2797 InVals.push_back(FIN);
2798 if (ObjSize==1 || ObjSize==2) {
2799 if (GPR_idx != Num_GPR_Regs) {
2802 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2804 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2805 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2806 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2807 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2808 MachinePointerInfo(FuncArg),
2809 ObjType, false, false, 0);
2810 MemOps.push_back(Store);
2814 ArgOffset += PtrByteSize;
2818 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2819 // Store whatever pieces of the object are in registers
2820 // to memory. ArgOffset will be the address of the beginning
2822 if (GPR_idx != Num_GPR_Regs) {
2825 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2827 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2828 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2829 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2830 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2831 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2832 MachinePointerInfo(FuncArg, j),
2834 MemOps.push_back(Store);
2836 ArgOffset += PtrByteSize;
2838 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2845 switch (ObjectVT.getSimpleVT().SimpleTy) {
2846 default: llvm_unreachable("Unhandled argument type!");
2850 if (GPR_idx != Num_GPR_Regs) {
2851 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2852 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2854 if (ObjectVT == MVT::i1)
2855 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2860 ArgSize = PtrByteSize;
2862 // All int arguments reserve stack space in the Darwin ABI.
2863 ArgOffset += PtrByteSize;
2867 case MVT::i64: // PPC64
2868 if (GPR_idx != Num_GPR_Regs) {
2869 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2870 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2872 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2873 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2874 // value to MVT::i64 and then truncate to the correct register size.
2875 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2880 ArgSize = PtrByteSize;
2882 // All int arguments reserve stack space in the Darwin ABI.
2888 // Every 4 bytes of argument space consumes one of the GPRs available for
2889 // argument passing.
2890 if (GPR_idx != Num_GPR_Regs) {
2892 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2895 if (FPR_idx != Num_FPR_Regs) {
2898 if (ObjectVT == MVT::f32)
2899 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2901 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2903 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2909 // All FP arguments reserve stack space in the Darwin ABI.
2910 ArgOffset += isPPC64 ? 8 : ObjSize;
2916 // Note that vector arguments in registers don't reserve stack space,
2917 // except in varargs functions.
2918 if (VR_idx != Num_VR_Regs) {
2919 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2920 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2922 while ((ArgOffset % 16) != 0) {
2923 ArgOffset += PtrByteSize;
2924 if (GPR_idx != Num_GPR_Regs)
2928 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2932 if (!isVarArg && !isPPC64) {
2933 // Vectors go after all the nonvectors.
2934 CurArgOffset = VecArgOffset;
2937 // Vectors are aligned.
2938 ArgOffset = ((ArgOffset+15)/16)*16;
2939 CurArgOffset = ArgOffset;
2947 // We need to load the argument to a virtual register if we determined above
2948 // that we ran out of physical registers of the appropriate type.
2950 int FI = MFI->CreateFixedObject(ObjSize,
2951 CurArgOffset + (ArgSize - ObjSize),
2953 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2954 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2955 false, false, false, 0);
2958 InVals.push_back(ArgVal);
2961 // Set the size that is at least reserved in caller of this function. Tail
2962 // call optimized functions' reserved stack space needs to be aligned so that
2963 // taking the difference between two stack areas will result in an aligned
2965 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2967 // If the function takes variable number of arguments, make a frame index for
2968 // the start of the first vararg value... for expansion of llvm.va_start.
2970 int Depth = ArgOffset;
2972 FuncInfo->setVarArgsFrameIndex(
2973 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2975 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2977 // If this function is vararg, store any remaining integer argument regs
2978 // to their spots on the stack so that they may be loaded by deferencing the
2979 // result of va_next.
2980 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2984 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2986 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2988 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2989 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2990 MachinePointerInfo(), false, false, 0);
2991 MemOps.push_back(Store);
2992 // Increment the address by four for the next argument to store
2993 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2994 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2998 if (!MemOps.empty())
2999 Chain = DAG.getNode(ISD::TokenFactor, dl,
3000 MVT::Other, &MemOps[0], MemOps.size());
3005 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
3006 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
3008 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
3012 const SmallVectorImpl<ISD::OutputArg>
3014 const SmallVectorImpl<SDValue> &OutVals,
3015 unsigned &nAltivecParamsAtEnd) {
3016 // Count how many bytes are to be pushed on the stack, including the linkage
3017 // area, and parameter passing area. We start with 24/48 bytes, which is
3018 // prereserved space for [SP][CR][LR][3 x unused].
3019 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
3020 unsigned NumOps = Outs.size();
3021 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3023 // Add up all the space actually used.
3024 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
3025 // they all go in registers, but we must reserve stack space for them for
3026 // possible use by the caller. In varargs or 64-bit calls, parameters are
3027 // assigned stack space in order, with padding so Altivec parameters are
3029 nAltivecParamsAtEnd = 0;
3030 for (unsigned i = 0; i != NumOps; ++i) {
3031 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3032 EVT ArgVT = Outs[i].VT;
3033 // Varargs Altivec parameters are padded to a 16 byte boundary.
3034 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
3035 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8 ||
3036 ArgVT==MVT::v2f64 || ArgVT==MVT::v2i64) {
3037 if (!isVarArg && !isPPC64) {
3038 // Non-varargs Altivec parameters go after all the non-Altivec
3039 // parameters; handle those later so we know how much padding we need.
3040 nAltivecParamsAtEnd++;
3043 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
3044 NumBytes = ((NumBytes+15)/16)*16;
3046 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3049 // Allow for Altivec parameters at the end, if needed.
3050 if (nAltivecParamsAtEnd) {
3051 NumBytes = ((NumBytes+15)/16)*16;
3052 NumBytes += 16*nAltivecParamsAtEnd;
3055 // The prolog code of the callee may store up to 8 GPR argument registers to
3056 // the stack, allowing va_start to index over them in memory if its varargs.
3057 // Because we cannot tell if this is needed on the caller side, we have to
3058 // conservatively assume that it is needed. As such, make sure we have at
3059 // least enough stack space for the caller to store the 8 GPRs.
3060 NumBytes = std::max(NumBytes,
3061 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
3063 // Tail call needs the stack to be aligned.
3064 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
3065 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
3066 getFrameLowering()->getStackAlignment();
3067 unsigned AlignMask = TargetAlign-1;
3068 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3074 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3075 /// adjusted to accommodate the arguments for the tailcall.
3076 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3077 unsigned ParamSize) {
3079 if (!isTailCall) return 0;
3081 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3082 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3083 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3084 // Remember only if the new adjustement is bigger.
3085 if (SPDiff < FI->getTailCallSPDelta())
3086 FI->setTailCallSPDelta(SPDiff);
3091 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3092 /// for tail call optimization. Targets which want to do tail call
3093 /// optimization should implement this function.
3095 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3096 CallingConv::ID CalleeCC,
3098 const SmallVectorImpl<ISD::InputArg> &Ins,
3099 SelectionDAG& DAG) const {
3100 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3103 // Variable argument functions are not supported.
3107 MachineFunction &MF = DAG.getMachineFunction();
3108 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3109 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3110 // Functions containing by val parameters are not supported.
3111 for (unsigned i = 0; i != Ins.size(); i++) {
3112 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3113 if (Flags.isByVal()) return false;
3116 // Non-PIC/GOT tail calls are supported.
3117 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3120 // At the moment we can only do local tail calls (in same module, hidden
3121 // or protected) if we are generating PIC.
3122 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3123 return G->getGlobal()->hasHiddenVisibility()
3124 || G->getGlobal()->hasProtectedVisibility();
3130 /// isCallCompatibleAddress - Return the immediate to use if the specified
3131 /// 32-bit value is representable in the immediate field of a BxA instruction.
3132 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3133 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3136 int Addr = C->getZExtValue();
3137 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3138 SignExtend32<26>(Addr) != Addr)
3139 return 0; // Top 6 bits have to be sext of immediate.
3141 return DAG.getConstant((int)C->getZExtValue() >> 2,
3142 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3147 struct TailCallArgumentInfo {
3152 TailCallArgumentInfo() : FrameIdx(0) {}
3157 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3159 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3161 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3162 SmallVectorImpl<SDValue> &MemOpChains,
3164 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3165 SDValue Arg = TailCallArgs[i].Arg;
3166 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3167 int FI = TailCallArgs[i].FrameIdx;
3168 // Store relative to framepointer.
3169 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3170 MachinePointerInfo::getFixedStack(FI),
3175 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3176 /// the appropriate stack slot for the tail call optimized function call.
3177 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3178 MachineFunction &MF,
3187 // Calculate the new stack slot for the return address.
3188 int SlotSize = isPPC64 ? 8 : 4;
3189 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3191 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3192 NewRetAddrLoc, true);
3193 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3194 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3195 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3196 MachinePointerInfo::getFixedStack(NewRetAddr),
3199 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3200 // slot as the FP is never overwritten.
3203 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3204 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3206 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3207 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3208 MachinePointerInfo::getFixedStack(NewFPIdx),
3215 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3216 /// the position of the argument.
3218 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3219 SDValue Arg, int SPDiff, unsigned ArgOffset,
3220 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3221 int Offset = ArgOffset + SPDiff;
3222 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3223 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3224 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3225 SDValue FIN = DAG.getFrameIndex(FI, VT);
3226 TailCallArgumentInfo Info;
3228 Info.FrameIdxOp = FIN;
3230 TailCallArguments.push_back(Info);
3233 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3234 /// stack slot. Returns the chain as result and the loaded frame pointers in
3235 /// LROpOut/FPOpout. Used when tail calling.
3236 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3244 // Load the LR and FP stack slot for later adjusting.
3245 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3246 LROpOut = getReturnAddrFrameIndex(DAG);
3247 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3248 false, false, false, 0);
3249 Chain = SDValue(LROpOut.getNode(), 1);
3251 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3252 // slot as the FP is never overwritten.
3254 FPOpOut = getFramePointerFrameIndex(DAG);
3255 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3256 false, false, false, 0);
3257 Chain = SDValue(FPOpOut.getNode(), 1);
3263 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3264 /// by "Src" to address "Dst" of size "Size". Alignment information is
3265 /// specified by the specific parameter attribute. The copy will be passed as
3266 /// a byval function parameter.
3267 /// Sometimes what we are copying is the end of a larger object, the part that
3268 /// does not fit in registers.
3270 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3271 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3273 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3274 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3275 false, false, MachinePointerInfo(0),
3276 MachinePointerInfo(0));
3279 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3282 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3283 SDValue Arg, SDValue PtrOff, int SPDiff,
3284 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3285 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3286 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3288 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3293 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3295 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3296 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3297 DAG.getConstant(ArgOffset, PtrVT));
3299 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3300 MachinePointerInfo(), false, false, 0));
3301 // Calculate and remember argument location.
3302 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3307 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3308 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3309 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3310 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3311 MachineFunction &MF = DAG.getMachineFunction();
3313 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3314 // might overwrite each other in case of tail call optimization.
3315 SmallVector<SDValue, 8> MemOpChains2;
3316 // Do not flag preceding copytoreg stuff together with the following stuff.
3318 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3320 if (!MemOpChains2.empty())
3321 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3322 &MemOpChains2[0], MemOpChains2.size());
3324 // Store the return address to the appropriate stack slot.
3325 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3326 isPPC64, isDarwinABI, dl);
3328 // Emit callseq_end just before tailcall node.
3329 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3330 DAG.getIntPtrConstant(0, true), InFlag, dl);
3331 InFlag = Chain.getValue(1);
3335 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3336 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3337 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3338 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3339 const PPCSubtarget &PPCSubTarget) {
3341 bool isPPC64 = PPCSubTarget.isPPC64();
3342 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3344 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3345 NodeTys.push_back(MVT::Other); // Returns a chain
3346 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3348 unsigned CallOpc = PPCISD::CALL;
3350 bool needIndirectCall = true;
3351 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3352 // If this is an absolute destination address, use the munged value.
3353 Callee = SDValue(Dest, 0);
3354 needIndirectCall = false;
3357 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3358 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3359 // Use indirect calls for ALL functions calls in JIT mode, since the
3360 // far-call stubs may be outside relocation limits for a BL instruction.
3361 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3362 unsigned OpFlags = 0;
3363 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3364 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3365 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3366 (G->getGlobal()->isDeclaration() ||
3367 G->getGlobal()->isWeakForLinker())) {
3368 // PC-relative references to external symbols should go through $stub,
3369 // unless we're building with the leopard linker or later, which
3370 // automatically synthesizes these stubs.
3371 OpFlags = PPCII::MO_DARWIN_STUB;
3374 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3375 // every direct call is) turn it into a TargetGlobalAddress /
3376 // TargetExternalSymbol node so that legalize doesn't hack it.
3377 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3378 Callee.getValueType(),
3380 needIndirectCall = false;
3384 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3385 unsigned char OpFlags = 0;
3387 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3388 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3389 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3390 // PC-relative references to external symbols should go through $stub,
3391 // unless we're building with the leopard linker or later, which
3392 // automatically synthesizes these stubs.
3393 OpFlags = PPCII::MO_DARWIN_STUB;
3396 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3398 needIndirectCall = false;
3401 if (needIndirectCall) {
3402 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3403 // to do the call, we can't use PPCISD::CALL.
3404 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3406 if (isSVR4ABI && isPPC64) {
3407 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3408 // entry point, but to the function descriptor (the function entry point
3409 // address is part of the function descriptor though).
3410 // The function descriptor is a three doubleword structure with the
3411 // following fields: function entry point, TOC base address and
3412 // environment pointer.
3413 // Thus for a call through a function pointer, the following actions need
3415 // 1. Save the TOC of the caller in the TOC save area of its stack
3416 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3417 // 2. Load the address of the function entry point from the function
3419 // 3. Load the TOC of the callee from the function descriptor into r2.
3420 // 4. Load the environment pointer from the function descriptor into
3422 // 5. Branch to the function entry point address.
3423 // 6. On return of the callee, the TOC of the caller needs to be
3424 // restored (this is done in FinishCall()).
3426 // All those operations are flagged together to ensure that no other
3427 // operations can be scheduled in between. E.g. without flagging the
3428 // operations together, a TOC access in the caller could be scheduled
3429 // between the load of the callee TOC and the branch to the callee, which
3430 // results in the TOC access going through the TOC of the callee instead
3431 // of going through the TOC of the caller, which leads to incorrect code.
3433 // Load the address of the function entry point from the function
3435 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3436 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3437 InFlag.getNode() ? 3 : 2);
3438 Chain = LoadFuncPtr.getValue(1);
3439 InFlag = LoadFuncPtr.getValue(2);
3441 // Load environment pointer into r11.
3442 // Offset of the environment pointer within the function descriptor.
3443 SDValue PtrOff = DAG.getIntPtrConstant(16);
3445 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3446 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3448 Chain = LoadEnvPtr.getValue(1);
3449 InFlag = LoadEnvPtr.getValue(2);
3451 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3453 Chain = EnvVal.getValue(0);
3454 InFlag = EnvVal.getValue(1);
3456 // Load TOC of the callee into r2. We are using a target-specific load
3457 // with r2 hard coded, because the result of a target-independent load
3458 // would never go directly into r2, since r2 is a reserved register (which
3459 // prevents the register allocator from allocating it), resulting in an
3460 // additional register being allocated and an unnecessary move instruction
3462 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3463 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3465 Chain = LoadTOCPtr.getValue(0);
3466 InFlag = LoadTOCPtr.getValue(1);
3468 MTCTROps[0] = Chain;
3469 MTCTROps[1] = LoadFuncPtr;
3470 MTCTROps[2] = InFlag;
3473 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3474 2 + (InFlag.getNode() != 0));
3475 InFlag = Chain.getValue(1);
3478 NodeTys.push_back(MVT::Other);
3479 NodeTys.push_back(MVT::Glue);
3480 Ops.push_back(Chain);
3481 CallOpc = PPCISD::BCTRL;
3483 // Add use of X11 (holding environment pointer)
3484 if (isSVR4ABI && isPPC64)
3485 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3486 // Add CTR register as callee so a bctr can be emitted later.
3488 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3491 // If this is a direct call, pass the chain and the callee.
3492 if (Callee.getNode()) {
3493 Ops.push_back(Chain);
3494 Ops.push_back(Callee);
3496 // If this is a tail call add stack pointer delta.
3498 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3500 // Add argument registers to the end of the list so that they are known live
3502 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3503 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3504 RegsToPass[i].second.getValueType()));
3510 bool isLocalCall(const SDValue &Callee)
3512 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3513 return !G->getGlobal()->isDeclaration() &&
3514 !G->getGlobal()->isWeakForLinker();
3519 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3520 CallingConv::ID CallConv, bool isVarArg,
3521 const SmallVectorImpl<ISD::InputArg> &Ins,
3522 SDLoc dl, SelectionDAG &DAG,
3523 SmallVectorImpl<SDValue> &InVals) const {
3525 SmallVector<CCValAssign, 16> RVLocs;
3526 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3527 getTargetMachine(), RVLocs, *DAG.getContext());
3528 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3530 // Copy all of the result registers out of their specified physreg.
3531 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3532 CCValAssign &VA = RVLocs[i];
3533 assert(VA.isRegLoc() && "Can only return in registers!");
3535 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3536 VA.getLocReg(), VA.getLocVT(), InFlag);
3537 Chain = Val.getValue(1);
3538 InFlag = Val.getValue(2);
3540 switch (VA.getLocInfo()) {
3541 default: llvm_unreachable("Unknown loc info!");
3542 case CCValAssign::Full: break;
3543 case CCValAssign::AExt:
3544 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3546 case CCValAssign::ZExt:
3547 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3548 DAG.getValueType(VA.getValVT()));
3549 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3551 case CCValAssign::SExt:
3552 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3553 DAG.getValueType(VA.getValVT()));
3554 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3558 InVals.push_back(Val);
3565 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3566 bool isTailCall, bool isVarArg,
3568 SmallVector<std::pair<unsigned, SDValue>, 8>
3570 SDValue InFlag, SDValue Chain,
3572 int SPDiff, unsigned NumBytes,
3573 const SmallVectorImpl<ISD::InputArg> &Ins,
3574 SmallVectorImpl<SDValue> &InVals) const {
3575 std::vector<EVT> NodeTys;
3576 SmallVector<SDValue, 8> Ops;
3577 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3578 isTailCall, RegsToPass, Ops, NodeTys,
3581 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3582 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3583 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3585 // When performing tail call optimization the callee pops its arguments off
3586 // the stack. Account for this here so these bytes can be pushed back on in
3587 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3588 int BytesCalleePops =
3589 (CallConv == CallingConv::Fast &&
3590 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3592 // Add a register mask operand representing the call-preserved registers.
3593 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3594 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3595 assert(Mask && "Missing call preserved mask for calling convention");
3596 Ops.push_back(DAG.getRegisterMask(Mask));
3598 if (InFlag.getNode())
3599 Ops.push_back(InFlag);
3603 assert(((Callee.getOpcode() == ISD::Register &&
3604 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3605 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3606 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3607 isa<ConstantSDNode>(Callee)) &&
3608 "Expecting an global address, external symbol, absolute value or register");
3610 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3613 // Add a NOP immediately after the branch instruction when using the 64-bit
3614 // SVR4 ABI. At link time, if caller and callee are in a different module and
3615 // thus have a different TOC, the call will be replaced with a call to a stub
3616 // function which saves the current TOC, loads the TOC of the callee and
3617 // branches to the callee. The NOP will be replaced with a load instruction
3618 // which restores the TOC of the caller from the TOC save slot of the current
3619 // stack frame. If caller and callee belong to the same module (and have the
3620 // same TOC), the NOP will remain unchanged.
3622 bool needsTOCRestore = false;
3623 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3624 if (CallOpc == PPCISD::BCTRL) {
3625 // This is a call through a function pointer.
3626 // Restore the caller TOC from the save area into R2.
3627 // See PrepareCall() for more information about calls through function
3628 // pointers in the 64-bit SVR4 ABI.
3629 // We are using a target-specific load with r2 hard coded, because the
3630 // result of a target-independent load would never go directly into r2,
3631 // since r2 is a reserved register (which prevents the register allocator
3632 // from allocating it), resulting in an additional register being
3633 // allocated and an unnecessary move instruction being generated.
3634 needsTOCRestore = true;
3635 } else if ((CallOpc == PPCISD::CALL) &&
3636 (!isLocalCall(Callee) ||
3637 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3638 // Otherwise insert NOP for non-local calls.
3639 CallOpc = PPCISD::CALL_NOP;
3643 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3644 InFlag = Chain.getValue(1);
3646 if (needsTOCRestore) {
3647 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3648 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3649 InFlag = Chain.getValue(1);
3652 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3653 DAG.getIntPtrConstant(BytesCalleePops, true),
3656 InFlag = Chain.getValue(1);
3658 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3659 Ins, dl, DAG, InVals);
3663 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3664 SmallVectorImpl<SDValue> &InVals) const {
3665 SelectionDAG &DAG = CLI.DAG;
3667 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3668 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3669 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3670 SDValue Chain = CLI.Chain;
3671 SDValue Callee = CLI.Callee;
3672 bool &isTailCall = CLI.IsTailCall;
3673 CallingConv::ID CallConv = CLI.CallConv;
3674 bool isVarArg = CLI.IsVarArg;
3677 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3680 if (PPCSubTarget.isSVR4ABI()) {
3681 if (PPCSubTarget.isPPC64())
3682 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3683 isTailCall, Outs, OutVals, Ins,
3686 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3687 isTailCall, Outs, OutVals, Ins,
3691 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3692 isTailCall, Outs, OutVals, Ins,
3697 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3698 CallingConv::ID CallConv, bool isVarArg,
3700 const SmallVectorImpl<ISD::OutputArg> &Outs,
3701 const SmallVectorImpl<SDValue> &OutVals,
3702 const SmallVectorImpl<ISD::InputArg> &Ins,
3703 SDLoc dl, SelectionDAG &DAG,
3704 SmallVectorImpl<SDValue> &InVals) const {
3705 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3706 // of the 32-bit SVR4 ABI stack frame layout.
3708 assert((CallConv == CallingConv::C ||
3709 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3711 unsigned PtrByteSize = 4;
3713 MachineFunction &MF = DAG.getMachineFunction();
3715 // Mark this function as potentially containing a function that contains a
3716 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3717 // and restoring the callers stack pointer in this functions epilog. This is
3718 // done because by tail calling the called function might overwrite the value
3719 // in this function's (MF) stack pointer stack slot 0(SP).
3720 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3721 CallConv == CallingConv::Fast)
3722 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3724 // Count how many bytes are to be pushed on the stack, including the linkage
3725 // area, parameter list area and the part of the local variable space which
3726 // contains copies of aggregates which are passed by value.
3728 // Assign locations to all of the outgoing arguments.
3729 SmallVector<CCValAssign, 16> ArgLocs;
3730 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3731 getTargetMachine(), ArgLocs, *DAG.getContext());
3733 // Reserve space for the linkage area on the stack.
3734 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3737 // Handle fixed and variable vector arguments differently.
3738 // Fixed vector arguments go into registers as long as registers are
3739 // available. Variable vector arguments always go into memory.
3740 unsigned NumArgs = Outs.size();
3742 for (unsigned i = 0; i != NumArgs; ++i) {
3743 MVT ArgVT = Outs[i].VT;
3744 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3747 if (Outs[i].IsFixed) {
3748 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3751 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3757 errs() << "Call operand #" << i << " has unhandled type "
3758 << EVT(ArgVT).getEVTString() << "\n";
3760 llvm_unreachable(0);
3764 // All arguments are treated the same.
3765 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3768 // Assign locations to all of the outgoing aggregate by value arguments.
3769 SmallVector<CCValAssign, 16> ByValArgLocs;
3770 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3771 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3773 // Reserve stack space for the allocations in CCInfo.
3774 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3776 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3778 // Size of the linkage area, parameter list area and the part of the local
3779 // space variable where copies of aggregates which are passed by value are
3781 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3783 // Calculate by how many bytes the stack has to be adjusted in case of tail
3784 // call optimization.
3785 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3787 // Adjust the stack pointer for the new arguments...
3788 // These operations are automatically eliminated by the prolog/epilog pass
3789 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3791 SDValue CallSeqStart = Chain;
3793 // Load the return address and frame pointer so it can be moved somewhere else
3796 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3799 // Set up a copy of the stack pointer for use loading and storing any
3800 // arguments that may not fit in the registers available for argument
3802 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3804 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3805 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3806 SmallVector<SDValue, 8> MemOpChains;
3808 bool seenFloatArg = false;
3809 // Walk the register/memloc assignments, inserting copies/loads.
3810 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3813 CCValAssign &VA = ArgLocs[i];
3814 SDValue Arg = OutVals[i];
3815 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3817 if (Flags.isByVal()) {
3818 // Argument is an aggregate which is passed by value, thus we need to
3819 // create a copy of it in the local variable space of the current stack
3820 // frame (which is the stack frame of the caller) and pass the address of
3821 // this copy to the callee.
3822 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3823 CCValAssign &ByValVA = ByValArgLocs[j++];
3824 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3826 // Memory reserved in the local variable space of the callers stack frame.
3827 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3829 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3830 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3832 // Create a copy of the argument in the local area of the current
3834 SDValue MemcpyCall =
3835 CreateCopyOfByValArgument(Arg, PtrOff,
3836 CallSeqStart.getNode()->getOperand(0),
3839 // This must go outside the CALLSEQ_START..END.
3840 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3841 CallSeqStart.getNode()->getOperand(1),
3843 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3844 NewCallSeqStart.getNode());
3845 Chain = CallSeqStart = NewCallSeqStart;
3847 // Pass the address of the aggregate copy on the stack either in a
3848 // physical register or in the parameter list area of the current stack
3849 // frame to the callee.
3853 if (VA.isRegLoc()) {
3854 if (Arg.getValueType() == MVT::i1)
3855 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3857 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3858 // Put argument in a physical register.
3859 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3861 // Put argument in the parameter list area of the current stack frame.
3862 assert(VA.isMemLoc());
3863 unsigned LocMemOffset = VA.getLocMemOffset();
3866 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3867 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3869 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3870 MachinePointerInfo(),
3873 // Calculate and remember argument location.
3874 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3880 if (!MemOpChains.empty())
3881 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3882 &MemOpChains[0], MemOpChains.size());
3884 // Build a sequence of copy-to-reg nodes chained together with token chain
3885 // and flag operands which copy the outgoing args into the appropriate regs.
3887 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3888 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3889 RegsToPass[i].second, InFlag);
3890 InFlag = Chain.getValue(1);
3893 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3896 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3897 SDValue Ops[] = { Chain, InFlag };
3899 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3900 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3902 InFlag = Chain.getValue(1);
3906 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3907 false, TailCallArguments);
3909 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3910 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3914 // Copy an argument into memory, being careful to do this outside the
3915 // call sequence for the call to which the argument belongs.
3917 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3918 SDValue CallSeqStart,
3919 ISD::ArgFlagsTy Flags,
3922 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3923 CallSeqStart.getNode()->getOperand(0),
3925 // The MEMCPY must go outside the CALLSEQ_START..END.
3926 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3927 CallSeqStart.getNode()->getOperand(1),
3929 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3930 NewCallSeqStart.getNode());
3931 return NewCallSeqStart;
3935 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3936 CallingConv::ID CallConv, bool isVarArg,
3938 const SmallVectorImpl<ISD::OutputArg> &Outs,
3939 const SmallVectorImpl<SDValue> &OutVals,
3940 const SmallVectorImpl<ISD::InputArg> &Ins,
3941 SDLoc dl, SelectionDAG &DAG,
3942 SmallVectorImpl<SDValue> &InVals) const {
3944 unsigned NumOps = Outs.size();
3946 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3947 unsigned PtrByteSize = 8;
3949 MachineFunction &MF = DAG.getMachineFunction();
3951 // Mark this function as potentially containing a function that contains a
3952 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3953 // and restoring the callers stack pointer in this functions epilog. This is
3954 // done because by tail calling the called function might overwrite the value
3955 // in this function's (MF) stack pointer stack slot 0(SP).
3956 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3957 CallConv == CallingConv::Fast)
3958 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3960 unsigned nAltivecParamsAtEnd = 0;
3962 // Count how many bytes are to be pushed on the stack, including the linkage
3963 // area, and parameter passing area. We start with at least 48 bytes, which
3964 // is reserved space for [SP][CR][LR][3 x unused].
3965 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3968 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3969 Outs, OutVals, nAltivecParamsAtEnd);
3971 // Calculate by how many bytes the stack has to be adjusted in case of tail
3972 // call optimization.
3973 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3975 // To protect arguments on the stack from being clobbered in a tail call,
3976 // force all the loads to happen before doing any other lowering.
3978 Chain = DAG.getStackArgumentTokenFactor(Chain);
3980 // Adjust the stack pointer for the new arguments...
3981 // These operations are automatically eliminated by the prolog/epilog pass
3982 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3984 SDValue CallSeqStart = Chain;
3986 // Load the return address and frame pointer so it can be move somewhere else
3989 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3992 // Set up a copy of the stack pointer for use loading and storing any
3993 // arguments that may not fit in the registers available for argument
3995 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3997 // Figure out which arguments are going to go in registers, and which in
3998 // memory. Also, if this is a vararg function, floating point operations
3999 // must be stored to our stack, and loaded into integer regs as well, if
4000 // any integer regs are available for argument passing.
4001 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
4002 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4004 static const uint16_t GPR[] = {
4005 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4006 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4008 static const uint16_t *FPR = GetFPR();
4010 static const uint16_t VR[] = {
4011 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4012 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4014 const unsigned NumGPRs = array_lengthof(GPR);
4015 const unsigned NumFPRs = 13;
4016 const unsigned NumVRs = array_lengthof(VR);
4018 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4019 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4021 SmallVector<SDValue, 8> MemOpChains;
4022 for (unsigned i = 0; i != NumOps; ++i) {
4023 SDValue Arg = OutVals[i];
4024 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4026 // PtrOff will be used to store the current argument to the stack if a
4027 // register cannot be found for it.
4030 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4032 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4034 // Promote integers to 64-bit values.
4035 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4036 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4037 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4038 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4041 // FIXME memcpy is used way more than necessary. Correctness first.
4042 // Note: "by value" is code for passing a structure by value, not
4044 if (Flags.isByVal()) {
4045 // Note: Size includes alignment padding, so
4046 // struct x { short a; char b; }
4047 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4048 // These are the proper values we need for right-justifying the
4049 // aggregate in a parameter register.
4050 unsigned Size = Flags.getByValSize();
4052 // An empty aggregate parameter takes up no storage and no
4057 unsigned BVAlign = Flags.getByValAlign();
4059 if (BVAlign % PtrByteSize != 0)
4061 "ByVal alignment is not a multiple of the pointer size");
4063 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
4066 // All aggregates smaller than 8 bytes must be passed right-justified.
4067 if (Size==1 || Size==2 || Size==4) {
4068 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4069 if (GPR_idx != NumGPRs) {
4070 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4071 MachinePointerInfo(), VT,
4073 MemOpChains.push_back(Load.getValue(1));
4074 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4076 ArgOffset += PtrByteSize;
4081 if (GPR_idx == NumGPRs && Size < 8) {
4082 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4083 PtrOff.getValueType());
4084 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4085 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4088 ArgOffset += PtrByteSize;
4091 // Copy entire object into memory. There are cases where gcc-generated
4092 // code assumes it is there, even if it could be put entirely into
4093 // registers. (This is not what the doc says.)
4095 // FIXME: The above statement is likely due to a misunderstanding of the
4096 // documents. All arguments must be copied into the parameter area BY
4097 // THE CALLEE in the event that the callee takes the address of any
4098 // formal argument. That has not yet been implemented. However, it is
4099 // reasonable to use the stack area as a staging area for the register
4102 // Skip this for small aggregates, as we will use the same slot for a
4103 // right-justified copy, below.
4105 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4109 // When a register is available, pass a small aggregate right-justified.
4110 if (Size < 8 && GPR_idx != NumGPRs) {
4111 // The easiest way to get this right-justified in a register
4112 // is to copy the structure into the rightmost portion of a
4113 // local variable slot, then load the whole slot into the
4115 // FIXME: The memcpy seems to produce pretty awful code for
4116 // small aggregates, particularly for packed ones.
4117 // FIXME: It would be preferable to use the slot in the
4118 // parameter save area instead of a new local variable.
4119 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4120 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4121 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4125 // Load the slot into the register.
4126 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4127 MachinePointerInfo(),
4128 false, false, false, 0);
4129 MemOpChains.push_back(Load.getValue(1));
4130 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4132 // Done with this argument.
4133 ArgOffset += PtrByteSize;
4137 // For aggregates larger than PtrByteSize, copy the pieces of the
4138 // object that fit into registers from the parameter save area.
4139 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4140 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4141 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4142 if (GPR_idx != NumGPRs) {
4143 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4144 MachinePointerInfo(),
4145 false, false, false, 0);
4146 MemOpChains.push_back(Load.getValue(1));
4147 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4148 ArgOffset += PtrByteSize;
4150 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4157 switch (Arg.getSimpleValueType().SimpleTy) {
4158 default: llvm_unreachable("Unexpected ValueType for argument!");
4162 if (GPR_idx != NumGPRs) {
4163 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4165 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4166 true, isTailCall, false, MemOpChains,
4167 TailCallArguments, dl);
4169 ArgOffset += PtrByteSize;
4173 if (FPR_idx != NumFPRs) {
4174 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4177 // A single float or an aggregate containing only a single float
4178 // must be passed right-justified in the stack doubleword, and
4179 // in the GPR, if one is available.
4181 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4182 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4183 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4187 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4188 MachinePointerInfo(), false, false, 0);
4189 MemOpChains.push_back(Store);
4191 // Float varargs are always shadowed in available integer registers
4192 if (GPR_idx != NumGPRs) {
4193 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4194 MachinePointerInfo(), false, false,
4196 MemOpChains.push_back(Load.getValue(1));
4197 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4199 } else if (GPR_idx != NumGPRs)
4200 // If we have any FPRs remaining, we may also have GPRs remaining.
4203 // Single-precision floating-point values are mapped to the
4204 // second (rightmost) word of the stack doubleword.
4205 if (Arg.getValueType() == MVT::f32) {
4206 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4207 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4210 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4211 true, isTailCall, false, MemOpChains,
4212 TailCallArguments, dl);
4223 // These go aligned on the stack, or in the corresponding R registers
4224 // when within range. The Darwin PPC ABI doc claims they also go in
4225 // V registers; in fact gcc does this only for arguments that are
4226 // prototyped, not for those that match the ... We do it for all
4227 // arguments, seems to work.
4228 while (ArgOffset % 16 !=0) {
4229 ArgOffset += PtrByteSize;
4230 if (GPR_idx != NumGPRs)
4233 // We could elide this store in the case where the object fits
4234 // entirely in R registers. Maybe later.
4235 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4236 DAG.getConstant(ArgOffset, PtrVT));
4237 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4238 MachinePointerInfo(), false, false, 0);
4239 MemOpChains.push_back(Store);
4240 if (VR_idx != NumVRs) {
4241 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4242 MachinePointerInfo(),
4243 false, false, false, 0);
4244 MemOpChains.push_back(Load.getValue(1));
4245 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4248 for (unsigned i=0; i<16; i+=PtrByteSize) {
4249 if (GPR_idx == NumGPRs)
4251 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4252 DAG.getConstant(i, PtrVT));
4253 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4254 false, false, false, 0);
4255 MemOpChains.push_back(Load.getValue(1));
4256 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4261 // Non-varargs Altivec params generally go in registers, but have
4262 // stack space allocated at the end.
4263 if (VR_idx != NumVRs) {
4264 // Doesn't have GPR space allocated.
4265 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4267 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4268 true, isTailCall, true, MemOpChains,
4269 TailCallArguments, dl);
4276 if (!MemOpChains.empty())
4277 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4278 &MemOpChains[0], MemOpChains.size());
4280 // Check if this is an indirect call (MTCTR/BCTRL).
4281 // See PrepareCall() for more information about calls through function
4282 // pointers in the 64-bit SVR4 ABI.
4284 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4285 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4286 !isBLACompatibleAddress(Callee, DAG)) {
4287 // Load r2 into a virtual register and store it to the TOC save area.
4288 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4289 // TOC save area offset.
4290 SDValue PtrOff = DAG.getIntPtrConstant(40);
4291 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4292 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4294 // R12 must contain the address of an indirect callee. This does not
4295 // mean the MTCTR instruction must use R12; it's easier to model this
4296 // as an extra parameter, so do that.
4297 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4300 // Build a sequence of copy-to-reg nodes chained together with token chain
4301 // and flag operands which copy the outgoing args into the appropriate regs.
4303 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4304 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4305 RegsToPass[i].second, InFlag);
4306 InFlag = Chain.getValue(1);
4310 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4311 FPOp, true, TailCallArguments);
4313 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4314 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4319 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4320 CallingConv::ID CallConv, bool isVarArg,
4322 const SmallVectorImpl<ISD::OutputArg> &Outs,
4323 const SmallVectorImpl<SDValue> &OutVals,
4324 const SmallVectorImpl<ISD::InputArg> &Ins,
4325 SDLoc dl, SelectionDAG &DAG,
4326 SmallVectorImpl<SDValue> &InVals) const {
4328 unsigned NumOps = Outs.size();
4330 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4331 bool isPPC64 = PtrVT == MVT::i64;
4332 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4334 MachineFunction &MF = DAG.getMachineFunction();
4336 // Mark this function as potentially containing a function that contains a
4337 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4338 // and restoring the callers stack pointer in this functions epilog. This is
4339 // done because by tail calling the called function might overwrite the value
4340 // in this function's (MF) stack pointer stack slot 0(SP).
4341 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4342 CallConv == CallingConv::Fast)
4343 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4345 unsigned nAltivecParamsAtEnd = 0;
4347 // Count how many bytes are to be pushed on the stack, including the linkage
4348 // area, and parameter passing area. We start with 24/48 bytes, which is
4349 // prereserved space for [SP][CR][LR][3 x unused].
4351 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4353 nAltivecParamsAtEnd);
4355 // Calculate by how many bytes the stack has to be adjusted in case of tail
4356 // call optimization.
4357 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4359 // To protect arguments on the stack from being clobbered in a tail call,
4360 // force all the loads to happen before doing any other lowering.
4362 Chain = DAG.getStackArgumentTokenFactor(Chain);
4364 // Adjust the stack pointer for the new arguments...
4365 // These operations are automatically eliminated by the prolog/epilog pass
4366 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4368 SDValue CallSeqStart = Chain;
4370 // Load the return address and frame pointer so it can be move somewhere else
4373 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4376 // Set up a copy of the stack pointer for use loading and storing any
4377 // arguments that may not fit in the registers available for argument
4381 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4383 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4385 // Figure out which arguments are going to go in registers, and which in
4386 // memory. Also, if this is a vararg function, floating point operations
4387 // must be stored to our stack, and loaded into integer regs as well, if
4388 // any integer regs are available for argument passing.
4389 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4390 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4392 static const uint16_t GPR_32[] = { // 32-bit registers.
4393 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4394 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4396 static const uint16_t GPR_64[] = { // 64-bit registers.
4397 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4398 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4400 static const uint16_t *FPR = GetFPR();
4402 static const uint16_t VR[] = {
4403 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4404 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4406 const unsigned NumGPRs = array_lengthof(GPR_32);
4407 const unsigned NumFPRs = 13;
4408 const unsigned NumVRs = array_lengthof(VR);
4410 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4412 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4413 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4415 SmallVector<SDValue, 8> MemOpChains;
4416 for (unsigned i = 0; i != NumOps; ++i) {
4417 SDValue Arg = OutVals[i];
4418 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4420 // PtrOff will be used to store the current argument to the stack if a
4421 // register cannot be found for it.
4424 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4426 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4428 // On PPC64, promote integers to 64-bit values.
4429 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4430 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4431 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4432 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4435 // FIXME memcpy is used way more than necessary. Correctness first.
4436 // Note: "by value" is code for passing a structure by value, not
4438 if (Flags.isByVal()) {
4439 unsigned Size = Flags.getByValSize();
4440 // Very small objects are passed right-justified. Everything else is
4441 // passed left-justified.
4442 if (Size==1 || Size==2) {
4443 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4444 if (GPR_idx != NumGPRs) {
4445 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4446 MachinePointerInfo(), VT,
4448 MemOpChains.push_back(Load.getValue(1));
4449 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4451 ArgOffset += PtrByteSize;
4453 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4454 PtrOff.getValueType());
4455 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4456 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4459 ArgOffset += PtrByteSize;
4463 // Copy entire object into memory. There are cases where gcc-generated
4464 // code assumes it is there, even if it could be put entirely into
4465 // registers. (This is not what the doc says.)
4466 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4470 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4471 // copy the pieces of the object that fit into registers from the
4472 // parameter save area.
4473 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4474 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4475 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4476 if (GPR_idx != NumGPRs) {
4477 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4478 MachinePointerInfo(),
4479 false, false, false, 0);
4480 MemOpChains.push_back(Load.getValue(1));
4481 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4482 ArgOffset += PtrByteSize;
4484 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4491 switch (Arg.getSimpleValueType().SimpleTy) {
4492 default: llvm_unreachable("Unexpected ValueType for argument!");
4496 if (GPR_idx != NumGPRs) {
4497 if (Arg.getValueType() == MVT::i1)
4498 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4500 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4502 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4503 isPPC64, isTailCall, false, MemOpChains,
4504 TailCallArguments, dl);
4506 ArgOffset += PtrByteSize;
4510 if (FPR_idx != NumFPRs) {
4511 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4514 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4515 MachinePointerInfo(), false, false, 0);
4516 MemOpChains.push_back(Store);
4518 // Float varargs are always shadowed in available integer registers
4519 if (GPR_idx != NumGPRs) {
4520 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4521 MachinePointerInfo(), false, false,
4523 MemOpChains.push_back(Load.getValue(1));
4524 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4526 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4527 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4528 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4529 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4530 MachinePointerInfo(),
4531 false, false, false, 0);
4532 MemOpChains.push_back(Load.getValue(1));
4533 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4536 // If we have any FPRs remaining, we may also have GPRs remaining.
4537 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4539 if (GPR_idx != NumGPRs)
4541 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4542 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4546 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4547 isPPC64, isTailCall, false, MemOpChains,
4548 TailCallArguments, dl);
4552 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4559 // These go aligned on the stack, or in the corresponding R registers
4560 // when within range. The Darwin PPC ABI doc claims they also go in
4561 // V registers; in fact gcc does this only for arguments that are
4562 // prototyped, not for those that match the ... We do it for all
4563 // arguments, seems to work.
4564 while (ArgOffset % 16 !=0) {
4565 ArgOffset += PtrByteSize;
4566 if (GPR_idx != NumGPRs)
4569 // We could elide this store in the case where the object fits
4570 // entirely in R registers. Maybe later.
4571 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4572 DAG.getConstant(ArgOffset, PtrVT));
4573 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4574 MachinePointerInfo(), false, false, 0);
4575 MemOpChains.push_back(Store);
4576 if (VR_idx != NumVRs) {
4577 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4578 MachinePointerInfo(),
4579 false, false, false, 0);
4580 MemOpChains.push_back(Load.getValue(1));
4581 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4584 for (unsigned i=0; i<16; i+=PtrByteSize) {
4585 if (GPR_idx == NumGPRs)
4587 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4588 DAG.getConstant(i, PtrVT));
4589 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4590 false, false, false, 0);
4591 MemOpChains.push_back(Load.getValue(1));
4592 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4597 // Non-varargs Altivec params generally go in registers, but have
4598 // stack space allocated at the end.
4599 if (VR_idx != NumVRs) {
4600 // Doesn't have GPR space allocated.
4601 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4602 } else if (nAltivecParamsAtEnd==0) {
4603 // We are emitting Altivec params in order.
4604 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4605 isPPC64, isTailCall, true, MemOpChains,
4606 TailCallArguments, dl);
4612 // If all Altivec parameters fit in registers, as they usually do,
4613 // they get stack space following the non-Altivec parameters. We
4614 // don't track this here because nobody below needs it.
4615 // If there are more Altivec parameters than fit in registers emit
4617 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4619 // Offset is aligned; skip 1st 12 params which go in V registers.
4620 ArgOffset = ((ArgOffset+15)/16)*16;
4622 for (unsigned i = 0; i != NumOps; ++i) {
4623 SDValue Arg = OutVals[i];
4624 EVT ArgType = Outs[i].VT;
4625 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4626 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4629 // We are emitting Altivec params in order.
4630 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4631 isPPC64, isTailCall, true, MemOpChains,
4632 TailCallArguments, dl);
4639 if (!MemOpChains.empty())
4640 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4641 &MemOpChains[0], MemOpChains.size());
4643 // On Darwin, R12 must contain the address of an indirect callee. This does
4644 // not mean the MTCTR instruction must use R12; it's easier to model this as
4645 // an extra parameter, so do that.
4647 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4648 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4649 !isBLACompatibleAddress(Callee, DAG))
4650 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4651 PPC::R12), Callee));
4653 // Build a sequence of copy-to-reg nodes chained together with token chain
4654 // and flag operands which copy the outgoing args into the appropriate regs.
4656 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4657 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4658 RegsToPass[i].second, InFlag);
4659 InFlag = Chain.getValue(1);
4663 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4664 FPOp, true, TailCallArguments);
4666 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4667 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4672 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4673 MachineFunction &MF, bool isVarArg,
4674 const SmallVectorImpl<ISD::OutputArg> &Outs,
4675 LLVMContext &Context) const {
4676 SmallVector<CCValAssign, 16> RVLocs;
4677 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4679 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4683 PPCTargetLowering::LowerReturn(SDValue Chain,
4684 CallingConv::ID CallConv, bool isVarArg,
4685 const SmallVectorImpl<ISD::OutputArg> &Outs,
4686 const SmallVectorImpl<SDValue> &OutVals,
4687 SDLoc dl, SelectionDAG &DAG) const {
4689 SmallVector<CCValAssign, 16> RVLocs;
4690 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4691 getTargetMachine(), RVLocs, *DAG.getContext());
4692 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4695 SmallVector<SDValue, 4> RetOps(1, Chain);
4697 // Copy the result values into the output registers.
4698 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4699 CCValAssign &VA = RVLocs[i];
4700 assert(VA.isRegLoc() && "Can only return in registers!");
4702 SDValue Arg = OutVals[i];
4704 switch (VA.getLocInfo()) {
4705 default: llvm_unreachable("Unknown loc info!");
4706 case CCValAssign::Full: break;
4707 case CCValAssign::AExt:
4708 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4710 case CCValAssign::ZExt:
4711 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4713 case CCValAssign::SExt:
4714 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4718 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4719 Flag = Chain.getValue(1);
4720 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4723 RetOps[0] = Chain; // Update chain.
4725 // Add the flag if we have it.
4727 RetOps.push_back(Flag);
4729 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4730 &RetOps[0], RetOps.size());
4733 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4734 const PPCSubtarget &Subtarget) const {
4735 // When we pop the dynamic allocation we need to restore the SP link.
4738 // Get the corect type for pointers.
4739 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4741 // Construct the stack pointer operand.
4742 bool isPPC64 = Subtarget.isPPC64();
4743 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4744 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4746 // Get the operands for the STACKRESTORE.
4747 SDValue Chain = Op.getOperand(0);
4748 SDValue SaveSP = Op.getOperand(1);
4750 // Load the old link SP.
4751 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4752 MachinePointerInfo(),
4753 false, false, false, 0);
4755 // Restore the stack pointer.
4756 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4758 // Store the old link SP.
4759 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4766 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4767 MachineFunction &MF = DAG.getMachineFunction();
4768 bool isPPC64 = PPCSubTarget.isPPC64();
4769 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4770 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4772 // Get current frame pointer save index. The users of this index will be
4773 // primarily DYNALLOC instructions.
4774 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4775 int RASI = FI->getReturnAddrSaveIndex();
4777 // If the frame pointer save index hasn't been defined yet.
4779 // Find out what the fix offset of the frame pointer save area.
4780 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4781 // Allocate the frame index for frame pointer save area.
4782 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4784 FI->setReturnAddrSaveIndex(RASI);
4786 return DAG.getFrameIndex(RASI, PtrVT);
4790 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4791 MachineFunction &MF = DAG.getMachineFunction();
4792 bool isPPC64 = PPCSubTarget.isPPC64();
4793 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4794 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4796 // Get current frame pointer save index. The users of this index will be
4797 // primarily DYNALLOC instructions.
4798 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4799 int FPSI = FI->getFramePointerSaveIndex();
4801 // If the frame pointer save index hasn't been defined yet.
4803 // Find out what the fix offset of the frame pointer save area.
4804 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4807 // Allocate the frame index for frame pointer save area.
4808 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4810 FI->setFramePointerSaveIndex(FPSI);
4812 return DAG.getFrameIndex(FPSI, PtrVT);
4815 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4817 const PPCSubtarget &Subtarget) const {
4819 SDValue Chain = Op.getOperand(0);
4820 SDValue Size = Op.getOperand(1);
4823 // Get the corect type for pointers.
4824 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4826 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4827 DAG.getConstant(0, PtrVT), Size);
4828 // Construct a node for the frame pointer save index.
4829 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4830 // Build a DYNALLOC node.
4831 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4832 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4833 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4836 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4837 SelectionDAG &DAG) const {
4839 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4840 DAG.getVTList(MVT::i32, MVT::Other),
4841 Op.getOperand(0), Op.getOperand(1));
4844 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4845 SelectionDAG &DAG) const {
4847 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4848 Op.getOperand(0), Op.getOperand(1));
4851 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4852 assert(Op.getValueType() == MVT::i1 &&
4853 "Custom lowering only for i1 loads");
4855 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4858 LoadSDNode *LD = cast<LoadSDNode>(Op);
4860 SDValue Chain = LD->getChain();
4861 SDValue BasePtr = LD->getBasePtr();
4862 MachineMemOperand *MMO = LD->getMemOperand();
4864 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4865 BasePtr, MVT::i8, MMO);
4866 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4868 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4869 return DAG.getMergeValues(Ops, 2, dl);
4872 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4873 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4874 "Custom lowering only for i1 stores");
4876 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4879 StoreSDNode *ST = cast<StoreSDNode>(Op);
4881 SDValue Chain = ST->getChain();
4882 SDValue BasePtr = ST->getBasePtr();
4883 SDValue Value = ST->getValue();
4884 MachineMemOperand *MMO = ST->getMemOperand();
4886 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4887 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4890 // FIXME: Remove this once the ANDI glue bug is fixed:
4891 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4892 assert(Op.getValueType() == MVT::i1 &&
4893 "Custom lowering only for i1 results");
4896 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4900 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4902 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4903 // Not FP? Not a fsel.
4904 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4905 !Op.getOperand(2).getValueType().isFloatingPoint())
4908 // We might be able to do better than this under some circumstances, but in
4909 // general, fsel-based lowering of select is a finite-math-only optimization.
4910 // For more information, see section F.3 of the 2.06 ISA specification.
4911 if (!DAG.getTarget().Options.NoInfsFPMath ||
4912 !DAG.getTarget().Options.NoNaNsFPMath)
4915 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4917 EVT ResVT = Op.getValueType();
4918 EVT CmpVT = Op.getOperand(0).getValueType();
4919 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4920 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4923 // If the RHS of the comparison is a 0.0, we don't need to do the
4924 // subtraction at all.
4926 if (isFloatingPointZero(RHS))
4928 default: break; // SETUO etc aren't handled by fsel.
4932 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4933 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4934 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4935 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4936 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4937 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4938 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4941 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4944 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4945 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4946 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4949 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4952 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4953 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4954 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4955 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4960 default: break; // SETUO etc aren't handled by fsel.
4964 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4965 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4966 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4967 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4968 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4969 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4970 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4971 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
4974 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4975 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4976 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4977 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4980 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4981 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4982 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4983 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4986 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4987 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4988 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4989 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4992 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4993 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4994 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4995 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5000 // FIXME: Split this code up when LegalizeDAGTypes lands.
5001 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5003 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5004 SDValue Src = Op.getOperand(0);
5005 if (Src.getValueType() == MVT::f32)
5006 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5009 switch (Op.getSimpleValueType().SimpleTy) {
5010 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5012 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5013 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5018 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
5019 "i64 FP_TO_UINT is supported only with FPCVT");
5020 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5026 // Convert the FP value to an int value through memory.
5027 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
5028 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
5029 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5030 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5031 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5033 // Emit a store to the stack slot.
5036 MachineFunction &MF = DAG.getMachineFunction();
5037 MachineMemOperand *MMO =
5038 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5039 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5040 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5041 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
5044 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5045 MPI, false, false, 0);
5047 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5049 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5050 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5051 DAG.getConstant(4, FIPtr.getValueType()));
5052 MPI = MachinePointerInfo();
5055 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5056 false, false, false, 0);
5059 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5060 SelectionDAG &DAG) const {
5062 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5063 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5066 if (Op.getOperand(0).getValueType() == MVT::i1)
5067 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5068 DAG.getConstantFP(1.0, Op.getValueType()),
5069 DAG.getConstantFP(0.0, Op.getValueType()));
5071 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
5072 "UINT_TO_FP is supported only with FPCVT");
5074 // If we have FCFIDS, then use it when converting to single-precision.
5075 // Otherwise, convert to double-precision and then round.
5076 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5077 (Op.getOpcode() == ISD::UINT_TO_FP ?
5078 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5079 (Op.getOpcode() == ISD::UINT_TO_FP ?
5080 PPCISD::FCFIDU : PPCISD::FCFID);
5081 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5082 MVT::f32 : MVT::f64;
5084 if (Op.getOperand(0).getValueType() == MVT::i64) {
5085 SDValue SINT = Op.getOperand(0);
5086 // When converting to single-precision, we actually need to convert
5087 // to double-precision first and then round to single-precision.
5088 // To avoid double-rounding effects during that operation, we have
5089 // to prepare the input operand. Bits that might be truncated when
5090 // converting to double-precision are replaced by a bit that won't
5091 // be lost at this stage, but is below the single-precision rounding
5094 // However, if -enable-unsafe-fp-math is in effect, accept double
5095 // rounding to avoid the extra overhead.
5096 if (Op.getValueType() == MVT::f32 &&
5097 !PPCSubTarget.hasFPCVT() &&
5098 !DAG.getTarget().Options.UnsafeFPMath) {
5100 // Twiddle input to make sure the low 11 bits are zero. (If this
5101 // is the case, we are guaranteed the value will fit into the 53 bit
5102 // mantissa of an IEEE double-precision value without rounding.)
5103 // If any of those low 11 bits were not zero originally, make sure
5104 // bit 12 (value 2048) is set instead, so that the final rounding
5105 // to single-precision gets the correct result.
5106 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5107 SINT, DAG.getConstant(2047, MVT::i64));
5108 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5109 Round, DAG.getConstant(2047, MVT::i64));
5110 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5111 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5112 Round, DAG.getConstant(-2048, MVT::i64));
5114 // However, we cannot use that value unconditionally: if the magnitude
5115 // of the input value is small, the bit-twiddling we did above might
5116 // end up visibly changing the output. Fortunately, in that case, we
5117 // don't need to twiddle bits since the original input will convert
5118 // exactly to double-precision floating-point already. Therefore,
5119 // construct a conditional to use the original value if the top 11
5120 // bits are all sign-bit copies, and use the rounded value computed
5122 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5123 SINT, DAG.getConstant(53, MVT::i32));
5124 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5125 Cond, DAG.getConstant(1, MVT::i64));
5126 Cond = DAG.getSetCC(dl, MVT::i32,
5127 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5129 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5132 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5133 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5135 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5136 FP = DAG.getNode(ISD::FP_ROUND, dl,
5137 MVT::f32, FP, DAG.getIntPtrConstant(0));
5141 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5142 "Unhandled INT_TO_FP type in custom expander!");
5143 // Since we only generate this in 64-bit mode, we can take advantage of
5144 // 64-bit registers. In particular, sign extend the input value into the
5145 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5146 // then lfd it and fcfid it.
5147 MachineFunction &MF = DAG.getMachineFunction();
5148 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5149 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5152 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5153 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5154 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5156 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5157 MachinePointerInfo::getFixedStack(FrameIdx),
5160 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5161 "Expected an i32 store");
5162 MachineMemOperand *MMO =
5163 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5164 MachineMemOperand::MOLoad, 4, 4);
5165 SDValue Ops[] = { Store, FIdx };
5166 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5167 PPCISD::LFIWZX : PPCISD::LFIWAX,
5168 dl, DAG.getVTList(MVT::f64, MVT::Other),
5169 Ops, 2, MVT::i32, MMO);
5171 assert(PPCSubTarget.isPPC64() &&
5172 "i32->FP without LFIWAX supported only on PPC64");
5174 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5175 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5177 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5180 // STD the extended value into the stack slot.
5181 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5182 MachinePointerInfo::getFixedStack(FrameIdx),
5185 // Load the value as a double.
5186 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5187 MachinePointerInfo::getFixedStack(FrameIdx),
5188 false, false, false, 0);
5191 // FCFID it and return it.
5192 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5193 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5194 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5198 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5199 SelectionDAG &DAG) const {
5202 The rounding mode is in bits 30:31 of FPSR, and has the following
5209 FLT_ROUNDS, on the other hand, expects the following:
5216 To perform the conversion, we do:
5217 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5220 MachineFunction &MF = DAG.getMachineFunction();
5221 EVT VT = Op.getValueType();
5222 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5223 SDValue MFFSreg, InFlag;
5225 // Save FP Control Word to register
5227 MVT::f64, // return register
5228 MVT::Glue // unused in this context
5230 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5232 // Save FP register to stack slot
5233 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5234 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5235 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5236 StackSlot, MachinePointerInfo(), false, false,0);
5238 // Load FP Control Word from low 32 bits of stack slot.
5239 SDValue Four = DAG.getConstant(4, PtrVT);
5240 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5241 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5242 false, false, false, 0);
5244 // Transform as necessary
5246 DAG.getNode(ISD::AND, dl, MVT::i32,
5247 CWD, DAG.getConstant(3, MVT::i32));
5249 DAG.getNode(ISD::SRL, dl, MVT::i32,
5250 DAG.getNode(ISD::AND, dl, MVT::i32,
5251 DAG.getNode(ISD::XOR, dl, MVT::i32,
5252 CWD, DAG.getConstant(3, MVT::i32)),
5253 DAG.getConstant(3, MVT::i32)),
5254 DAG.getConstant(1, MVT::i32));
5257 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5259 return DAG.getNode((VT.getSizeInBits() < 16 ?
5260 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5263 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5264 EVT VT = Op.getValueType();
5265 unsigned BitWidth = VT.getSizeInBits();
5267 assert(Op.getNumOperands() == 3 &&
5268 VT == Op.getOperand(1).getValueType() &&
5271 // Expand into a bunch of logical ops. Note that these ops
5272 // depend on the PPC behavior for oversized shift amounts.
5273 SDValue Lo = Op.getOperand(0);
5274 SDValue Hi = Op.getOperand(1);
5275 SDValue Amt = Op.getOperand(2);
5276 EVT AmtVT = Amt.getValueType();
5278 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5279 DAG.getConstant(BitWidth, AmtVT), Amt);
5280 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5281 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5282 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5283 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5284 DAG.getConstant(-BitWidth, AmtVT));
5285 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5286 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5287 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5288 SDValue OutOps[] = { OutLo, OutHi };
5289 return DAG.getMergeValues(OutOps, 2, dl);
5292 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5293 EVT VT = Op.getValueType();
5295 unsigned BitWidth = VT.getSizeInBits();
5296 assert(Op.getNumOperands() == 3 &&
5297 VT == Op.getOperand(1).getValueType() &&
5300 // Expand into a bunch of logical ops. Note that these ops
5301 // depend on the PPC behavior for oversized shift amounts.
5302 SDValue Lo = Op.getOperand(0);
5303 SDValue Hi = Op.getOperand(1);
5304 SDValue Amt = Op.getOperand(2);
5305 EVT AmtVT = Amt.getValueType();
5307 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5308 DAG.getConstant(BitWidth, AmtVT), Amt);
5309 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5310 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5311 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5312 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5313 DAG.getConstant(-BitWidth, AmtVT));
5314 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5315 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5316 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5317 SDValue OutOps[] = { OutLo, OutHi };
5318 return DAG.getMergeValues(OutOps, 2, dl);
5321 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5323 EVT VT = Op.getValueType();
5324 unsigned BitWidth = VT.getSizeInBits();
5325 assert(Op.getNumOperands() == 3 &&
5326 VT == Op.getOperand(1).getValueType() &&
5329 // Expand into a bunch of logical ops, followed by a select_cc.
5330 SDValue Lo = Op.getOperand(0);
5331 SDValue Hi = Op.getOperand(1);
5332 SDValue Amt = Op.getOperand(2);
5333 EVT AmtVT = Amt.getValueType();
5335 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5336 DAG.getConstant(BitWidth, AmtVT), Amt);
5337 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5338 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5339 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5340 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5341 DAG.getConstant(-BitWidth, AmtVT));
5342 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5343 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5344 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5345 Tmp4, Tmp6, ISD::SETLE);
5346 SDValue OutOps[] = { OutLo, OutHi };
5347 return DAG.getMergeValues(OutOps, 2, dl);
5350 //===----------------------------------------------------------------------===//
5351 // Vector related lowering.
5354 /// BuildSplatI - Build a canonical splati of Val with an element size of
5355 /// SplatSize. Cast the result to VT.
5356 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5357 SelectionDAG &DAG, SDLoc dl) {
5358 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5360 static const EVT VTys[] = { // canonical VT to use for each size.
5361 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5364 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5366 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5370 EVT CanonicalVT = VTys[SplatSize-1];
5372 // Build a canonical splat for this value.
5373 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5374 SmallVector<SDValue, 8> Ops;
5375 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5376 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5377 &Ops[0], Ops.size());
5378 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5381 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5382 /// specified intrinsic ID.
5383 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5384 SelectionDAG &DAG, SDLoc dl,
5385 EVT DestVT = MVT::Other) {
5386 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5387 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5388 DAG.getConstant(IID, MVT::i32), Op);
5391 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5392 /// specified intrinsic ID.
5393 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5394 SelectionDAG &DAG, SDLoc dl,
5395 EVT DestVT = MVT::Other) {
5396 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5397 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5398 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5401 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5402 /// specified intrinsic ID.
5403 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5404 SDValue Op2, SelectionDAG &DAG,
5405 SDLoc dl, EVT DestVT = MVT::Other) {
5406 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5407 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5408 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5412 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5413 /// amount. The result has the specified value type.
5414 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5415 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5416 // Force LHS/RHS to be the right type.
5417 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5418 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5421 for (unsigned i = 0; i != 16; ++i)
5423 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5424 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5427 // If this is a case we can't handle, return null and let the default
5428 // expansion code take care of it. If we CAN select this case, and if it
5429 // selects to a single instruction, return Op. Otherwise, if we can codegen
5430 // this case more efficiently than a constant pool load, lower it to the
5431 // sequence of ops that should be used.
5432 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5433 SelectionDAG &DAG) const {
5435 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5436 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5438 // Check if this is a splat of a constant value.
5439 APInt APSplatBits, APSplatUndef;
5440 unsigned SplatBitSize;
5442 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5443 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5446 unsigned SplatBits = APSplatBits.getZExtValue();
5447 unsigned SplatUndef = APSplatUndef.getZExtValue();
5448 unsigned SplatSize = SplatBitSize / 8;
5450 // First, handle single instruction cases.
5453 if (SplatBits == 0) {
5454 // Canonicalize all zero vectors to be v4i32.
5455 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5456 SDValue Z = DAG.getConstant(0, MVT::i32);
5457 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5458 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5463 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5464 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5466 if (SextVal >= -16 && SextVal <= 15)
5467 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5470 // Two instruction sequences.
5472 // If this value is in the range [-32,30] and is even, use:
5473 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5474 // If this value is in the range [17,31] and is odd, use:
5475 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5476 // If this value is in the range [-31,-17] and is odd, use:
5477 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5478 // Note the last two are three-instruction sequences.
5479 if (SextVal >= -32 && SextVal <= 31) {
5480 // To avoid having these optimizations undone by constant folding,
5481 // we convert to a pseudo that will be expanded later into one of
5483 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5484 EVT VT = Op.getValueType();
5485 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5486 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5487 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5490 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5491 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5493 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5494 // Make -1 and vspltisw -1:
5495 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5497 // Make the VSLW intrinsic, computing 0x8000_0000.
5498 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5501 // xor by OnesV to invert it.
5502 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5503 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5506 // Check to see if this is a wide variety of vsplti*, binop self cases.
5507 static const signed char SplatCsts[] = {
5508 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5509 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5512 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5513 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5514 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5515 int i = SplatCsts[idx];
5517 // Figure out what shift amount will be used by altivec if shifted by i in
5519 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5521 // vsplti + shl self.
5522 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5523 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5524 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5525 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5526 Intrinsic::ppc_altivec_vslw
5528 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5529 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5532 // vsplti + srl self.
5533 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5534 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5535 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5536 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5537 Intrinsic::ppc_altivec_vsrw
5539 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5540 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5543 // vsplti + sra self.
5544 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5545 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5546 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5547 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5548 Intrinsic::ppc_altivec_vsraw
5550 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5551 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5554 // vsplti + rol self.
5555 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5556 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5557 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5558 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5559 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5560 Intrinsic::ppc_altivec_vrlw
5562 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5563 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5566 // t = vsplti c, result = vsldoi t, t, 1
5567 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5568 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5569 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5571 // t = vsplti c, result = vsldoi t, t, 2
5572 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5573 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5574 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5576 // t = vsplti c, result = vsldoi t, t, 3
5577 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5578 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5579 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5586 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5587 /// the specified operations to build the shuffle.
5588 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5589 SDValue RHS, SelectionDAG &DAG,
5591 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5592 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5593 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5596 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5608 if (OpNum == OP_COPY) {
5609 if (LHSID == (1*9+2)*9+3) return LHS;
5610 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5614 SDValue OpLHS, OpRHS;
5615 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5616 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5620 default: llvm_unreachable("Unknown i32 permute!");
5622 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5623 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5624 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5625 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5628 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5629 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5630 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5631 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5634 for (unsigned i = 0; i != 16; ++i)
5635 ShufIdxs[i] = (i&3)+0;
5638 for (unsigned i = 0; i != 16; ++i)
5639 ShufIdxs[i] = (i&3)+4;
5642 for (unsigned i = 0; i != 16; ++i)
5643 ShufIdxs[i] = (i&3)+8;
5646 for (unsigned i = 0; i != 16; ++i)
5647 ShufIdxs[i] = (i&3)+12;
5650 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5652 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5654 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5656 EVT VT = OpLHS.getValueType();
5657 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5658 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5659 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5660 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5663 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5664 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5665 /// return the code it can be lowered into. Worst case, it can always be
5666 /// lowered into a vperm.
5667 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5668 SelectionDAG &DAG) const {
5670 SDValue V1 = Op.getOperand(0);
5671 SDValue V2 = Op.getOperand(1);
5672 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5673 EVT VT = Op.getValueType();
5675 // Cases that are handled by instructions that take permute immediates
5676 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5677 // selected by the instruction selector.
5678 if (V2.getOpcode() == ISD::UNDEF) {
5679 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5680 PPC::isSplatShuffleMask(SVOp, 2) ||
5681 PPC::isSplatShuffleMask(SVOp, 4) ||
5682 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5683 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5684 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5685 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5686 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5687 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5688 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5689 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5690 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5695 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5696 // and produce a fixed permutation. If any of these match, do not lower to
5698 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5699 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5700 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5701 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5702 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5703 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5704 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5705 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5706 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5709 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5710 // perfect shuffle table to emit an optimal matching sequence.
5711 ArrayRef<int> PermMask = SVOp->getMask();
5713 unsigned PFIndexes[4];
5714 bool isFourElementShuffle = true;
5715 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5716 unsigned EltNo = 8; // Start out undef.
5717 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5718 if (PermMask[i*4+j] < 0)
5719 continue; // Undef, ignore it.
5721 unsigned ByteSource = PermMask[i*4+j];
5722 if ((ByteSource & 3) != j) {
5723 isFourElementShuffle = false;
5728 EltNo = ByteSource/4;
5729 } else if (EltNo != ByteSource/4) {
5730 isFourElementShuffle = false;
5734 PFIndexes[i] = EltNo;
5737 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5738 // perfect shuffle vector to determine if it is cost effective to do this as
5739 // discrete instructions, or whether we should use a vperm.
5740 if (isFourElementShuffle) {
5741 // Compute the index in the perfect shuffle table.
5742 unsigned PFTableIndex =
5743 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5745 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5746 unsigned Cost = (PFEntry >> 30);
5748 // Determining when to avoid vperm is tricky. Many things affect the cost
5749 // of vperm, particularly how many times the perm mask needs to be computed.
5750 // For example, if the perm mask can be hoisted out of a loop or is already
5751 // used (perhaps because there are multiple permutes with the same shuffle
5752 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5753 // the loop requires an extra register.
5755 // As a compromise, we only emit discrete instructions if the shuffle can be
5756 // generated in 3 or fewer operations. When we have loop information
5757 // available, if this block is within a loop, we should avoid using vperm
5758 // for 3-operation perms and use a constant pool load instead.
5760 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5763 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5764 // vector that will get spilled to the constant pool.
5765 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5767 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5768 // that it is in input element units, not in bytes. Convert now.
5769 EVT EltVT = V1.getValueType().getVectorElementType();
5770 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5772 SmallVector<SDValue, 16> ResultMask;
5773 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5774 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5776 for (unsigned j = 0; j != BytesPerElement; ++j)
5777 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5781 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5782 &ResultMask[0], ResultMask.size());
5783 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5786 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5787 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5788 /// information about the intrinsic.
5789 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5791 unsigned IntrinsicID =
5792 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5795 switch (IntrinsicID) {
5796 default: return false;
5797 // Comparison predicates.
5798 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5799 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5800 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5801 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5802 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5803 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5804 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5805 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5806 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5807 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5808 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5809 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5810 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5812 // Normal Comparisons.
5813 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5814 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5815 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5816 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5817 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5818 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5819 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5820 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5821 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5822 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5823 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5824 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5825 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5830 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5831 /// lower, do it, otherwise return null.
5832 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5833 SelectionDAG &DAG) const {
5834 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5835 // opcode number of the comparison.
5839 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5840 return SDValue(); // Don't custom lower most intrinsics.
5842 // If this is a non-dot comparison, make the VCMP node and we are done.
5844 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5845 Op.getOperand(1), Op.getOperand(2),
5846 DAG.getConstant(CompareOpc, MVT::i32));
5847 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5850 // Create the PPCISD altivec 'dot' comparison node.
5852 Op.getOperand(2), // LHS
5853 Op.getOperand(3), // RHS
5854 DAG.getConstant(CompareOpc, MVT::i32)
5856 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5857 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5859 // Now that we have the comparison, emit a copy from the CR to a GPR.
5860 // This is flagged to the above dot comparison.
5861 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5862 DAG.getRegister(PPC::CR6, MVT::i32),
5863 CompNode.getValue(1));
5865 // Unpack the result based on how the target uses it.
5866 unsigned BitNo; // Bit # of CR6.
5867 bool InvertBit; // Invert result?
5868 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5869 default: // Can't happen, don't crash on invalid number though.
5870 case 0: // Return the value of the EQ bit of CR6.
5871 BitNo = 0; InvertBit = false;
5873 case 1: // Return the inverted value of the EQ bit of CR6.
5874 BitNo = 0; InvertBit = true;
5876 case 2: // Return the value of the LT bit of CR6.
5877 BitNo = 2; InvertBit = false;
5879 case 3: // Return the inverted value of the LT bit of CR6.
5880 BitNo = 2; InvertBit = true;
5884 // Shift the bit into the low position.
5885 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5886 DAG.getConstant(8-(3-BitNo), MVT::i32));
5888 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5889 DAG.getConstant(1, MVT::i32));
5891 // If we are supposed to, toggle the bit.
5893 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5894 DAG.getConstant(1, MVT::i32));
5898 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5899 SelectionDAG &DAG) const {
5901 // Create a stack slot that is 16-byte aligned.
5902 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5903 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5904 EVT PtrVT = getPointerTy();
5905 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5907 // Store the input value into Value#0 of the stack slot.
5908 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5909 Op.getOperand(0), FIdx, MachinePointerInfo(),
5912 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5913 false, false, false, 0);
5916 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5918 if (Op.getValueType() == MVT::v4i32) {
5919 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5921 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5922 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5924 SDValue RHSSwap = // = vrlw RHS, 16
5925 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5927 // Shrinkify inputs to v8i16.
5928 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5929 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5930 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5932 // Low parts multiplied together, generating 32-bit results (we ignore the
5934 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5935 LHS, RHS, DAG, dl, MVT::v4i32);
5937 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5938 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5939 // Shift the high parts up 16 bits.
5940 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5942 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5943 } else if (Op.getValueType() == MVT::v8i16) {
5944 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5946 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5948 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5949 LHS, RHS, Zero, DAG, dl);
5950 } else if (Op.getValueType() == MVT::v16i8) {
5951 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5953 // Multiply the even 8-bit parts, producing 16-bit sums.
5954 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5955 LHS, RHS, DAG, dl, MVT::v8i16);
5956 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5958 // Multiply the odd 8-bit parts, producing 16-bit sums.
5959 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5960 LHS, RHS, DAG, dl, MVT::v8i16);
5961 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5963 // Merge the results together.
5965 for (unsigned i = 0; i != 8; ++i) {
5967 Ops[i*2+1] = 2*i+1+16;
5969 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5971 llvm_unreachable("Unknown mul to lower!");
5975 /// LowerOperation - Provide custom lowering hooks for some operations.
5977 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5978 switch (Op.getOpcode()) {
5979 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5980 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5981 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5982 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5983 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5984 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5985 case ISD::SETCC: return LowerSETCC(Op, DAG);
5986 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5987 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5989 return LowerVASTART(Op, DAG, PPCSubTarget);
5992 return LowerVAARG(Op, DAG, PPCSubTarget);
5995 return LowerVACOPY(Op, DAG, PPCSubTarget);
5997 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5998 case ISD::DYNAMIC_STACKALLOC:
5999 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
6001 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6002 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6004 case ISD::LOAD: return LowerLOAD(Op, DAG);
6005 case ISD::STORE: return LowerSTORE(Op, DAG);
6006 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6007 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6008 case ISD::FP_TO_UINT:
6009 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6011 case ISD::UINT_TO_FP:
6012 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6013 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6015 // Lower 64-bit shifts.
6016 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6017 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6018 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6020 // Vector-related lowering.
6021 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6022 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6023 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6024 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6025 case ISD::MUL: return LowerMUL(Op, DAG);
6027 // For counter-based loop handling.
6028 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6030 // Frame & Return address.
6031 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6032 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6036 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6037 SmallVectorImpl<SDValue>&Results,
6038 SelectionDAG &DAG) const {
6039 const TargetMachine &TM = getTargetMachine();
6041 switch (N->getOpcode()) {
6043 llvm_unreachable("Do not know how to custom type legalize this operation!");
6044 case ISD::INTRINSIC_W_CHAIN: {
6045 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6046 Intrinsic::ppc_is_decremented_ctr_nonzero)
6049 assert(N->getValueType(0) == MVT::i1 &&
6050 "Unexpected result type for CTR decrement intrinsic");
6051 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6052 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6053 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6056 Results.push_back(NewInt);
6057 Results.push_back(NewInt.getValue(1));
6061 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6062 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6065 EVT VT = N->getValueType(0);
6067 if (VT == MVT::i64) {
6068 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
6070 Results.push_back(NewNode);
6071 Results.push_back(NewNode.getValue(1));
6075 case ISD::FP_ROUND_INREG: {
6076 assert(N->getValueType(0) == MVT::ppcf128);
6077 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6078 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6079 MVT::f64, N->getOperand(0),
6080 DAG.getIntPtrConstant(0));
6081 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6082 MVT::f64, N->getOperand(0),
6083 DAG.getIntPtrConstant(1));
6085 // Add the two halves of the long double in round-to-zero mode.
6086 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6088 // We know the low half is about to be thrown away, so just use something
6090 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6094 case ISD::FP_TO_SINT:
6095 // LowerFP_TO_INT() can only handle f32 and f64.
6096 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6098 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6104 //===----------------------------------------------------------------------===//
6105 // Other Lowering Code
6106 //===----------------------------------------------------------------------===//
6109 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6110 bool is64bit, unsigned BinOpcode) const {
6111 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6112 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6114 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6115 MachineFunction *F = BB->getParent();
6116 MachineFunction::iterator It = BB;
6119 unsigned dest = MI->getOperand(0).getReg();
6120 unsigned ptrA = MI->getOperand(1).getReg();
6121 unsigned ptrB = MI->getOperand(2).getReg();
6122 unsigned incr = MI->getOperand(3).getReg();
6123 DebugLoc dl = MI->getDebugLoc();
6125 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6126 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6127 F->insert(It, loopMBB);
6128 F->insert(It, exitMBB);
6129 exitMBB->splice(exitMBB->begin(), BB,
6130 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6131 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6133 MachineRegisterInfo &RegInfo = F->getRegInfo();
6134 unsigned TmpReg = (!BinOpcode) ? incr :
6135 RegInfo.createVirtualRegister(
6136 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6137 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6141 // fallthrough --> loopMBB
6142 BB->addSuccessor(loopMBB);
6145 // l[wd]arx dest, ptr
6146 // add r0, dest, incr
6147 // st[wd]cx. r0, ptr
6149 // fallthrough --> exitMBB
6151 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6152 .addReg(ptrA).addReg(ptrB);
6154 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6155 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6156 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6157 BuildMI(BB, dl, TII->get(PPC::BCC))
6158 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6159 BB->addSuccessor(loopMBB);
6160 BB->addSuccessor(exitMBB);
6169 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6170 MachineBasicBlock *BB,
6171 bool is8bit, // operation
6172 unsigned BinOpcode) const {
6173 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6174 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6175 // In 64 bit mode we have to use 64 bits for addresses, even though the
6176 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6177 // registers without caring whether they're 32 or 64, but here we're
6178 // doing actual arithmetic on the addresses.
6179 bool is64bit = PPCSubTarget.isPPC64();
6180 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6182 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6183 MachineFunction *F = BB->getParent();
6184 MachineFunction::iterator It = BB;
6187 unsigned dest = MI->getOperand(0).getReg();
6188 unsigned ptrA = MI->getOperand(1).getReg();
6189 unsigned ptrB = MI->getOperand(2).getReg();
6190 unsigned incr = MI->getOperand(3).getReg();
6191 DebugLoc dl = MI->getDebugLoc();
6193 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6194 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6195 F->insert(It, loopMBB);
6196 F->insert(It, exitMBB);
6197 exitMBB->splice(exitMBB->begin(), BB,
6198 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6199 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6201 MachineRegisterInfo &RegInfo = F->getRegInfo();
6202 const TargetRegisterClass *RC =
6203 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6204 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6205 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6206 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6207 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6208 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6209 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6210 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6211 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6212 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6213 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6214 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6215 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6217 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6221 // fallthrough --> loopMBB
6222 BB->addSuccessor(loopMBB);
6224 // The 4-byte load must be aligned, while a char or short may be
6225 // anywhere in the word. Hence all this nasty bookkeeping code.
6226 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6227 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6228 // xori shift, shift1, 24 [16]
6229 // rlwinm ptr, ptr1, 0, 0, 29
6230 // slw incr2, incr, shift
6231 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6232 // slw mask, mask2, shift
6234 // lwarx tmpDest, ptr
6235 // add tmp, tmpDest, incr2
6236 // andc tmp2, tmpDest, mask
6237 // and tmp3, tmp, mask
6238 // or tmp4, tmp3, tmp2
6241 // fallthrough --> exitMBB
6242 // srw dest, tmpDest, shift
6243 if (ptrA != ZeroReg) {
6244 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6245 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6246 .addReg(ptrA).addReg(ptrB);
6250 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6251 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6252 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6253 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6255 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6256 .addReg(Ptr1Reg).addImm(0).addImm(61);
6258 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6259 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6260 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6261 .addReg(incr).addReg(ShiftReg);
6263 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6265 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6266 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6268 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6269 .addReg(Mask2Reg).addReg(ShiftReg);
6272 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6273 .addReg(ZeroReg).addReg(PtrReg);
6275 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6276 .addReg(Incr2Reg).addReg(TmpDestReg);
6277 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6278 .addReg(TmpDestReg).addReg(MaskReg);
6279 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6280 .addReg(TmpReg).addReg(MaskReg);
6281 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6282 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6283 BuildMI(BB, dl, TII->get(PPC::STWCX))
6284 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6285 BuildMI(BB, dl, TII->get(PPC::BCC))
6286 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6287 BB->addSuccessor(loopMBB);
6288 BB->addSuccessor(exitMBB);
6293 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6298 llvm::MachineBasicBlock*
6299 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6300 MachineBasicBlock *MBB) const {
6301 DebugLoc DL = MI->getDebugLoc();
6302 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6304 MachineFunction *MF = MBB->getParent();
6305 MachineRegisterInfo &MRI = MF->getRegInfo();
6307 const BasicBlock *BB = MBB->getBasicBlock();
6308 MachineFunction::iterator I = MBB;
6312 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6313 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6315 unsigned DstReg = MI->getOperand(0).getReg();
6316 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6317 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6318 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6319 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6321 MVT PVT = getPointerTy();
6322 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6323 "Invalid Pointer Size!");
6324 // For v = setjmp(buf), we generate
6327 // SjLjSetup mainMBB
6333 // buf[LabelOffset] = LR
6337 // v = phi(main, restore)
6340 MachineBasicBlock *thisMBB = MBB;
6341 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6342 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6343 MF->insert(I, mainMBB);
6344 MF->insert(I, sinkMBB);
6346 MachineInstrBuilder MIB;
6348 // Transfer the remainder of BB and its successor edges to sinkMBB.
6349 sinkMBB->splice(sinkMBB->begin(), MBB,
6350 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6351 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6353 // Note that the structure of the jmp_buf used here is not compatible
6354 // with that used by libc, and is not designed to be. Specifically, it
6355 // stores only those 'reserved' registers that LLVM does not otherwise
6356 // understand how to spill. Also, by convention, by the time this
6357 // intrinsic is called, Clang has already stored the frame address in the
6358 // first slot of the buffer and stack address in the third. Following the
6359 // X86 target code, we'll store the jump address in the second slot. We also
6360 // need to save the TOC pointer (R2) to handle jumps between shared
6361 // libraries, and that will be stored in the fourth slot. The thread
6362 // identifier (R13) is not affected.
6365 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6366 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6367 const int64_t BPOffset = 4 * PVT.getStoreSize();
6369 // Prepare IP either in reg.
6370 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6371 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6372 unsigned BufReg = MI->getOperand(1).getReg();
6374 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6375 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6379 MIB.setMemRefs(MMOBegin, MMOEnd);
6382 // Naked functions never have a base pointer, and so we use r1. For all
6383 // other functions, this decision must be delayed until during PEI.
6385 if (MF->getFunction()->getAttributes().hasAttribute(
6386 AttributeSet::FunctionIndex, Attribute::Naked))
6387 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6389 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6391 MIB = BuildMI(*thisMBB, MI, DL,
6392 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6396 MIB.setMemRefs(MMOBegin, MMOEnd);
6399 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6400 const PPCRegisterInfo *TRI =
6401 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6402 MIB.addRegMask(TRI->getNoPreservedMask());
6404 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6406 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6408 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6410 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6411 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6415 MIB = BuildMI(mainMBB, DL,
6416 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6419 if (PPCSubTarget.isPPC64()) {
6420 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6422 .addImm(LabelOffset)
6425 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6427 .addImm(LabelOffset)
6431 MIB.setMemRefs(MMOBegin, MMOEnd);
6433 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6434 mainMBB->addSuccessor(sinkMBB);
6437 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6438 TII->get(PPC::PHI), DstReg)
6439 .addReg(mainDstReg).addMBB(mainMBB)
6440 .addReg(restoreDstReg).addMBB(thisMBB);
6442 MI->eraseFromParent();
6447 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6448 MachineBasicBlock *MBB) const {
6449 DebugLoc DL = MI->getDebugLoc();
6450 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6452 MachineFunction *MF = MBB->getParent();
6453 MachineRegisterInfo &MRI = MF->getRegInfo();
6456 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6457 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6459 MVT PVT = getPointerTy();
6460 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6461 "Invalid Pointer Size!");
6463 const TargetRegisterClass *RC =
6464 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6465 unsigned Tmp = MRI.createVirtualRegister(RC);
6466 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6467 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6468 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6469 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6471 MachineInstrBuilder MIB;
6473 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6474 const int64_t SPOffset = 2 * PVT.getStoreSize();
6475 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6476 const int64_t BPOffset = 4 * PVT.getStoreSize();
6478 unsigned BufReg = MI->getOperand(0).getReg();
6480 // Reload FP (the jumped-to function may not have had a
6481 // frame pointer, and if so, then its r31 will be restored
6483 if (PVT == MVT::i64) {
6484 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6488 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6492 MIB.setMemRefs(MMOBegin, MMOEnd);
6495 if (PVT == MVT::i64) {
6496 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6497 .addImm(LabelOffset)
6500 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6501 .addImm(LabelOffset)
6504 MIB.setMemRefs(MMOBegin, MMOEnd);
6507 if (PVT == MVT::i64) {
6508 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6512 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6516 MIB.setMemRefs(MMOBegin, MMOEnd);
6519 if (PVT == MVT::i64) {
6520 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6524 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6528 MIB.setMemRefs(MMOBegin, MMOEnd);
6531 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6532 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6536 MIB.setMemRefs(MMOBegin, MMOEnd);
6540 BuildMI(*MBB, MI, DL,
6541 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6542 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6544 MI->eraseFromParent();
6549 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6550 MachineBasicBlock *BB) const {
6551 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6552 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6553 return emitEHSjLjSetJmp(MI, BB);
6554 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6555 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6556 return emitEHSjLjLongJmp(MI, BB);
6559 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6561 // To "insert" these instructions we actually have to insert their
6562 // control-flow patterns.
6563 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6564 MachineFunction::iterator It = BB;
6567 MachineFunction *F = BB->getParent();
6569 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6570 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6571 MI->getOpcode() == PPC::SELECT_I4 ||
6572 MI->getOpcode() == PPC::SELECT_I8)) {
6573 SmallVector<MachineOperand, 2> Cond;
6574 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6575 MI->getOpcode() == PPC::SELECT_CC_I8)
6576 Cond.push_back(MI->getOperand(4));
6578 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6579 Cond.push_back(MI->getOperand(1));
6581 DebugLoc dl = MI->getDebugLoc();
6582 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6583 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6584 Cond, MI->getOperand(2).getReg(),
6585 MI->getOperand(3).getReg());
6586 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6587 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6588 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6589 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6590 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6591 MI->getOpcode() == PPC::SELECT_I4 ||
6592 MI->getOpcode() == PPC::SELECT_I8 ||
6593 MI->getOpcode() == PPC::SELECT_F4 ||
6594 MI->getOpcode() == PPC::SELECT_F8 ||
6595 MI->getOpcode() == PPC::SELECT_VRRC) {
6596 // The incoming instruction knows the destination vreg to set, the
6597 // condition code register to branch on, the true/false values to
6598 // select between, and a branch opcode to use.
6603 // cmpTY ccX, r1, r2
6605 // fallthrough --> copy0MBB
6606 MachineBasicBlock *thisMBB = BB;
6607 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6608 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6609 DebugLoc dl = MI->getDebugLoc();
6610 F->insert(It, copy0MBB);
6611 F->insert(It, sinkMBB);
6613 // Transfer the remainder of BB and its successor edges to sinkMBB.
6614 sinkMBB->splice(sinkMBB->begin(), BB,
6615 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6616 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6618 // Next, add the true and fallthrough blocks as its successors.
6619 BB->addSuccessor(copy0MBB);
6620 BB->addSuccessor(sinkMBB);
6622 if (MI->getOpcode() == PPC::SELECT_I4 ||
6623 MI->getOpcode() == PPC::SELECT_I8 ||
6624 MI->getOpcode() == PPC::SELECT_F4 ||
6625 MI->getOpcode() == PPC::SELECT_F8 ||
6626 MI->getOpcode() == PPC::SELECT_VRRC) {
6627 BuildMI(BB, dl, TII->get(PPC::BC))
6628 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6630 unsigned SelectPred = MI->getOperand(4).getImm();
6631 BuildMI(BB, dl, TII->get(PPC::BCC))
6632 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6636 // %FalseValue = ...
6637 // # fallthrough to sinkMBB
6640 // Update machine-CFG edges
6641 BB->addSuccessor(sinkMBB);
6644 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6647 BuildMI(*BB, BB->begin(), dl,
6648 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6649 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6650 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6652 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6653 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6654 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6655 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6656 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6657 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6658 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6659 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6661 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6662 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6663 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6664 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6665 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6666 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6667 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6668 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6670 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6671 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6672 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6673 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6674 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6675 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6676 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6677 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6679 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6680 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6681 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6682 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6683 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6684 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6685 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6686 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6688 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6689 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6690 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6691 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6692 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6693 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6694 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6695 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6697 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6698 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6699 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6700 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6701 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6702 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6703 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6704 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6706 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6707 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6708 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6709 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6710 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6711 BB = EmitAtomicBinary(MI, BB, false, 0);
6712 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6713 BB = EmitAtomicBinary(MI, BB, true, 0);
6715 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6716 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6717 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6719 unsigned dest = MI->getOperand(0).getReg();
6720 unsigned ptrA = MI->getOperand(1).getReg();
6721 unsigned ptrB = MI->getOperand(2).getReg();
6722 unsigned oldval = MI->getOperand(3).getReg();
6723 unsigned newval = MI->getOperand(4).getReg();
6724 DebugLoc dl = MI->getDebugLoc();
6726 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6727 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6728 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6729 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6730 F->insert(It, loop1MBB);
6731 F->insert(It, loop2MBB);
6732 F->insert(It, midMBB);
6733 F->insert(It, exitMBB);
6734 exitMBB->splice(exitMBB->begin(), BB,
6735 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6736 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6740 // fallthrough --> loopMBB
6741 BB->addSuccessor(loop1MBB);
6744 // l[wd]arx dest, ptr
6745 // cmp[wd] dest, oldval
6748 // st[wd]cx. newval, ptr
6752 // st[wd]cx. dest, ptr
6755 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6756 .addReg(ptrA).addReg(ptrB);
6757 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6758 .addReg(oldval).addReg(dest);
6759 BuildMI(BB, dl, TII->get(PPC::BCC))
6760 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6761 BB->addSuccessor(loop2MBB);
6762 BB->addSuccessor(midMBB);
6765 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6766 .addReg(newval).addReg(ptrA).addReg(ptrB);
6767 BuildMI(BB, dl, TII->get(PPC::BCC))
6768 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6769 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6770 BB->addSuccessor(loop1MBB);
6771 BB->addSuccessor(exitMBB);
6774 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6775 .addReg(dest).addReg(ptrA).addReg(ptrB);
6776 BB->addSuccessor(exitMBB);
6781 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6782 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6783 // We must use 64-bit registers for addresses when targeting 64-bit,
6784 // since we're actually doing arithmetic on them. Other registers
6786 bool is64bit = PPCSubTarget.isPPC64();
6787 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6789 unsigned dest = MI->getOperand(0).getReg();
6790 unsigned ptrA = MI->getOperand(1).getReg();
6791 unsigned ptrB = MI->getOperand(2).getReg();
6792 unsigned oldval = MI->getOperand(3).getReg();
6793 unsigned newval = MI->getOperand(4).getReg();
6794 DebugLoc dl = MI->getDebugLoc();
6796 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6797 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6798 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6799 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6800 F->insert(It, loop1MBB);
6801 F->insert(It, loop2MBB);
6802 F->insert(It, midMBB);
6803 F->insert(It, exitMBB);
6804 exitMBB->splice(exitMBB->begin(), BB,
6805 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6806 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6808 MachineRegisterInfo &RegInfo = F->getRegInfo();
6809 const TargetRegisterClass *RC =
6810 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6811 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6812 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6813 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6814 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6815 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6816 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6817 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6818 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6819 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6820 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6821 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6822 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6823 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6824 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6826 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6827 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6830 // fallthrough --> loopMBB
6831 BB->addSuccessor(loop1MBB);
6833 // The 4-byte load must be aligned, while a char or short may be
6834 // anywhere in the word. Hence all this nasty bookkeeping code.
6835 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6836 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6837 // xori shift, shift1, 24 [16]
6838 // rlwinm ptr, ptr1, 0, 0, 29
6839 // slw newval2, newval, shift
6840 // slw oldval2, oldval,shift
6841 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6842 // slw mask, mask2, shift
6843 // and newval3, newval2, mask
6844 // and oldval3, oldval2, mask
6846 // lwarx tmpDest, ptr
6847 // and tmp, tmpDest, mask
6848 // cmpw tmp, oldval3
6851 // andc tmp2, tmpDest, mask
6852 // or tmp4, tmp2, newval3
6857 // stwcx. tmpDest, ptr
6859 // srw dest, tmpDest, shift
6860 if (ptrA != ZeroReg) {
6861 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6862 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6863 .addReg(ptrA).addReg(ptrB);
6867 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6868 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6869 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6870 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6872 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6873 .addReg(Ptr1Reg).addImm(0).addImm(61);
6875 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6876 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6877 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6878 .addReg(newval).addReg(ShiftReg);
6879 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6880 .addReg(oldval).addReg(ShiftReg);
6882 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6884 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6885 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6886 .addReg(Mask3Reg).addImm(65535);
6888 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6889 .addReg(Mask2Reg).addReg(ShiftReg);
6890 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6891 .addReg(NewVal2Reg).addReg(MaskReg);
6892 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6893 .addReg(OldVal2Reg).addReg(MaskReg);
6896 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6897 .addReg(ZeroReg).addReg(PtrReg);
6898 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6899 .addReg(TmpDestReg).addReg(MaskReg);
6900 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6901 .addReg(TmpReg).addReg(OldVal3Reg);
6902 BuildMI(BB, dl, TII->get(PPC::BCC))
6903 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6904 BB->addSuccessor(loop2MBB);
6905 BB->addSuccessor(midMBB);
6908 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6909 .addReg(TmpDestReg).addReg(MaskReg);
6910 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6911 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6912 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6913 .addReg(ZeroReg).addReg(PtrReg);
6914 BuildMI(BB, dl, TII->get(PPC::BCC))
6915 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6916 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6917 BB->addSuccessor(loop1MBB);
6918 BB->addSuccessor(exitMBB);
6921 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6922 .addReg(ZeroReg).addReg(PtrReg);
6923 BB->addSuccessor(exitMBB);
6928 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6930 } else if (MI->getOpcode() == PPC::FADDrtz) {
6931 // This pseudo performs an FADD with rounding mode temporarily forced
6932 // to round-to-zero. We emit this via custom inserter since the FPSCR
6933 // is not modeled at the SelectionDAG level.
6934 unsigned Dest = MI->getOperand(0).getReg();
6935 unsigned Src1 = MI->getOperand(1).getReg();
6936 unsigned Src2 = MI->getOperand(2).getReg();
6937 DebugLoc dl = MI->getDebugLoc();
6939 MachineRegisterInfo &RegInfo = F->getRegInfo();
6940 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6942 // Save FPSCR value.
6943 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6945 // Set rounding mode to round-to-zero.
6946 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6947 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6949 // Perform addition.
6950 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6952 // Restore FPSCR value.
6953 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6954 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6955 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
6956 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6957 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
6958 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6959 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
6960 PPC::ANDIo8 : PPC::ANDIo;
6961 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6962 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
6964 MachineRegisterInfo &RegInfo = F->getRegInfo();
6965 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
6966 &PPC::GPRCRegClass :
6967 &PPC::G8RCRegClass);
6969 DebugLoc dl = MI->getDebugLoc();
6970 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
6971 .addReg(MI->getOperand(1).getReg()).addImm(1);
6972 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
6973 MI->getOperand(0).getReg())
6974 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
6976 llvm_unreachable("Unexpected instr type to insert");
6979 MI->eraseFromParent(); // The pseudo instruction is gone now.
6983 //===----------------------------------------------------------------------===//
6984 // Target Optimization Hooks
6985 //===----------------------------------------------------------------------===//
6987 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6988 DAGCombinerInfo &DCI) const {
6989 if (DCI.isAfterLegalizeVectorOps())
6992 EVT VT = Op.getValueType();
6994 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6995 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6996 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
6997 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
6999 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7000 // For the reciprocal, we need to find the zero of the function:
7001 // F(X) = A X - 1 [which has a zero at X = 1/A]
7003 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7004 // does not require additional intermediate precision]
7006 // Convergence is quadratic, so we essentially double the number of digits
7007 // correct after every iteration. The minimum architected relative
7008 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7009 // 23 digits and double has 52 digits.
7010 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7011 if (VT.getScalarType() == MVT::f64)
7014 SelectionDAG &DAG = DCI.DAG;
7018 DAG.getConstantFP(1.0, VT.getScalarType());
7019 if (VT.isVector()) {
7020 assert(VT.getVectorNumElements() == 4 &&
7021 "Unknown vector type");
7022 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7023 FPOne, FPOne, FPOne, FPOne);
7026 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7027 DCI.AddToWorklist(Est.getNode());
7029 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7030 for (int i = 0; i < Iterations; ++i) {
7031 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7032 DCI.AddToWorklist(NewEst.getNode());
7034 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7035 DCI.AddToWorklist(NewEst.getNode());
7037 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7038 DCI.AddToWorklist(NewEst.getNode());
7040 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7041 DCI.AddToWorklist(Est.getNode());
7050 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7051 DAGCombinerInfo &DCI) const {
7052 if (DCI.isAfterLegalizeVectorOps())
7055 EVT VT = Op.getValueType();
7057 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
7058 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
7059 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7060 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7062 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7063 // For the reciprocal sqrt, we need to find the zero of the function:
7064 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7066 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7067 // As a result, we precompute A/2 prior to the iteration loop.
7069 // Convergence is quadratic, so we essentially double the number of digits
7070 // correct after every iteration. The minimum architected relative
7071 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7072 // 23 digits and double has 52 digits.
7073 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7074 if (VT.getScalarType() == MVT::f64)
7077 SelectionDAG &DAG = DCI.DAG;
7080 SDValue FPThreeHalves =
7081 DAG.getConstantFP(1.5, VT.getScalarType());
7082 if (VT.isVector()) {
7083 assert(VT.getVectorNumElements() == 4 &&
7084 "Unknown vector type");
7085 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7086 FPThreeHalves, FPThreeHalves,
7087 FPThreeHalves, FPThreeHalves);
7090 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7091 DCI.AddToWorklist(Est.getNode());
7093 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7094 // this entire sequence requires only one FP constant.
7095 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7096 DCI.AddToWorklist(HalfArg.getNode());
7098 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7099 DCI.AddToWorklist(HalfArg.getNode());
7101 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7102 for (int i = 0; i < Iterations; ++i) {
7103 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7104 DCI.AddToWorklist(NewEst.getNode());
7106 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7107 DCI.AddToWorklist(NewEst.getNode());
7109 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7110 DCI.AddToWorklist(NewEst.getNode());
7112 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7113 DCI.AddToWorklist(Est.getNode());
7122 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7123 // not enforce equality of the chain operands.
7124 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7125 unsigned Bytes, int Dist,
7126 SelectionDAG &DAG) {
7127 EVT VT = LS->getMemoryVT();
7128 if (VT.getSizeInBits() / 8 != Bytes)
7131 SDValue Loc = LS->getBasePtr();
7132 SDValue BaseLoc = Base->getBasePtr();
7133 if (Loc.getOpcode() == ISD::FrameIndex) {
7134 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7136 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7137 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7138 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7139 int FS = MFI->getObjectSize(FI);
7140 int BFS = MFI->getObjectSize(BFI);
7141 if (FS != BFS || FS != (int)Bytes) return false;
7142 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7146 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7147 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7150 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7151 const GlobalValue *GV1 = NULL;
7152 const GlobalValue *GV2 = NULL;
7153 int64_t Offset1 = 0;
7154 int64_t Offset2 = 0;
7155 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7156 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7157 if (isGA1 && isGA2 && GV1 == GV2)
7158 return Offset1 == (Offset2 + Dist*Bytes);
7162 // Return true is there is a nearyby consecutive load to the one provided
7163 // (regardless of alignment). We search up and down the chain, looking though
7164 // token factors and other loads (but nothing else). As a result, a true
7165 // results indicates that it is safe to create a new consecutive load adjacent
7166 // to the load provided.
7167 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7168 SDValue Chain = LD->getChain();
7169 EVT VT = LD->getMemoryVT();
7171 SmallSet<SDNode *, 16> LoadRoots;
7172 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7173 SmallSet<SDNode *, 16> Visited;
7175 // First, search up the chain, branching to follow all token-factor operands.
7176 // If we find a consecutive load, then we're done, otherwise, record all
7177 // nodes just above the top-level loads and token factors.
7178 while (!Queue.empty()) {
7179 SDNode *ChainNext = Queue.pop_back_val();
7180 if (!Visited.insert(ChainNext))
7183 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7184 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7187 if (!Visited.count(ChainLD->getChain().getNode()))
7188 Queue.push_back(ChainLD->getChain().getNode());
7189 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7190 for (SDNode::op_iterator O = ChainNext->op_begin(),
7191 OE = ChainNext->op_end(); O != OE; ++O)
7192 if (!Visited.count(O->getNode()))
7193 Queue.push_back(O->getNode());
7195 LoadRoots.insert(ChainNext);
7198 // Second, search down the chain, starting from the top-level nodes recorded
7199 // in the first phase. These top-level nodes are the nodes just above all
7200 // loads and token factors. Starting with their uses, recursively look though
7201 // all loads (just the chain uses) and token factors to find a consecutive
7206 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7207 IE = LoadRoots.end(); I != IE; ++I) {
7208 Queue.push_back(*I);
7210 while (!Queue.empty()) {
7211 SDNode *LoadRoot = Queue.pop_back_val();
7212 if (!Visited.insert(LoadRoot))
7215 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7216 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7219 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7220 UE = LoadRoot->use_end(); UI != UE; ++UI)
7221 if (((isa<LoadSDNode>(*UI) &&
7222 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7223 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7224 Queue.push_back(*UI);
7231 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7232 DAGCombinerInfo &DCI) const {
7233 SelectionDAG &DAG = DCI.DAG;
7236 assert(PPCSubTarget.useCRBits() &&
7237 "Expecting to be tracking CR bits");
7238 // If we're tracking CR bits, we need to be careful that we don't have:
7239 // trunc(binary-ops(zext(x), zext(y)))
7241 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7242 // such that we're unnecessarily moving things into GPRs when it would be
7243 // better to keep them in CR bits.
7245 // Note that trunc here can be an actual i1 trunc, or can be the effective
7246 // truncation that comes from a setcc or select_cc.
7247 if (N->getOpcode() == ISD::TRUNCATE &&
7248 N->getValueType(0) != MVT::i1)
7251 if (N->getOperand(0).getValueType() != MVT::i32 &&
7252 N->getOperand(0).getValueType() != MVT::i64)
7255 if (N->getOpcode() == ISD::SETCC ||
7256 N->getOpcode() == ISD::SELECT_CC) {
7257 // If we're looking at a comparison, then we need to make sure that the
7258 // high bits (all except for the first) don't matter the result.
7260 cast<CondCodeSDNode>(N->getOperand(
7261 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7262 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7264 if (ISD::isSignedIntSetCC(CC)) {
7265 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7266 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7268 } else if (ISD::isUnsignedIntSetCC(CC)) {
7269 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7270 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7271 !DAG.MaskedValueIsZero(N->getOperand(1),
7272 APInt::getHighBitsSet(OpBits, OpBits-1)))
7275 // This is neither a signed nor an unsigned comparison, just make sure
7276 // that the high bits are equal.
7277 APInt Op1Zero, Op1One;
7278 APInt Op2Zero, Op2One;
7279 DAG.ComputeMaskedBits(N->getOperand(0), Op1Zero, Op1One);
7280 DAG.ComputeMaskedBits(N->getOperand(1), Op2Zero, Op2One);
7282 // We don't really care about what is known about the first bit (if
7283 // anything), so clear it in all masks prior to comparing them.
7284 Op1Zero.clearBit(0); Op1One.clearBit(0);
7285 Op2Zero.clearBit(0); Op2One.clearBit(0);
7287 if (Op1Zero != Op2Zero || Op1One != Op2One)
7292 // We now know that the higher-order bits are irrelevant, we just need to
7293 // make sure that all of the intermediate operations are bit operations, and
7294 // all inputs are extensions.
7295 if (N->getOperand(0).getOpcode() != ISD::AND &&
7296 N->getOperand(0).getOpcode() != ISD::OR &&
7297 N->getOperand(0).getOpcode() != ISD::XOR &&
7298 N->getOperand(0).getOpcode() != ISD::SELECT &&
7299 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7300 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7301 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7302 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7303 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7306 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7307 N->getOperand(1).getOpcode() != ISD::AND &&
7308 N->getOperand(1).getOpcode() != ISD::OR &&
7309 N->getOperand(1).getOpcode() != ISD::XOR &&
7310 N->getOperand(1).getOpcode() != ISD::SELECT &&
7311 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7312 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7313 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7314 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7315 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7318 SmallVector<SDValue, 4> Inputs;
7319 SmallVector<SDValue, 8> BinOps, PromOps;
7320 SmallPtrSet<SDNode *, 16> Visited;
7322 for (unsigned i = 0; i < 2; ++i) {
7323 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7324 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7325 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7326 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7327 isa<ConstantSDNode>(N->getOperand(i)))
7328 Inputs.push_back(N->getOperand(i));
7330 BinOps.push_back(N->getOperand(i));
7332 if (N->getOpcode() == ISD::TRUNCATE)
7336 // Visit all inputs, collect all binary operations (and, or, xor and
7337 // select) that are all fed by extensions.
7338 while (!BinOps.empty()) {
7339 SDValue BinOp = BinOps.back();
7342 if (!Visited.insert(BinOp.getNode()))
7345 PromOps.push_back(BinOp);
7347 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7348 // The condition of the select is not promoted.
7349 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7351 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7354 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7355 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7356 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7357 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7358 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7359 Inputs.push_back(BinOp.getOperand(i));
7360 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7361 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7362 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7363 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7364 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7365 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7366 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7367 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7368 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7369 BinOps.push_back(BinOp.getOperand(i));
7371 // We have an input that is not an extension or another binary
7372 // operation; we'll abort this transformation.
7378 // Make sure that this is a self-contained cluster of operations (which
7379 // is not quite the same thing as saying that everything has only one
7381 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7382 if (isa<ConstantSDNode>(Inputs[i]))
7385 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7386 UE = Inputs[i].getNode()->use_end();
7389 if (User != N && !Visited.count(User))
7392 // Make sure that we're not going to promote the non-output-value
7393 // operand(s) or SELECT or SELECT_CC.
7394 // FIXME: Although we could sometimes handle this, and it does occur in
7395 // practice that one of the condition inputs to the select is also one of
7396 // the outputs, we currently can't deal with this.
7397 if (User->getOpcode() == ISD::SELECT) {
7398 if (User->getOperand(0) == Inputs[i])
7400 } else if (User->getOpcode() == ISD::SELECT_CC) {
7401 if (User->getOperand(0) == Inputs[i] ||
7402 User->getOperand(1) == Inputs[i])
7408 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7409 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7410 UE = PromOps[i].getNode()->use_end();
7413 if (User != N && !Visited.count(User))
7416 // Make sure that we're not going to promote the non-output-value
7417 // operand(s) or SELECT or SELECT_CC.
7418 // FIXME: Although we could sometimes handle this, and it does occur in
7419 // practice that one of the condition inputs to the select is also one of
7420 // the outputs, we currently can't deal with this.
7421 if (User->getOpcode() == ISD::SELECT) {
7422 if (User->getOperand(0) == PromOps[i])
7424 } else if (User->getOpcode() == ISD::SELECT_CC) {
7425 if (User->getOperand(0) == PromOps[i] ||
7426 User->getOperand(1) == PromOps[i])
7432 // Replace all inputs with the extension operand.
7433 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7434 // Constants may have users outside the cluster of to-be-promoted nodes,
7435 // and so we need to replace those as we do the promotions.
7436 if (isa<ConstantSDNode>(Inputs[i]))
7439 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7442 // Replace all operations (these are all the same, but have a different
7443 // (i1) return type). DAG.getNode will validate that the types of
7444 // a binary operator match, so go through the list in reverse so that
7445 // we've likely promoted both operands first. Any intermediate truncations or
7446 // extensions disappear.
7447 while (!PromOps.empty()) {
7448 SDValue PromOp = PromOps.back();
7451 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7452 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7453 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7454 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7455 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7456 PromOp.getOperand(0).getValueType() != MVT::i1) {
7457 // The operand is not yet ready (see comment below).
7458 PromOps.insert(PromOps.begin(), PromOp);
7462 SDValue RepValue = PromOp.getOperand(0);
7463 if (isa<ConstantSDNode>(RepValue))
7464 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7466 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7471 switch (PromOp.getOpcode()) {
7472 default: C = 0; break;
7473 case ISD::SELECT: C = 1; break;
7474 case ISD::SELECT_CC: C = 2; break;
7477 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7478 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7479 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7480 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7481 // The to-be-promoted operands of this node have not yet been
7482 // promoted (this should be rare because we're going through the
7483 // list backward, but if one of the operands has several users in
7484 // this cluster of to-be-promoted nodes, it is possible).
7485 PromOps.insert(PromOps.begin(), PromOp);
7489 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7490 PromOp.getNode()->op_end());
7492 // If there are any constant inputs, make sure they're replaced now.
7493 for (unsigned i = 0; i < 2; ++i)
7494 if (isa<ConstantSDNode>(Ops[C+i]))
7495 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7497 DAG.ReplaceAllUsesOfValueWith(PromOp,
7498 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1,
7499 Ops.data(), Ops.size()));
7502 // Now we're left with the initial truncation itself.
7503 if (N->getOpcode() == ISD::TRUNCATE)
7504 return N->getOperand(0);
7506 // Otherwise, this is a comparison. The operands to be compared have just
7507 // changed type (to i1), but everything else is the same.
7508 return SDValue(N, 0);
7511 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7512 DAGCombinerInfo &DCI) const {
7513 SelectionDAG &DAG = DCI.DAG;
7516 // If we're tracking CR bits, we need to be careful that we don't have:
7517 // zext(binary-ops(trunc(x), trunc(y)))
7519 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7520 // such that we're unnecessarily moving things into CR bits that can more
7521 // efficiently stay in GPRs. Note that if we're not certain that the high
7522 // bits are set as required by the final extension, we still may need to do
7523 // some masking to get the proper behavior.
7525 // This same functionality is important on PPC64 when dealing with
7526 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7527 // the return values of functions. Because it is so similar, it is handled
7530 if (N->getValueType(0) != MVT::i32 &&
7531 N->getValueType(0) != MVT::i64)
7534 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7535 PPCSubTarget.useCRBits()) ||
7536 (N->getOperand(0).getValueType() == MVT::i32 &&
7537 PPCSubTarget.isPPC64())))
7540 if (N->getOperand(0).getOpcode() != ISD::AND &&
7541 N->getOperand(0).getOpcode() != ISD::OR &&
7542 N->getOperand(0).getOpcode() != ISD::XOR &&
7543 N->getOperand(0).getOpcode() != ISD::SELECT &&
7544 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7547 SmallVector<SDValue, 4> Inputs;
7548 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7549 SmallPtrSet<SDNode *, 16> Visited;
7551 // Visit all inputs, collect all binary operations (and, or, xor and
7552 // select) that are all fed by truncations.
7553 while (!BinOps.empty()) {
7554 SDValue BinOp = BinOps.back();
7557 if (!Visited.insert(BinOp.getNode()))
7560 PromOps.push_back(BinOp);
7562 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7563 // The condition of the select is not promoted.
7564 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7566 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7569 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7570 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7571 Inputs.push_back(BinOp.getOperand(i));
7572 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7573 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7574 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7575 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7576 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7577 BinOps.push_back(BinOp.getOperand(i));
7579 // We have an input that is not a truncation or another binary
7580 // operation; we'll abort this transformation.
7586 // Make sure that this is a self-contained cluster of operations (which
7587 // is not quite the same thing as saying that everything has only one
7589 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7590 if (isa<ConstantSDNode>(Inputs[i]))
7593 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7594 UE = Inputs[i].getNode()->use_end();
7597 if (User != N && !Visited.count(User))
7600 // Make sure that we're not going to promote the non-output-value
7601 // operand(s) or SELECT or SELECT_CC.
7602 // FIXME: Although we could sometimes handle this, and it does occur in
7603 // practice that one of the condition inputs to the select is also one of
7604 // the outputs, we currently can't deal with this.
7605 if (User->getOpcode() == ISD::SELECT) {
7606 if (User->getOperand(0) == Inputs[i])
7608 } else if (User->getOpcode() == ISD::SELECT_CC) {
7609 if (User->getOperand(0) == Inputs[i] ||
7610 User->getOperand(1) == Inputs[i])
7616 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7617 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7618 UE = PromOps[i].getNode()->use_end();
7621 if (User != N && !Visited.count(User))
7624 // Make sure that we're not going to promote the non-output-value
7625 // operand(s) or SELECT or SELECT_CC.
7626 // FIXME: Although we could sometimes handle this, and it does occur in
7627 // practice that one of the condition inputs to the select is also one of
7628 // the outputs, we currently can't deal with this.
7629 if (User->getOpcode() == ISD::SELECT) {
7630 if (User->getOperand(0) == PromOps[i])
7632 } else if (User->getOpcode() == ISD::SELECT_CC) {
7633 if (User->getOperand(0) == PromOps[i] ||
7634 User->getOperand(1) == PromOps[i])
7640 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7641 bool ReallyNeedsExt = false;
7642 if (N->getOpcode() != ISD::ANY_EXTEND) {
7643 // If all of the inputs are not already sign/zero extended, then
7644 // we'll still need to do that at the end.
7645 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7646 if (isa<ConstantSDNode>(Inputs[i]))
7650 Inputs[i].getOperand(0).getValueSizeInBits();
7651 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7653 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7654 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7655 APInt::getHighBitsSet(OpBits,
7656 OpBits-PromBits))) ||
7657 (N->getOpcode() == ISD::SIGN_EXTEND &&
7658 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7659 (OpBits-(PromBits-1)))) {
7660 ReallyNeedsExt = true;
7666 // Replace all inputs, either with the truncation operand, or a
7667 // truncation or extension to the final output type.
7668 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7669 // Constant inputs need to be replaced with the to-be-promoted nodes that
7670 // use them because they might have users outside of the cluster of
7672 if (isa<ConstantSDNode>(Inputs[i]))
7675 SDValue InSrc = Inputs[i].getOperand(0);
7676 if (Inputs[i].getValueType() == N->getValueType(0))
7677 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7678 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7679 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7680 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7681 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7682 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7683 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7685 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7686 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7689 // Replace all operations (these are all the same, but have a different
7690 // (promoted) return type). DAG.getNode will validate that the types of
7691 // a binary operator match, so go through the list in reverse so that
7692 // we've likely promoted both operands first.
7693 while (!PromOps.empty()) {
7694 SDValue PromOp = PromOps.back();
7698 switch (PromOp.getOpcode()) {
7699 default: C = 0; break;
7700 case ISD::SELECT: C = 1; break;
7701 case ISD::SELECT_CC: C = 2; break;
7704 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7705 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7706 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7707 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7708 // The to-be-promoted operands of this node have not yet been
7709 // promoted (this should be rare because we're going through the
7710 // list backward, but if one of the operands has several users in
7711 // this cluster of to-be-promoted nodes, it is possible).
7712 PromOps.insert(PromOps.begin(), PromOp);
7716 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7717 PromOp.getNode()->op_end());
7719 // If this node has constant inputs, then they'll need to be promoted here.
7720 for (unsigned i = 0; i < 2; ++i) {
7721 if (!isa<ConstantSDNode>(Ops[C+i]))
7723 if (Ops[C+i].getValueType() == N->getValueType(0))
7726 if (N->getOpcode() == ISD::SIGN_EXTEND)
7727 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7728 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7729 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7731 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7734 DAG.ReplaceAllUsesOfValueWith(PromOp,
7735 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0),
7736 Ops.data(), Ops.size()));
7739 // Now we're left with the initial extension itself.
7740 if (!ReallyNeedsExt)
7741 return N->getOperand(0);
7743 // To zero extend, just mask off everything except for the first bit (in the
7745 if (N->getOpcode() == ISD::ZERO_EXTEND)
7746 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7747 DAG.getConstant(APInt::getLowBitsSet(
7748 N->getValueSizeInBits(0), PromBits),
7749 N->getValueType(0)));
7751 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7752 "Invalid extension type");
7753 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7755 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7756 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7757 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7758 N->getOperand(0), ShiftCst), ShiftCst);
7761 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7762 DAGCombinerInfo &DCI) const {
7763 const TargetMachine &TM = getTargetMachine();
7764 SelectionDAG &DAG = DCI.DAG;
7766 switch (N->getOpcode()) {
7769 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7770 if (C->isNullValue()) // 0 << V -> 0.
7771 return N->getOperand(0);
7775 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7776 if (C->isNullValue()) // 0 >>u V -> 0.
7777 return N->getOperand(0);
7781 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7782 if (C->isNullValue() || // 0 >>s V -> 0.
7783 C->isAllOnesValue()) // -1 >>s V -> -1.
7784 return N->getOperand(0);
7787 case ISD::SIGN_EXTEND:
7788 case ISD::ZERO_EXTEND:
7789 case ISD::ANY_EXTEND:
7790 return DAGCombineExtBoolTrunc(N, DCI);
7793 case ISD::SELECT_CC:
7794 return DAGCombineTruncBoolExt(N, DCI);
7796 assert(TM.Options.UnsafeFPMath &&
7797 "Reciprocal estimates require UnsafeFPMath");
7799 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7801 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7802 if (RV.getNode() != 0) {
7803 DCI.AddToWorklist(RV.getNode());
7804 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7805 N->getOperand(0), RV);
7807 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7808 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7810 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7812 if (RV.getNode() != 0) {
7813 DCI.AddToWorklist(RV.getNode());
7814 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7815 N->getValueType(0), RV);
7816 DCI.AddToWorklist(RV.getNode());
7817 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7818 N->getOperand(0), RV);
7820 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7821 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7823 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7825 if (RV.getNode() != 0) {
7826 DCI.AddToWorklist(RV.getNode());
7827 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7828 N->getValueType(0), RV,
7829 N->getOperand(1).getOperand(1));
7830 DCI.AddToWorklist(RV.getNode());
7831 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7832 N->getOperand(0), RV);
7836 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7837 if (RV.getNode() != 0) {
7838 DCI.AddToWorklist(RV.getNode());
7839 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7840 N->getOperand(0), RV);
7846 assert(TM.Options.UnsafeFPMath &&
7847 "Reciprocal estimates require UnsafeFPMath");
7849 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7851 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7852 if (RV.getNode() != 0) {
7853 DCI.AddToWorklist(RV.getNode());
7854 RV = DAGCombineFastRecip(RV, DCI);
7855 if (RV.getNode() != 0) {
7856 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7857 // this case and force the answer to 0.
7859 EVT VT = RV.getValueType();
7861 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7862 if (VT.isVector()) {
7863 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7864 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7868 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7869 N->getOperand(0), Zero, ISD::SETEQ);
7870 DCI.AddToWorklist(ZeroCmp.getNode());
7871 DCI.AddToWorklist(RV.getNode());
7873 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7881 case ISD::SINT_TO_FP:
7882 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7883 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7884 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7885 // We allow the src/dst to be either f32/f64, but the intermediate
7886 // type must be i64.
7887 if (N->getOperand(0).getValueType() == MVT::i64 &&
7888 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7889 SDValue Val = N->getOperand(0).getOperand(0);
7890 if (Val.getValueType() == MVT::f32) {
7891 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7892 DCI.AddToWorklist(Val.getNode());
7895 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7896 DCI.AddToWorklist(Val.getNode());
7897 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7898 DCI.AddToWorklist(Val.getNode());
7899 if (N->getValueType(0) == MVT::f32) {
7900 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7901 DAG.getIntPtrConstant(0));
7902 DCI.AddToWorklist(Val.getNode());
7905 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7906 // If the intermediate type is i32, we can avoid the load/store here
7913 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7914 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7915 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7916 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7917 N->getOperand(1).getValueType() == MVT::i32 &&
7918 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7919 SDValue Val = N->getOperand(1).getOperand(0);
7920 if (Val.getValueType() == MVT::f32) {
7921 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7922 DCI.AddToWorklist(Val.getNode());
7924 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7925 DCI.AddToWorklist(Val.getNode());
7928 N->getOperand(0), Val, N->getOperand(2),
7929 DAG.getValueType(N->getOperand(1).getValueType())
7932 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7933 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7934 cast<StoreSDNode>(N)->getMemoryVT(),
7935 cast<StoreSDNode>(N)->getMemOperand());
7936 DCI.AddToWorklist(Val.getNode());
7940 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7941 if (cast<StoreSDNode>(N)->isUnindexed() &&
7942 N->getOperand(1).getOpcode() == ISD::BSWAP &&
7943 N->getOperand(1).getNode()->hasOneUse() &&
7944 (N->getOperand(1).getValueType() == MVT::i32 ||
7945 N->getOperand(1).getValueType() == MVT::i16 ||
7946 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7947 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7948 N->getOperand(1).getValueType() == MVT::i64))) {
7949 SDValue BSwapOp = N->getOperand(1).getOperand(0);
7950 // Do an any-extend to 32-bits if this is a half-word input.
7951 if (BSwapOp.getValueType() == MVT::i16)
7952 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7955 N->getOperand(0), BSwapOp, N->getOperand(2),
7956 DAG.getValueType(N->getOperand(1).getValueType())
7959 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7960 Ops, array_lengthof(Ops),
7961 cast<StoreSDNode>(N)->getMemoryVT(),
7962 cast<StoreSDNode>(N)->getMemOperand());
7966 LoadSDNode *LD = cast<LoadSDNode>(N);
7967 EVT VT = LD->getValueType(0);
7968 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
7969 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
7970 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
7971 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
7972 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
7973 VT == MVT::v4i32 || VT == MVT::v4f32) &&
7974 LD->getAlignment() < ABIAlignment) {
7975 // This is a type-legal unaligned Altivec load.
7976 SDValue Chain = LD->getChain();
7977 SDValue Ptr = LD->getBasePtr();
7979 // This implements the loading of unaligned vectors as described in
7980 // the venerable Apple Velocity Engine overview. Specifically:
7981 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
7982 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
7984 // The general idea is to expand a sequence of one or more unaligned
7985 // loads into a alignment-based permutation-control instruction (lvsl),
7986 // a series of regular vector loads (which always truncate their
7987 // input address to an aligned address), and a series of permutations.
7988 // The results of these permutations are the requested loaded values.
7989 // The trick is that the last "extra" load is not taken from the address
7990 // you might suspect (sizeof(vector) bytes after the last requested
7991 // load), but rather sizeof(vector) - 1 bytes after the last
7992 // requested vector. The point of this is to avoid a page fault if the
7993 // base address happened to be aligned. This works because if the base
7994 // address is aligned, then adding less than a full vector length will
7995 // cause the last vector in the sequence to be (re)loaded. Otherwise,
7996 // the next vector will be fetched as you might suspect was necessary.
7998 // We might be able to reuse the permutation generation from
7999 // a different base address offset from this one by an aligned amount.
8000 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8001 // optimization later.
8002 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
8003 DAG, dl, MVT::v16i8);
8005 // Refine the alignment of the original load (a "new" load created here
8006 // which was identical to the first except for the alignment would be
8007 // merged with the existing node regardless).
8008 MachineFunction &MF = DAG.getMachineFunction();
8009 MachineMemOperand *MMO =
8010 MF.getMachineMemOperand(LD->getPointerInfo(),
8011 LD->getMemOperand()->getFlags(),
8012 LD->getMemoryVT().getStoreSize(),
8014 LD->refineAlignment(MMO);
8015 SDValue BaseLoad = SDValue(LD, 0);
8017 // Note that the value of IncOffset (which is provided to the next
8018 // load's pointer info offset value, and thus used to calculate the
8019 // alignment), and the value of IncValue (which is actually used to
8020 // increment the pointer value) are different! This is because we
8021 // require the next load to appear to be aligned, even though it
8022 // is actually offset from the base pointer by a lesser amount.
8023 int IncOffset = VT.getSizeInBits() / 8;
8024 int IncValue = IncOffset;
8026 // Walk (both up and down) the chain looking for another load at the real
8027 // (aligned) offset (the alignment of the other load does not matter in
8028 // this case). If found, then do not use the offset reduction trick, as
8029 // that will prevent the loads from being later combined (as they would
8030 // otherwise be duplicates).
8031 if (!findConsecutiveLoad(LD, DAG))
8034 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8035 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8038 DAG.getLoad(VT, dl, Chain, Ptr,
8039 LD->getPointerInfo().getWithOffset(IncOffset),
8040 LD->isVolatile(), LD->isNonTemporal(),
8041 LD->isInvariant(), ABIAlignment);
8043 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8044 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8046 if (BaseLoad.getValueType() != MVT::v4i32)
8047 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8049 if (ExtraLoad.getValueType() != MVT::v4i32)
8050 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8052 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8053 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8055 if (VT != MVT::v4i32)
8056 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8058 // Now we need to be really careful about how we update the users of the
8059 // original load. We cannot just call DCI.CombineTo (or
8060 // DAG.ReplaceAllUsesWith for that matter), because the load still has
8061 // uses created here (the permutation for example) that need to stay.
8062 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8064 SDUse &Use = UI.getUse();
8066 // Note: BaseLoad is checked here because it might not be N, but a
8068 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8069 User == TF.getNode() || Use.getResNo() > 1) {
8074 SDValue To = Use.getResNo() ? TF : Perm;
8077 SmallVector<SDValue, 8> Ops;
8078 for (SDNode::op_iterator O = User->op_begin(),
8079 OE = User->op_end(); O != OE; ++O) {
8086 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
8089 return SDValue(N, 0);
8093 case ISD::INTRINSIC_WO_CHAIN:
8094 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8095 Intrinsic::ppc_altivec_lvsl &&
8096 N->getOperand(1)->getOpcode() == ISD::ADD) {
8097 SDValue Add = N->getOperand(1);
8099 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8100 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8101 Add.getValueType().getScalarType().getSizeInBits()))) {
8102 SDNode *BasePtr = Add->getOperand(0).getNode();
8103 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8104 UE = BasePtr->use_end(); UI != UE; ++UI) {
8105 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8106 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8107 Intrinsic::ppc_altivec_lvsl) {
8108 // We've found another LVSL, and this address if an aligned
8109 // multiple of that one. The results will be the same, so use the
8110 // one we've just found instead.
8112 return SDValue(*UI, 0);
8120 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8121 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8122 N->getOperand(0).hasOneUse() &&
8123 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8124 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8125 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8126 N->getValueType(0) == MVT::i64))) {
8127 SDValue Load = N->getOperand(0);
8128 LoadSDNode *LD = cast<LoadSDNode>(Load);
8129 // Create the byte-swapping load.
8131 LD->getChain(), // Chain
8132 LD->getBasePtr(), // Ptr
8133 DAG.getValueType(N->getValueType(0)) // VT
8136 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8137 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8138 MVT::i64 : MVT::i32, MVT::Other),
8139 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
8141 // If this is an i16 load, insert the truncate.
8142 SDValue ResVal = BSLoad;
8143 if (N->getValueType(0) == MVT::i16)
8144 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8146 // First, combine the bswap away. This makes the value produced by the
8148 DCI.CombineTo(N, ResVal);
8150 // Next, combine the load away, we give it a bogus result value but a real
8151 // chain result. The result value is dead because the bswap is dead.
8152 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8154 // Return N so it doesn't get rechecked!
8155 return SDValue(N, 0);
8159 case PPCISD::VCMP: {
8160 // If a VCMPo node already exists with exactly the same operands as this
8161 // node, use its result instead of this node (VCMPo computes both a CR6 and
8162 // a normal output).
8164 if (!N->getOperand(0).hasOneUse() &&
8165 !N->getOperand(1).hasOneUse() &&
8166 !N->getOperand(2).hasOneUse()) {
8168 // Scan all of the users of the LHS, looking for VCMPo's that match.
8169 SDNode *VCMPoNode = 0;
8171 SDNode *LHSN = N->getOperand(0).getNode();
8172 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8174 if (UI->getOpcode() == PPCISD::VCMPo &&
8175 UI->getOperand(1) == N->getOperand(1) &&
8176 UI->getOperand(2) == N->getOperand(2) &&
8177 UI->getOperand(0) == N->getOperand(0)) {
8182 // If there is no VCMPo node, or if the flag value has a single use, don't
8184 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8187 // Look at the (necessarily single) use of the flag value. If it has a
8188 // chain, this transformation is more complex. Note that multiple things
8189 // could use the value result, which we should ignore.
8190 SDNode *FlagUser = 0;
8191 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8192 FlagUser == 0; ++UI) {
8193 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8195 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8196 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8203 // If the user is a MFOCRF instruction, we know this is safe.
8204 // Otherwise we give up for right now.
8205 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8206 return SDValue(VCMPoNode, 0);
8211 SDValue Cond = N->getOperand(1);
8212 SDValue Target = N->getOperand(2);
8214 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8215 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8216 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8218 // We now need to make the intrinsic dead (it cannot be instruction
8220 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8221 assert(Cond.getNode()->hasOneUse() &&
8222 "Counter decrement has more than one use");
8224 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8225 N->getOperand(0), Target);
8230 // If this is a branch on an altivec predicate comparison, lower this so
8231 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8232 // lowering is done pre-legalize, because the legalizer lowers the predicate
8233 // compare down to code that is difficult to reassemble.
8234 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8235 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8237 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8238 // value. If so, pass-through the AND to get to the intrinsic.
8239 if (LHS.getOpcode() == ISD::AND &&
8240 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8241 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8242 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8243 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8244 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8246 LHS = LHS.getOperand(0);
8248 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8249 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8250 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8251 isa<ConstantSDNode>(RHS)) {
8252 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8253 "Counter decrement comparison is not EQ or NE");
8255 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8256 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8257 (CC == ISD::SETNE && !Val);
8259 // We now need to make the intrinsic dead (it cannot be instruction
8261 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8262 assert(LHS.getNode()->hasOneUse() &&
8263 "Counter decrement has more than one use");
8265 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8266 N->getOperand(0), N->getOperand(4));
8272 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8273 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8274 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8275 assert(isDot && "Can't compare against a vector result!");
8277 // If this is a comparison against something other than 0/1, then we know
8278 // that the condition is never/always true.
8279 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8280 if (Val != 0 && Val != 1) {
8281 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8282 return N->getOperand(0);
8283 // Always !=, turn it into an unconditional branch.
8284 return DAG.getNode(ISD::BR, dl, MVT::Other,
8285 N->getOperand(0), N->getOperand(4));
8288 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8290 // Create the PPCISD altivec 'dot' comparison node.
8292 LHS.getOperand(2), // LHS of compare
8293 LHS.getOperand(3), // RHS of compare
8294 DAG.getConstant(CompareOpc, MVT::i32)
8296 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8297 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
8299 // Unpack the result based on how the target uses it.
8300 PPC::Predicate CompOpc;
8301 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8302 default: // Can't happen, don't crash on invalid number though.
8303 case 0: // Branch on the value of the EQ bit of CR6.
8304 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8306 case 1: // Branch on the inverted value of the EQ bit of CR6.
8307 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8309 case 2: // Branch on the value of the LT bit of CR6.
8310 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8312 case 3: // Branch on the inverted value of the LT bit of CR6.
8313 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8317 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8318 DAG.getConstant(CompOpc, MVT::i32),
8319 DAG.getRegister(PPC::CR6, MVT::i32),
8320 N->getOperand(4), CompNode.getValue(1));
8329 //===----------------------------------------------------------------------===//
8330 // Inline Assembly Support
8331 //===----------------------------------------------------------------------===//
8333 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8336 const SelectionDAG &DAG,
8337 unsigned Depth) const {
8338 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8339 switch (Op.getOpcode()) {
8341 case PPCISD::LBRX: {
8342 // lhbrx is known to have the top bits cleared out.
8343 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8344 KnownZero = 0xFFFF0000;
8347 case ISD::INTRINSIC_WO_CHAIN: {
8348 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8350 case Intrinsic::ppc_altivec_vcmpbfp_p:
8351 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8352 case Intrinsic::ppc_altivec_vcmpequb_p:
8353 case Intrinsic::ppc_altivec_vcmpequh_p:
8354 case Intrinsic::ppc_altivec_vcmpequw_p:
8355 case Intrinsic::ppc_altivec_vcmpgefp_p:
8356 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8357 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8358 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8359 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8360 case Intrinsic::ppc_altivec_vcmpgtub_p:
8361 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8362 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8363 KnownZero = ~1U; // All bits but the low one are known to be zero.
8371 /// getConstraintType - Given a constraint, return the type of
8372 /// constraint it is for this target.
8373 PPCTargetLowering::ConstraintType
8374 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8375 if (Constraint.size() == 1) {
8376 switch (Constraint[0]) {
8383 return C_RegisterClass;
8385 // FIXME: While Z does indicate a memory constraint, it specifically
8386 // indicates an r+r address (used in conjunction with the 'y' modifier
8387 // in the replacement string). Currently, we're forcing the base
8388 // register to be r0 in the asm printer (which is interpreted as zero)
8389 // and forming the complete address in the second register. This is
8393 } else if (Constraint == "wc") { // individual CR bits.
8394 return C_RegisterClass;
8395 } else if (Constraint == "wa" || Constraint == "wd" ||
8396 Constraint == "wf" || Constraint == "ws") {
8397 return C_RegisterClass; // VSX registers.
8399 return TargetLowering::getConstraintType(Constraint);
8402 /// Examine constraint type and operand type and determine a weight value.
8403 /// This object must already have been set up with the operand type
8404 /// and the current alternative constraint selected.
8405 TargetLowering::ConstraintWeight
8406 PPCTargetLowering::getSingleConstraintMatchWeight(
8407 AsmOperandInfo &info, const char *constraint) const {
8408 ConstraintWeight weight = CW_Invalid;
8409 Value *CallOperandVal = info.CallOperandVal;
8410 // If we don't have a value, we can't do a match,
8411 // but allow it at the lowest weight.
8412 if (CallOperandVal == NULL)
8414 Type *type = CallOperandVal->getType();
8416 // Look at the constraint type.
8417 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8418 return CW_Register; // an individual CR bit.
8419 else if ((StringRef(constraint) == "wa" ||
8420 StringRef(constraint) == "wd" ||
8421 StringRef(constraint) == "wf") &&
8424 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8427 switch (*constraint) {
8429 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8432 if (type->isIntegerTy())
8433 weight = CW_Register;
8436 if (type->isFloatTy())
8437 weight = CW_Register;
8440 if (type->isDoubleTy())
8441 weight = CW_Register;
8444 if (type->isVectorTy())
8445 weight = CW_Register;
8448 weight = CW_Register;
8457 std::pair<unsigned, const TargetRegisterClass*>
8458 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8460 if (Constraint.size() == 1) {
8461 // GCC RS6000 Constraint Letters
8462 switch (Constraint[0]) {
8464 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8465 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8466 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8468 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8469 return std::make_pair(0U, &PPC::G8RCRegClass);
8470 return std::make_pair(0U, &PPC::GPRCRegClass);
8472 if (VT == MVT::f32 || VT == MVT::i32)
8473 return std::make_pair(0U, &PPC::F4RCRegClass);
8474 if (VT == MVT::f64 || VT == MVT::i64)
8475 return std::make_pair(0U, &PPC::F8RCRegClass);
8478 return std::make_pair(0U, &PPC::VRRCRegClass);
8480 return std::make_pair(0U, &PPC::CRRCRegClass);
8482 } else if (Constraint == "wc") { // an individual CR bit.
8483 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8484 } else if (Constraint == "wa" || Constraint == "wd" ||
8485 Constraint == "wf" || Constraint == "ws") {
8486 return std::make_pair(0U, &PPC::VSRCRegClass);
8489 std::pair<unsigned, const TargetRegisterClass*> R =
8490 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8492 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8493 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8494 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8496 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8497 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8498 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8499 PPC::GPRCRegClass.contains(R.first)) {
8500 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8501 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8502 PPC::sub_32, &PPC::G8RCRegClass),
8503 &PPC::G8RCRegClass);
8510 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8511 /// vector. If it is invalid, don't add anything to Ops.
8512 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8513 std::string &Constraint,
8514 std::vector<SDValue>&Ops,
8515 SelectionDAG &DAG) const {
8516 SDValue Result(0,0);
8518 // Only support length 1 constraints.
8519 if (Constraint.length() > 1) return;
8521 char Letter = Constraint[0];
8532 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8533 if (!CST) return; // Must be an immediate to match.
8534 unsigned Value = CST->getZExtValue();
8536 default: llvm_unreachable("Unknown constraint letter!");
8537 case 'I': // "I" is a signed 16-bit constant.
8538 if ((short)Value == (int)Value)
8539 Result = DAG.getTargetConstant(Value, Op.getValueType());
8541 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8542 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8543 if ((short)Value == 0)
8544 Result = DAG.getTargetConstant(Value, Op.getValueType());
8546 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8547 if ((Value >> 16) == 0)
8548 Result = DAG.getTargetConstant(Value, Op.getValueType());
8550 case 'M': // "M" is a constant that is greater than 31.
8552 Result = DAG.getTargetConstant(Value, Op.getValueType());
8554 case 'N': // "N" is a positive constant that is an exact power of two.
8555 if ((int)Value > 0 && isPowerOf2_32(Value))
8556 Result = DAG.getTargetConstant(Value, Op.getValueType());
8558 case 'O': // "O" is the constant zero.
8560 Result = DAG.getTargetConstant(Value, Op.getValueType());
8562 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8563 if ((short)-Value == (int)-Value)
8564 Result = DAG.getTargetConstant(Value, Op.getValueType());
8571 if (Result.getNode()) {
8572 Ops.push_back(Result);
8576 // Handle standard constraint letters.
8577 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8580 // isLegalAddressingMode - Return true if the addressing mode represented
8581 // by AM is legal for this target, for a load/store of the specified type.
8582 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8584 // FIXME: PPC does not allow r+i addressing modes for vectors!
8586 // PPC allows a sign-extended 16-bit immediate field.
8587 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8590 // No global is ever allowed as a base.
8594 // PPC only support r+r,
8596 case 0: // "r+i" or just "i", depending on HasBaseReg.
8599 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8601 // Otherwise we have r+r or r+i.
8604 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8606 // Allow 2*r as r+r.
8609 // No other scales are supported.
8616 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8617 SelectionDAG &DAG) const {
8618 MachineFunction &MF = DAG.getMachineFunction();
8619 MachineFrameInfo *MFI = MF.getFrameInfo();
8620 MFI->setReturnAddressIsTaken(true);
8622 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8626 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8628 // Make sure the function does not optimize away the store of the RA to
8630 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8631 FuncInfo->setLRStoreRequired();
8632 bool isPPC64 = PPCSubTarget.isPPC64();
8633 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8636 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8639 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8640 isPPC64? MVT::i64 : MVT::i32);
8641 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8642 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8644 MachinePointerInfo(), false, false, false, 0);
8647 // Just load the return address off the stack.
8648 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8649 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8650 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8653 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8654 SelectionDAG &DAG) const {
8656 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8658 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8659 bool isPPC64 = PtrVT == MVT::i64;
8661 MachineFunction &MF = DAG.getMachineFunction();
8662 MachineFrameInfo *MFI = MF.getFrameInfo();
8663 MFI->setFrameAddressIsTaken(true);
8665 // Naked functions never have a frame pointer, and so we use r1. For all
8666 // other functions, this decision must be delayed until during PEI.
8668 if (MF.getFunction()->getAttributes().hasAttribute(
8669 AttributeSet::FunctionIndex, Attribute::Naked))
8670 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8672 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8674 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8677 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8678 FrameAddr, MachinePointerInfo(), false, false,
8684 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8685 // The PowerPC target isn't yet aware of offsets.
8689 /// getOptimalMemOpType - Returns the target specific optimal type for load
8690 /// and store operations as a result of memset, memcpy, and memmove
8691 /// lowering. If DstAlign is zero that means it's safe to destination
8692 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8693 /// means there isn't a need to check it against alignment requirement,
8694 /// probably because the source does not need to be loaded. If 'IsMemset' is
8695 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8696 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8697 /// source is constant so it does not need to be loaded.
8698 /// It returns EVT::Other if the type should be determined using generic
8699 /// target-independent logic.
8700 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8701 unsigned DstAlign, unsigned SrcAlign,
8702 bool IsMemset, bool ZeroMemset,
8704 MachineFunction &MF) const {
8705 if (this->PPCSubTarget.isPPC64()) {
8712 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8715 if (DisablePPCUnaligned)
8718 // PowerPC supports unaligned memory access for simple non-vector types.
8719 // Although accessing unaligned addresses is not as efficient as accessing
8720 // aligned addresses, it is generally more efficient than manual expansion,
8721 // and generally only traps for software emulation when crossing page
8727 if (VT.getSimpleVT().isVector()) {
8728 if (PPCSubTarget.hasVSX()) {
8729 if (VT != MVT::v2f64 && VT != MVT::v2i64)
8736 if (VT == MVT::ppcf128)
8745 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8746 VT = VT.getScalarType();
8751 switch (VT.getSimpleVT().SimpleTy) {
8762 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8763 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8764 return TargetLowering::getSchedulingPreference(N);
8769 // Create a fast isel object.
8771 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8772 const TargetLibraryInfo *LibInfo) const {
8773 return PPC::createFastISel(FuncInfo, LibInfo);