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) {
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);
537 if (Subtarget->has64BitSupport()) {
538 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
539 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
542 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
543 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
544 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
545 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
547 setBooleanContents(ZeroOrOneBooleanContent);
548 // Altivec instructions set fields to all zeros or all ones.
549 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
552 setStackPointerRegisterToSaveRestore(PPC::X1);
553 setExceptionPointerRegister(PPC::X3);
554 setExceptionSelectorRegister(PPC::X4);
556 setStackPointerRegisterToSaveRestore(PPC::R1);
557 setExceptionPointerRegister(PPC::R3);
558 setExceptionSelectorRegister(PPC::R4);
561 // We have target-specific dag combine patterns for the following nodes:
562 setTargetDAGCombine(ISD::SINT_TO_FP);
563 setTargetDAGCombine(ISD::LOAD);
564 setTargetDAGCombine(ISD::STORE);
565 setTargetDAGCombine(ISD::BR_CC);
566 if (Subtarget->useCRBits())
567 setTargetDAGCombine(ISD::BRCOND);
568 setTargetDAGCombine(ISD::BSWAP);
569 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
571 setTargetDAGCombine(ISD::SIGN_EXTEND);
572 setTargetDAGCombine(ISD::ZERO_EXTEND);
573 setTargetDAGCombine(ISD::ANY_EXTEND);
575 if (Subtarget->useCRBits()) {
576 setTargetDAGCombine(ISD::TRUNCATE);
577 setTargetDAGCombine(ISD::SETCC);
578 setTargetDAGCombine(ISD::SELECT_CC);
581 // Use reciprocal estimates.
582 if (TM.Options.UnsafeFPMath) {
583 setTargetDAGCombine(ISD::FDIV);
584 setTargetDAGCombine(ISD::FSQRT);
587 // Darwin long double math library functions have $LDBL128 appended.
588 if (Subtarget->isDarwin()) {
589 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
590 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
591 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
592 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
593 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
594 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
595 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
596 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
597 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
598 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
601 // With 32 condition bits, we don't need to sink (and duplicate) compares
602 // aggressively in CodeGenPrep.
603 if (Subtarget->useCRBits())
604 setHasMultipleConditionRegisters();
606 setMinFunctionAlignment(2);
607 if (PPCSubTarget.isDarwin())
608 setPrefFunctionAlignment(4);
610 if (isPPC64 && Subtarget->isJITCodeModel())
611 // Temporary workaround for the inability of PPC64 JIT to handle jump
613 setSupportJumpTables(false);
615 setInsertFencesForAtomic(true);
617 if (Subtarget->enableMachineScheduler())
618 setSchedulingPreference(Sched::Source);
620 setSchedulingPreference(Sched::Hybrid);
622 computeRegisterProperties();
624 // The Freescale cores does better with aggressive inlining of memcpy and
625 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
626 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
627 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
628 MaxStoresPerMemset = 32;
629 MaxStoresPerMemsetOptSize = 16;
630 MaxStoresPerMemcpy = 32;
631 MaxStoresPerMemcpyOptSize = 8;
632 MaxStoresPerMemmove = 32;
633 MaxStoresPerMemmoveOptSize = 8;
635 setPrefFunctionAlignment(4);
639 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
640 /// the desired ByVal argument alignment.
641 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
642 unsigned MaxMaxAlign) {
643 if (MaxAlign == MaxMaxAlign)
645 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
646 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
648 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
650 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
651 unsigned EltAlign = 0;
652 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
653 if (EltAlign > MaxAlign)
655 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
656 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
657 unsigned EltAlign = 0;
658 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
659 if (EltAlign > MaxAlign)
661 if (MaxAlign == MaxMaxAlign)
667 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
668 /// function arguments in the caller parameter area.
669 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
670 // Darwin passes everything on 4 byte boundary.
671 if (PPCSubTarget.isDarwin())
674 // 16byte and wider vectors are passed on 16byte boundary.
675 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
676 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
677 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
678 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
682 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
685 case PPCISD::FSEL: return "PPCISD::FSEL";
686 case PPCISD::FCFID: return "PPCISD::FCFID";
687 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
688 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
689 case PPCISD::FRE: return "PPCISD::FRE";
690 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
691 case PPCISD::STFIWX: return "PPCISD::STFIWX";
692 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
693 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
694 case PPCISD::VPERM: return "PPCISD::VPERM";
695 case PPCISD::Hi: return "PPCISD::Hi";
696 case PPCISD::Lo: return "PPCISD::Lo";
697 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
698 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
699 case PPCISD::LOAD: return "PPCISD::LOAD";
700 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
701 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
702 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
703 case PPCISD::SRL: return "PPCISD::SRL";
704 case PPCISD::SRA: return "PPCISD::SRA";
705 case PPCISD::SHL: return "PPCISD::SHL";
706 case PPCISD::CALL: return "PPCISD::CALL";
707 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
708 case PPCISD::MTCTR: return "PPCISD::MTCTR";
709 case PPCISD::BCTRL: return "PPCISD::BCTRL";
710 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
711 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
712 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
713 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
714 case PPCISD::VCMP: return "PPCISD::VCMP";
715 case PPCISD::VCMPo: return "PPCISD::VCMPo";
716 case PPCISD::LBRX: return "PPCISD::LBRX";
717 case PPCISD::STBRX: return "PPCISD::STBRX";
718 case PPCISD::LARX: return "PPCISD::LARX";
719 case PPCISD::STCX: return "PPCISD::STCX";
720 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
721 case PPCISD::BDNZ: return "PPCISD::BDNZ";
722 case PPCISD::BDZ: return "PPCISD::BDZ";
723 case PPCISD::MFFS: return "PPCISD::MFFS";
724 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
725 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
726 case PPCISD::CR6SET: return "PPCISD::CR6SET";
727 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
728 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
729 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
730 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
731 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
732 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
733 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
734 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
735 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
736 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
737 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
738 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
739 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
740 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
741 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
742 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
743 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
744 case PPCISD::SC: return "PPCISD::SC";
748 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
750 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
751 return VT.changeVectorElementTypeToInteger();
754 //===----------------------------------------------------------------------===//
755 // Node matching predicates, for use by the tblgen matching code.
756 //===----------------------------------------------------------------------===//
758 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
759 static bool isFloatingPointZero(SDValue Op) {
760 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
761 return CFP->getValueAPF().isZero();
762 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
763 // Maybe this has already been legalized into the constant pool?
764 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
765 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
766 return CFP->getValueAPF().isZero();
771 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
772 /// true if Op is undef or if it matches the specified value.
773 static bool isConstantOrUndef(int Op, int Val) {
774 return Op < 0 || Op == Val;
777 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
778 /// VPKUHUM instruction.
779 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
781 for (unsigned i = 0; i != 16; ++i)
782 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
785 for (unsigned i = 0; i != 8; ++i)
786 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
787 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
793 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
794 /// VPKUWUM instruction.
795 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
797 for (unsigned i = 0; i != 16; i += 2)
798 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
799 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
802 for (unsigned i = 0; i != 8; i += 2)
803 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
804 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
805 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
806 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
812 /// isVMerge - Common function, used to match vmrg* shuffles.
814 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
815 unsigned LHSStart, unsigned RHSStart) {
816 assert(N->getValueType(0) == MVT::v16i8 &&
817 "PPC only supports shuffles by bytes!");
818 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
819 "Unsupported merge size!");
821 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
822 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
823 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
824 LHSStart+j+i*UnitSize) ||
825 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
826 RHSStart+j+i*UnitSize))
832 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
833 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
834 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
837 return isVMerge(N, UnitSize, 8, 24);
838 return isVMerge(N, UnitSize, 8, 8);
841 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
842 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
843 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
846 return isVMerge(N, UnitSize, 0, 16);
847 return isVMerge(N, UnitSize, 0, 0);
851 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
852 /// amount, otherwise return -1.
853 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
854 assert(N->getValueType(0) == MVT::v16i8 &&
855 "PPC only supports shuffles by bytes!");
857 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
859 // Find the first non-undef value in the shuffle mask.
861 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
864 if (i == 16) return -1; // all undef.
866 // Otherwise, check to see if the rest of the elements are consecutively
867 // numbered from this value.
868 unsigned ShiftAmt = SVOp->getMaskElt(i);
869 if (ShiftAmt < i) return -1;
873 // Check the rest of the elements to see if they are consecutive.
874 for (++i; i != 16; ++i)
875 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
878 // Check the rest of the elements to see if they are consecutive.
879 for (++i; i != 16; ++i)
880 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
886 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
887 /// specifies a splat of a single element that is suitable for input to
888 /// VSPLTB/VSPLTH/VSPLTW.
889 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
890 assert(N->getValueType(0) == MVT::v16i8 &&
891 (EltSize == 1 || EltSize == 2 || EltSize == 4));
893 // This is a splat operation if each element of the permute is the same, and
894 // if the value doesn't reference the second vector.
895 unsigned ElementBase = N->getMaskElt(0);
897 // FIXME: Handle UNDEF elements too!
898 if (ElementBase >= 16)
901 // Check that the indices are consecutive, in the case of a multi-byte element
902 // splatted with a v16i8 mask.
903 for (unsigned i = 1; i != EltSize; ++i)
904 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
907 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
908 if (N->getMaskElt(i) < 0) continue;
909 for (unsigned j = 0; j != EltSize; ++j)
910 if (N->getMaskElt(i+j) != N->getMaskElt(j))
916 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
918 bool PPC::isAllNegativeZeroVector(SDNode *N) {
919 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
921 APInt APVal, APUndef;
925 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
926 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
927 return CFP->getValueAPF().isNegZero();
932 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
933 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
934 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
935 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
936 assert(isSplatShuffleMask(SVOp, EltSize));
937 return SVOp->getMaskElt(0) / EltSize;
940 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
941 /// by using a vspltis[bhw] instruction of the specified element size, return
942 /// the constant being splatted. The ByteSize field indicates the number of
943 /// bytes of each element [124] -> [bhw].
944 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
947 // If ByteSize of the splat is bigger than the element size of the
948 // build_vector, then we have a case where we are checking for a splat where
949 // multiple elements of the buildvector are folded together into a single
950 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
951 unsigned EltSize = 16/N->getNumOperands();
952 if (EltSize < ByteSize) {
953 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
954 SDValue UniquedVals[4];
955 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
957 // See if all of the elements in the buildvector agree across.
958 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
959 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
960 // If the element isn't a constant, bail fully out.
961 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
964 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
965 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
966 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
967 return SDValue(); // no match.
970 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
971 // either constant or undef values that are identical for each chunk. See
972 // if these chunks can form into a larger vspltis*.
974 // Check to see if all of the leading entries are either 0 or -1. If
975 // neither, then this won't fit into the immediate field.
976 bool LeadingZero = true;
977 bool LeadingOnes = true;
978 for (unsigned i = 0; i != Multiple-1; ++i) {
979 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
981 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
982 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
984 // Finally, check the least significant entry.
986 if (UniquedVals[Multiple-1].getNode() == 0)
987 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
988 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
990 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
993 if (UniquedVals[Multiple-1].getNode() == 0)
994 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
995 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
996 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
997 return DAG.getTargetConstant(Val, MVT::i32);
1003 // Check to see if this buildvec has a single non-undef value in its elements.
1004 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1005 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1006 if (OpVal.getNode() == 0)
1007 OpVal = N->getOperand(i);
1008 else if (OpVal != N->getOperand(i))
1012 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
1014 unsigned ValSizeInBytes = EltSize;
1016 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1017 Value = CN->getZExtValue();
1018 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1019 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1020 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1023 // If the splat value is larger than the element value, then we can never do
1024 // this splat. The only case that we could fit the replicated bits into our
1025 // immediate field for would be zero, and we prefer to use vxor for it.
1026 if (ValSizeInBytes < ByteSize) return SDValue();
1028 // If the element value is larger than the splat value, cut it in half and
1029 // check to see if the two halves are equal. Continue doing this until we
1030 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1031 while (ValSizeInBytes > ByteSize) {
1032 ValSizeInBytes >>= 1;
1034 // If the top half equals the bottom half, we're still ok.
1035 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1036 (Value & ((1 << (8*ValSizeInBytes))-1)))
1040 // Properly sign extend the value.
1041 int MaskVal = SignExtend32(Value, ByteSize * 8);
1043 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1044 if (MaskVal == 0) return SDValue();
1046 // Finally, if this value fits in a 5 bit sext field, return it
1047 if (SignExtend32<5>(MaskVal) == MaskVal)
1048 return DAG.getTargetConstant(MaskVal, MVT::i32);
1052 //===----------------------------------------------------------------------===//
1053 // Addressing Mode Selection
1054 //===----------------------------------------------------------------------===//
1056 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1057 /// or 64-bit immediate, and if the value can be accurately represented as a
1058 /// sign extension from a 16-bit value. If so, this returns true and the
1060 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1061 if (N->getOpcode() != ISD::Constant)
1064 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1065 if (N->getValueType(0) == MVT::i32)
1066 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1068 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1070 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1071 return isIntS16Immediate(Op.getNode(), Imm);
1075 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1076 /// can be represented as an indexed [r+r] operation. Returns false if it
1077 /// can be more efficiently represented with [r+imm].
1078 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1080 SelectionDAG &DAG) const {
1082 if (N.getOpcode() == ISD::ADD) {
1083 if (isIntS16Immediate(N.getOperand(1), imm))
1084 return false; // r+i
1085 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1086 return false; // r+i
1088 Base = N.getOperand(0);
1089 Index = N.getOperand(1);
1091 } else if (N.getOpcode() == ISD::OR) {
1092 if (isIntS16Immediate(N.getOperand(1), imm))
1093 return false; // r+i can fold it if we can.
1095 // If this is an or of disjoint bitfields, we can codegen this as an add
1096 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1098 APInt LHSKnownZero, LHSKnownOne;
1099 APInt RHSKnownZero, RHSKnownOne;
1100 DAG.ComputeMaskedBits(N.getOperand(0),
1101 LHSKnownZero, LHSKnownOne);
1103 if (LHSKnownZero.getBoolValue()) {
1104 DAG.ComputeMaskedBits(N.getOperand(1),
1105 RHSKnownZero, RHSKnownOne);
1106 // If all of the bits are known zero on the LHS or RHS, the add won't
1108 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1109 Base = N.getOperand(0);
1110 Index = N.getOperand(1);
1119 // If we happen to be doing an i64 load or store into a stack slot that has
1120 // less than a 4-byte alignment, then the frame-index elimination may need to
1121 // use an indexed load or store instruction (because the offset may not be a
1122 // multiple of 4). The extra register needed to hold the offset comes from the
1123 // register scavenger, and it is possible that the scavenger will need to use
1124 // an emergency spill slot. As a result, we need to make sure that a spill slot
1125 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1127 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1128 // FIXME: This does not handle the LWA case.
1132 // NOTE: We'll exclude negative FIs here, which come from argument
1133 // lowering, because there are no known test cases triggering this problem
1134 // using packed structures (or similar). We can remove this exclusion if
1135 // we find such a test case. The reason why this is so test-case driven is
1136 // because this entire 'fixup' is only to prevent crashes (from the
1137 // register scavenger) on not-really-valid inputs. For example, if we have:
1139 // %b = bitcast i1* %a to i64*
1140 // store i64* a, i64 b
1141 // then the store should really be marked as 'align 1', but is not. If it
1142 // were marked as 'align 1' then the indexed form would have been
1143 // instruction-selected initially, and the problem this 'fixup' is preventing
1144 // won't happen regardless.
1148 MachineFunction &MF = DAG.getMachineFunction();
1149 MachineFrameInfo *MFI = MF.getFrameInfo();
1151 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1155 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1156 FuncInfo->setHasNonRISpills();
1159 /// Returns true if the address N can be represented by a base register plus
1160 /// a signed 16-bit displacement [r+imm], and if it is not better
1161 /// represented as reg+reg. If Aligned is true, only accept displacements
1162 /// suitable for STD and friends, i.e. multiples of 4.
1163 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1166 bool Aligned) const {
1167 // FIXME dl should come from parent load or store, not from address
1169 // If this can be more profitably realized as r+r, fail.
1170 if (SelectAddressRegReg(N, Disp, Base, DAG))
1173 if (N.getOpcode() == ISD::ADD) {
1175 if (isIntS16Immediate(N.getOperand(1), imm) &&
1176 (!Aligned || (imm & 3) == 0)) {
1177 Disp = DAG.getTargetConstant(imm, N.getValueType());
1178 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1179 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1180 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1182 Base = N.getOperand(0);
1184 return true; // [r+i]
1185 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1186 // Match LOAD (ADD (X, Lo(G))).
1187 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1188 && "Cannot handle constant offsets yet!");
1189 Disp = N.getOperand(1).getOperand(0); // The global address.
1190 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1191 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1192 Disp.getOpcode() == ISD::TargetConstantPool ||
1193 Disp.getOpcode() == ISD::TargetJumpTable);
1194 Base = N.getOperand(0);
1195 return true; // [&g+r]
1197 } else if (N.getOpcode() == ISD::OR) {
1199 if (isIntS16Immediate(N.getOperand(1), imm) &&
1200 (!Aligned || (imm & 3) == 0)) {
1201 // If this is an or of disjoint bitfields, we can codegen this as an add
1202 // (for better address arithmetic) if the LHS and RHS of the OR are
1203 // provably disjoint.
1204 APInt LHSKnownZero, LHSKnownOne;
1205 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1207 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1208 // If all of the bits are known zero on the LHS or RHS, the add won't
1210 Base = N.getOperand(0);
1211 Disp = DAG.getTargetConstant(imm, N.getValueType());
1215 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1216 // Loading from a constant address.
1218 // If this address fits entirely in a 16-bit sext immediate field, codegen
1221 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1222 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1223 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1224 CN->getValueType(0));
1228 // Handle 32-bit sext immediates with LIS + addr mode.
1229 if ((CN->getValueType(0) == MVT::i32 ||
1230 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1231 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1232 int Addr = (int)CN->getZExtValue();
1234 // Otherwise, break this down into an LIS + disp.
1235 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1237 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1238 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1239 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1244 Disp = DAG.getTargetConstant(0, getPointerTy());
1245 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1246 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1247 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1250 return true; // [r+0]
1253 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1254 /// represented as an indexed [r+r] operation.
1255 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1257 SelectionDAG &DAG) const {
1258 // Check to see if we can easily represent this as an [r+r] address. This
1259 // will fail if it thinks that the address is more profitably represented as
1260 // reg+imm, e.g. where imm = 0.
1261 if (SelectAddressRegReg(N, Base, Index, DAG))
1264 // If the operand is an addition, always emit this as [r+r], since this is
1265 // better (for code size, and execution, as the memop does the add for free)
1266 // than emitting an explicit add.
1267 if (N.getOpcode() == ISD::ADD) {
1268 Base = N.getOperand(0);
1269 Index = N.getOperand(1);
1273 // Otherwise, do it the hard way, using R0 as the base register.
1274 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1280 /// getPreIndexedAddressParts - returns true by value, base pointer and
1281 /// offset pointer and addressing mode by reference if the node's address
1282 /// can be legally represented as pre-indexed load / store address.
1283 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1285 ISD::MemIndexedMode &AM,
1286 SelectionDAG &DAG) const {
1287 if (DisablePPCPreinc) return false;
1293 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1294 Ptr = LD->getBasePtr();
1295 VT = LD->getMemoryVT();
1296 Alignment = LD->getAlignment();
1297 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1298 Ptr = ST->getBasePtr();
1299 VT = ST->getMemoryVT();
1300 Alignment = ST->getAlignment();
1305 // PowerPC doesn't have preinc load/store instructions for vectors.
1309 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1311 // Common code will reject creating a pre-inc form if the base pointer
1312 // is a frame index, or if N is a store and the base pointer is either
1313 // the same as or a predecessor of the value being stored. Check for
1314 // those situations here, and try with swapped Base/Offset instead.
1317 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1320 SDValue Val = cast<StoreSDNode>(N)->getValue();
1321 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1326 std::swap(Base, Offset);
1332 // LDU/STU can only handle immediates that are a multiple of 4.
1333 if (VT != MVT::i64) {
1334 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1337 // LDU/STU need an address with at least 4-byte alignment.
1341 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1345 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1346 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1347 // sext i32 to i64 when addr mode is r+i.
1348 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1349 LD->getExtensionType() == ISD::SEXTLOAD &&
1350 isa<ConstantSDNode>(Offset))
1358 //===----------------------------------------------------------------------===//
1359 // LowerOperation implementation
1360 //===----------------------------------------------------------------------===//
1362 /// GetLabelAccessInfo - Return true if we should reference labels using a
1363 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1364 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1365 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1366 HiOpFlags = PPCII::MO_HA;
1367 LoOpFlags = PPCII::MO_LO;
1369 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1370 // non-darwin platform. We don't support PIC on other platforms yet.
1371 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1372 TM.getSubtarget<PPCSubtarget>().isDarwin();
1374 HiOpFlags |= PPCII::MO_PIC_FLAG;
1375 LoOpFlags |= PPCII::MO_PIC_FLAG;
1378 // If this is a reference to a global value that requires a non-lazy-ptr, make
1379 // sure that instruction lowering adds it.
1380 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1381 HiOpFlags |= PPCII::MO_NLP_FLAG;
1382 LoOpFlags |= PPCII::MO_NLP_FLAG;
1384 if (GV->hasHiddenVisibility()) {
1385 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1386 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1393 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1394 SelectionDAG &DAG) {
1395 EVT PtrVT = HiPart.getValueType();
1396 SDValue Zero = DAG.getConstant(0, PtrVT);
1399 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1400 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1402 // With PIC, the first instruction is actually "GR+hi(&G)".
1404 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1405 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1407 // Generate non-pic code that has direct accesses to the constant pool.
1408 // The address of the global is just (hi(&g)+lo(&g)).
1409 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1412 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1413 SelectionDAG &DAG) const {
1414 EVT PtrVT = Op.getValueType();
1415 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1416 const Constant *C = CP->getConstVal();
1418 // 64-bit SVR4 ABI code is always position-independent.
1419 // The actual address of the GlobalValue is stored in the TOC.
1420 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1421 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1422 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1423 DAG.getRegister(PPC::X2, MVT::i64));
1426 unsigned MOHiFlag, MOLoFlag;
1427 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1429 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1431 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1432 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1435 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1436 EVT PtrVT = Op.getValueType();
1437 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1439 // 64-bit SVR4 ABI code is always position-independent.
1440 // The actual address of the GlobalValue is stored in the TOC.
1441 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1442 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1443 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1444 DAG.getRegister(PPC::X2, MVT::i64));
1447 unsigned MOHiFlag, MOLoFlag;
1448 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1449 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1450 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1451 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1454 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1455 SelectionDAG &DAG) const {
1456 EVT PtrVT = Op.getValueType();
1458 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1460 unsigned MOHiFlag, MOLoFlag;
1461 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1462 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1463 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1464 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1467 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1468 SelectionDAG &DAG) const {
1470 // FIXME: TLS addresses currently use medium model code sequences,
1471 // which is the most useful form. Eventually support for small and
1472 // large models could be added if users need it, at the cost of
1473 // additional complexity.
1474 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1476 const GlobalValue *GV = GA->getGlobal();
1477 EVT PtrVT = getPointerTy();
1478 bool is64bit = PPCSubTarget.isPPC64();
1480 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1482 if (Model == TLSModel::LocalExec) {
1483 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1484 PPCII::MO_TPREL_HA);
1485 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1486 PPCII::MO_TPREL_LO);
1487 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1488 is64bit ? MVT::i64 : MVT::i32);
1489 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1490 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1493 if (Model == TLSModel::InitialExec) {
1494 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1495 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1499 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1500 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1501 PtrVT, GOTReg, TGA);
1503 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1504 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1505 PtrVT, TGA, GOTPtr);
1506 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1509 if (Model == TLSModel::GeneralDynamic) {
1510 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1511 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1512 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1514 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1517 // We need a chain node, and don't have one handy. The underlying
1518 // call has no side effects, so using the function entry node
1520 SDValue Chain = DAG.getEntryNode();
1521 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1522 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1523 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1524 PtrVT, ParmReg, TGA);
1525 // The return value from GET_TLS_ADDR really is in X3 already, but
1526 // some hacks are needed here to tie everything together. The extra
1527 // copies dissolve during subsequent transforms.
1528 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1529 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1532 if (Model == TLSModel::LocalDynamic) {
1533 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1534 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1535 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1537 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1540 // We need a chain node, and don't have one handy. The underlying
1541 // call has no side effects, so using the function entry node
1543 SDValue Chain = DAG.getEntryNode();
1544 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1545 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1546 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1547 PtrVT, ParmReg, TGA);
1548 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1549 // some hacks are needed here to tie everything together. The extra
1550 // copies dissolve during subsequent transforms.
1551 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1552 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1553 Chain, ParmReg, TGA);
1554 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1557 llvm_unreachable("Unknown TLS model!");
1560 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1561 SelectionDAG &DAG) const {
1562 EVT PtrVT = Op.getValueType();
1563 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1565 const GlobalValue *GV = GSDN->getGlobal();
1567 // 64-bit SVR4 ABI code is always position-independent.
1568 // The actual address of the GlobalValue is stored in the TOC.
1569 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1570 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1571 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1572 DAG.getRegister(PPC::X2, MVT::i64));
1575 unsigned MOHiFlag, MOLoFlag;
1576 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1579 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1581 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1583 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1585 // If the global reference is actually to a non-lazy-pointer, we have to do an
1586 // extra load to get the address of the global.
1587 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1588 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1589 false, false, false, 0);
1593 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1594 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1597 // If we're comparing for equality to zero, expose the fact that this is
1598 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1599 // fold the new nodes.
1600 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1601 if (C->isNullValue() && CC == ISD::SETEQ) {
1602 EVT VT = Op.getOperand(0).getValueType();
1603 SDValue Zext = Op.getOperand(0);
1604 if (VT.bitsLT(MVT::i32)) {
1606 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1608 unsigned Log2b = Log2_32(VT.getSizeInBits());
1609 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1610 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1611 DAG.getConstant(Log2b, MVT::i32));
1612 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1614 // Leave comparisons against 0 and -1 alone for now, since they're usually
1615 // optimized. FIXME: revisit this when we can custom lower all setcc
1617 if (C->isAllOnesValue() || C->isNullValue())
1621 // If we have an integer seteq/setne, turn it into a compare against zero
1622 // by xor'ing the rhs with the lhs, which is faster than setting a
1623 // condition register, reading it back out, and masking the correct bit. The
1624 // normal approach here uses sub to do this instead of xor. Using xor exposes
1625 // the result to other bit-twiddling opportunities.
1626 EVT LHSVT = Op.getOperand(0).getValueType();
1627 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1628 EVT VT = Op.getValueType();
1629 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1631 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1636 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1637 const PPCSubtarget &Subtarget) const {
1638 SDNode *Node = Op.getNode();
1639 EVT VT = Node->getValueType(0);
1640 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1641 SDValue InChain = Node->getOperand(0);
1642 SDValue VAListPtr = Node->getOperand(1);
1643 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1646 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1649 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1650 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1652 InChain = GprIndex.getValue(1);
1654 if (VT == MVT::i64) {
1655 // Check if GprIndex is even
1656 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1657 DAG.getConstant(1, MVT::i32));
1658 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1659 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1660 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1661 DAG.getConstant(1, MVT::i32));
1662 // Align GprIndex to be even if it isn't
1663 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1667 // fpr index is 1 byte after gpr
1668 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1669 DAG.getConstant(1, MVT::i32));
1672 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1673 FprPtr, MachinePointerInfo(SV), MVT::i8,
1675 InChain = FprIndex.getValue(1);
1677 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1678 DAG.getConstant(8, MVT::i32));
1680 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1681 DAG.getConstant(4, MVT::i32));
1684 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1685 MachinePointerInfo(), false, false,
1687 InChain = OverflowArea.getValue(1);
1689 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1690 MachinePointerInfo(), false, false,
1692 InChain = RegSaveArea.getValue(1);
1694 // select overflow_area if index > 8
1695 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1696 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1698 // adjustment constant gpr_index * 4/8
1699 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1700 VT.isInteger() ? GprIndex : FprIndex,
1701 DAG.getConstant(VT.isInteger() ? 4 : 8,
1704 // OurReg = RegSaveArea + RegConstant
1705 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1708 // Floating types are 32 bytes into RegSaveArea
1709 if (VT.isFloatingPoint())
1710 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1711 DAG.getConstant(32, MVT::i32));
1713 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1714 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1715 VT.isInteger() ? GprIndex : FprIndex,
1716 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1719 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1720 VT.isInteger() ? VAListPtr : FprPtr,
1721 MachinePointerInfo(SV),
1722 MVT::i8, false, false, 0);
1724 // determine if we should load from reg_save_area or overflow_area
1725 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1727 // increase overflow_area by 4/8 if gpr/fpr > 8
1728 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1729 DAG.getConstant(VT.isInteger() ? 4 : 8,
1732 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1735 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1737 MachinePointerInfo(),
1738 MVT::i32, false, false, 0);
1740 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1741 false, false, false, 0);
1744 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1745 const PPCSubtarget &Subtarget) const {
1746 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1748 // We have to copy the entire va_list struct:
1749 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1750 return DAG.getMemcpy(Op.getOperand(0), Op,
1751 Op.getOperand(1), Op.getOperand(2),
1752 DAG.getConstant(12, MVT::i32), 8, false, true,
1753 MachinePointerInfo(), MachinePointerInfo());
1756 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1757 SelectionDAG &DAG) const {
1758 return Op.getOperand(0);
1761 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1762 SelectionDAG &DAG) const {
1763 SDValue Chain = Op.getOperand(0);
1764 SDValue Trmp = Op.getOperand(1); // trampoline
1765 SDValue FPtr = Op.getOperand(2); // nested function
1766 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1769 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1770 bool isPPC64 = (PtrVT == MVT::i64);
1772 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1775 TargetLowering::ArgListTy Args;
1776 TargetLowering::ArgListEntry Entry;
1778 Entry.Ty = IntPtrTy;
1779 Entry.Node = Trmp; Args.push_back(Entry);
1781 // TrampSize == (isPPC64 ? 48 : 40);
1782 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1783 isPPC64 ? MVT::i64 : MVT::i32);
1784 Args.push_back(Entry);
1786 Entry.Node = FPtr; Args.push_back(Entry);
1787 Entry.Node = Nest; Args.push_back(Entry);
1789 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1790 TargetLowering::CallLoweringInfo CLI(Chain,
1791 Type::getVoidTy(*DAG.getContext()),
1792 false, false, false, false, 0,
1794 /*isTailCall=*/false,
1795 /*doesNotRet=*/false,
1796 /*isReturnValueUsed=*/true,
1797 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1799 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1801 return CallResult.second;
1804 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1805 const PPCSubtarget &Subtarget) const {
1806 MachineFunction &MF = DAG.getMachineFunction();
1807 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1811 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1812 // vastart just stores the address of the VarArgsFrameIndex slot into the
1813 // memory location argument.
1814 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1815 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1816 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1817 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1818 MachinePointerInfo(SV),
1822 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1823 // We suppose the given va_list is already allocated.
1826 // char gpr; /* index into the array of 8 GPRs
1827 // * stored in the register save area
1828 // * gpr=0 corresponds to r3,
1829 // * gpr=1 to r4, etc.
1831 // char fpr; /* index into the array of 8 FPRs
1832 // * stored in the register save area
1833 // * fpr=0 corresponds to f1,
1834 // * fpr=1 to f2, etc.
1836 // char *overflow_arg_area;
1837 // /* location on stack that holds
1838 // * the next overflow argument
1840 // char *reg_save_area;
1841 // /* where r3:r10 and f1:f8 (if saved)
1847 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1848 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1851 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1853 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1855 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1858 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1859 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1861 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1862 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1864 uint64_t FPROffset = 1;
1865 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1867 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1869 // Store first byte : number of int regs
1870 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1872 MachinePointerInfo(SV),
1873 MVT::i8, false, false, 0);
1874 uint64_t nextOffset = FPROffset;
1875 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1878 // Store second byte : number of float regs
1879 SDValue secondStore =
1880 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1881 MachinePointerInfo(SV, nextOffset), MVT::i8,
1883 nextOffset += StackOffset;
1884 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1886 // Store second word : arguments given on stack
1887 SDValue thirdStore =
1888 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1889 MachinePointerInfo(SV, nextOffset),
1891 nextOffset += FrameOffset;
1892 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1894 // Store third word : arguments given in registers
1895 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1896 MachinePointerInfo(SV, nextOffset),
1901 #include "PPCGenCallingConv.inc"
1903 // Function whose sole purpose is to kill compiler warnings
1904 // stemming from unused functions included from PPCGenCallingConv.inc.
1905 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
1906 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
1909 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1910 CCValAssign::LocInfo &LocInfo,
1911 ISD::ArgFlagsTy &ArgFlags,
1916 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1918 CCValAssign::LocInfo &LocInfo,
1919 ISD::ArgFlagsTy &ArgFlags,
1921 static const uint16_t ArgRegs[] = {
1922 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1923 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1925 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1927 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1929 // Skip one register if the first unallocated register has an even register
1930 // number and there are still argument registers available which have not been
1931 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1932 // need to skip a register if RegNum is odd.
1933 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1934 State.AllocateReg(ArgRegs[RegNum]);
1937 // Always return false here, as this function only makes sure that the first
1938 // unallocated register has an odd register number and does not actually
1939 // allocate a register for the current argument.
1943 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1945 CCValAssign::LocInfo &LocInfo,
1946 ISD::ArgFlagsTy &ArgFlags,
1948 static const uint16_t ArgRegs[] = {
1949 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1953 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1955 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1957 // If there is only one Floating-point register left we need to put both f64
1958 // values of a split ppc_fp128 value on the stack.
1959 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1960 State.AllocateReg(ArgRegs[RegNum]);
1963 // Always return false here, as this function only makes sure that the two f64
1964 // values a ppc_fp128 value is split into are both passed in registers or both
1965 // passed on the stack and does not actually allocate a register for the
1966 // current argument.
1970 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1972 static const uint16_t *GetFPR() {
1973 static const uint16_t FPR[] = {
1974 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1975 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1981 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1983 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1984 unsigned PtrByteSize) {
1985 unsigned ArgSize = ArgVT.getStoreSize();
1986 if (Flags.isByVal())
1987 ArgSize = Flags.getByValSize();
1988 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1994 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1995 CallingConv::ID CallConv, bool isVarArg,
1996 const SmallVectorImpl<ISD::InputArg>
1998 SDLoc dl, SelectionDAG &DAG,
1999 SmallVectorImpl<SDValue> &InVals)
2001 if (PPCSubTarget.isSVR4ABI()) {
2002 if (PPCSubTarget.isPPC64())
2003 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2006 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2009 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2015 PPCTargetLowering::LowerFormalArguments_32SVR4(
2017 CallingConv::ID CallConv, bool isVarArg,
2018 const SmallVectorImpl<ISD::InputArg>
2020 SDLoc dl, SelectionDAG &DAG,
2021 SmallVectorImpl<SDValue> &InVals) const {
2023 // 32-bit SVR4 ABI Stack Frame Layout:
2024 // +-----------------------------------+
2025 // +--> | Back chain |
2026 // | +-----------------------------------+
2027 // | | Floating-point register save area |
2028 // | +-----------------------------------+
2029 // | | General register save area |
2030 // | +-----------------------------------+
2031 // | | CR save word |
2032 // | +-----------------------------------+
2033 // | | VRSAVE save word |
2034 // | +-----------------------------------+
2035 // | | Alignment padding |
2036 // | +-----------------------------------+
2037 // | | Vector register save area |
2038 // | +-----------------------------------+
2039 // | | Local variable space |
2040 // | +-----------------------------------+
2041 // | | Parameter list area |
2042 // | +-----------------------------------+
2043 // | | LR save word |
2044 // | +-----------------------------------+
2045 // SP--> +--- | Back chain |
2046 // +-----------------------------------+
2049 // System V Application Binary Interface PowerPC Processor Supplement
2050 // AltiVec Technology Programming Interface Manual
2052 MachineFunction &MF = DAG.getMachineFunction();
2053 MachineFrameInfo *MFI = MF.getFrameInfo();
2054 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2056 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2057 // Potential tail calls could cause overwriting of argument stack slots.
2058 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2059 (CallConv == CallingConv::Fast));
2060 unsigned PtrByteSize = 4;
2062 // Assign locations to all of the incoming arguments.
2063 SmallVector<CCValAssign, 16> ArgLocs;
2064 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2065 getTargetMachine(), ArgLocs, *DAG.getContext());
2067 // Reserve space for the linkage area on the stack.
2068 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2070 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2072 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2073 CCValAssign &VA = ArgLocs[i];
2075 // Arguments stored in registers.
2076 if (VA.isRegLoc()) {
2077 const TargetRegisterClass *RC;
2078 EVT ValVT = VA.getValVT();
2080 switch (ValVT.getSimpleVT().SimpleTy) {
2082 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2085 RC = &PPC::GPRCRegClass;
2088 RC = &PPC::F4RCRegClass;
2091 RC = &PPC::F8RCRegClass;
2097 RC = &PPC::VRRCRegClass;
2101 // Transform the arguments stored in physical registers into virtual ones.
2102 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2103 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2104 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2106 if (ValVT == MVT::i1)
2107 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2109 InVals.push_back(ArgValue);
2111 // Argument stored in memory.
2112 assert(VA.isMemLoc());
2114 unsigned ArgSize = VA.getLocVT().getStoreSize();
2115 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2118 // Create load nodes to retrieve arguments from the stack.
2119 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2120 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2121 MachinePointerInfo(),
2122 false, false, false, 0));
2126 // Assign locations to all of the incoming aggregate by value arguments.
2127 // Aggregates passed by value are stored in the local variable space of the
2128 // caller's stack frame, right above the parameter list area.
2129 SmallVector<CCValAssign, 16> ByValArgLocs;
2130 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2131 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2133 // Reserve stack space for the allocations in CCInfo.
2134 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2136 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2138 // Area that is at least reserved in the caller of this function.
2139 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2141 // Set the size that is at least reserved in caller of this function. Tail
2142 // call optimized function's reserved stack space needs to be aligned so that
2143 // taking the difference between two stack areas will result in an aligned
2145 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2148 std::max(MinReservedArea,
2149 PPCFrameLowering::getMinCallFrameSize(false, false));
2151 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2152 getStackAlignment();
2153 unsigned AlignMask = TargetAlign-1;
2154 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2156 FI->setMinReservedArea(MinReservedArea);
2158 SmallVector<SDValue, 8> MemOps;
2160 // If the function takes variable number of arguments, make a frame index for
2161 // the start of the first vararg value... for expansion of llvm.va_start.
2163 static const uint16_t GPArgRegs[] = {
2164 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2165 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2167 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2169 static const uint16_t FPArgRegs[] = {
2170 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2173 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2175 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2177 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2180 // Make room for NumGPArgRegs and NumFPArgRegs.
2181 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2182 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2184 FuncInfo->setVarArgsStackOffset(
2185 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2186 CCInfo.getNextStackOffset(), true));
2188 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2189 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2191 // The fixed integer arguments of a variadic function are stored to the
2192 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2193 // the result of va_next.
2194 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2195 // Get an existing live-in vreg, or add a new one.
2196 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2198 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2200 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2201 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2202 MachinePointerInfo(), false, false, 0);
2203 MemOps.push_back(Store);
2204 // Increment the address by four for the next argument to store
2205 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2206 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2209 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2211 // The double arguments are stored to the VarArgsFrameIndex
2213 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2214 // Get an existing live-in vreg, or add a new one.
2215 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2217 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2219 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2220 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2221 MachinePointerInfo(), false, false, 0);
2222 MemOps.push_back(Store);
2223 // Increment the address by eight for the next argument to store
2224 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2226 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2230 if (!MemOps.empty())
2231 Chain = DAG.getNode(ISD::TokenFactor, dl,
2232 MVT::Other, &MemOps[0], MemOps.size());
2237 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2238 // value to MVT::i64 and then truncate to the correct register size.
2240 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2241 SelectionDAG &DAG, SDValue ArgVal,
2244 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2245 DAG.getValueType(ObjectVT));
2246 else if (Flags.isZExt())
2247 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2248 DAG.getValueType(ObjectVT));
2250 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2253 // Set the size that is at least reserved in caller of this function. Tail
2254 // call optimized functions' reserved stack space needs to be aligned so that
2255 // taking the difference between two stack areas will result in an aligned
2258 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2259 unsigned nAltivecParamsAtEnd,
2260 unsigned MinReservedArea,
2261 bool isPPC64) const {
2262 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2263 // Add the Altivec parameters at the end, if needed.
2264 if (nAltivecParamsAtEnd) {
2265 MinReservedArea = ((MinReservedArea+15)/16)*16;
2266 MinReservedArea += 16*nAltivecParamsAtEnd;
2269 std::max(MinReservedArea,
2270 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2271 unsigned TargetAlign
2272 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2273 getStackAlignment();
2274 unsigned AlignMask = TargetAlign-1;
2275 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2276 FI->setMinReservedArea(MinReservedArea);
2280 PPCTargetLowering::LowerFormalArguments_64SVR4(
2282 CallingConv::ID CallConv, bool isVarArg,
2283 const SmallVectorImpl<ISD::InputArg>
2285 SDLoc dl, SelectionDAG &DAG,
2286 SmallVectorImpl<SDValue> &InVals) const {
2287 // TODO: add description of PPC stack frame format, or at least some docs.
2289 MachineFunction &MF = DAG.getMachineFunction();
2290 MachineFrameInfo *MFI = MF.getFrameInfo();
2291 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2293 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2294 // Potential tail calls could cause overwriting of argument stack slots.
2295 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2296 (CallConv == CallingConv::Fast));
2297 unsigned PtrByteSize = 8;
2299 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2300 // Area that is at least reserved in caller of this function.
2301 unsigned MinReservedArea = ArgOffset;
2303 static const uint16_t GPR[] = {
2304 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2305 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2308 static const uint16_t *FPR = GetFPR();
2310 static const uint16_t VR[] = {
2311 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2312 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2315 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2316 const unsigned Num_FPR_Regs = 13;
2317 const unsigned Num_VR_Regs = array_lengthof(VR);
2319 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2321 // Add DAG nodes to load the arguments or copy them out of registers. On
2322 // entry to a function on PPC, the arguments start after the linkage area,
2323 // although the first ones are often in registers.
2325 SmallVector<SDValue, 8> MemOps;
2326 unsigned nAltivecParamsAtEnd = 0;
2327 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2328 unsigned CurArgIdx = 0;
2329 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2331 bool needsLoad = false;
2332 EVT ObjectVT = Ins[ArgNo].VT;
2333 unsigned ObjSize = ObjectVT.getStoreSize();
2334 unsigned ArgSize = ObjSize;
2335 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2336 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2337 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2339 unsigned CurArgOffset = ArgOffset;
2341 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2342 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2343 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2345 MinReservedArea = ((MinReservedArea+15)/16)*16;
2346 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2350 nAltivecParamsAtEnd++;
2352 // Calculate min reserved area.
2353 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2357 // FIXME the codegen can be much improved in some cases.
2358 // We do not have to keep everything in memory.
2359 if (Flags.isByVal()) {
2360 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2361 ObjSize = Flags.getByValSize();
2362 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2363 // Empty aggregate parameters do not take up registers. Examples:
2367 // etc. However, we have to provide a place-holder in InVals, so
2368 // pretend we have an 8-byte item at the current address for that
2371 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2372 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2373 InVals.push_back(FIN);
2377 unsigned BVAlign = Flags.getByValAlign();
2379 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2380 CurArgOffset = ArgOffset;
2383 // All aggregates smaller than 8 bytes must be passed right-justified.
2384 if (ObjSize < PtrByteSize)
2385 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2386 // The value of the object is its address.
2387 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2388 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2389 InVals.push_back(FIN);
2392 if (GPR_idx != Num_GPR_Regs) {
2393 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2394 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2397 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2398 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2399 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2400 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2401 MachinePointerInfo(FuncArg),
2402 ObjType, false, false, 0);
2404 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2405 // store the whole register as-is to the parameter save area
2406 // slot. The address of the parameter was already calculated
2407 // above (InVals.push_back(FIN)) to be the right-justified
2408 // offset within the slot. For this store, we need a new
2409 // frame index that points at the beginning of the slot.
2410 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2411 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2412 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2413 MachinePointerInfo(FuncArg),
2417 MemOps.push_back(Store);
2420 // Whether we copied from a register or not, advance the offset
2421 // into the parameter save area by a full doubleword.
2422 ArgOffset += PtrByteSize;
2426 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2427 // Store whatever pieces of the object are in registers
2428 // to memory. ArgOffset will be the address of the beginning
2430 if (GPR_idx != Num_GPR_Regs) {
2432 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2433 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2434 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2435 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2436 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2437 MachinePointerInfo(FuncArg, j),
2439 MemOps.push_back(Store);
2441 ArgOffset += PtrByteSize;
2443 ArgOffset += ArgSize - j;
2450 switch (ObjectVT.getSimpleVT().SimpleTy) {
2451 default: llvm_unreachable("Unhandled argument type!");
2455 if (GPR_idx != Num_GPR_Regs) {
2456 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2457 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2459 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2460 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2461 // value to MVT::i64 and then truncate to the correct register size.
2462 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2467 ArgSize = PtrByteSize;
2474 // Every 8 bytes of argument space consumes one of the GPRs available for
2475 // argument passing.
2476 if (GPR_idx != Num_GPR_Regs) {
2479 if (FPR_idx != Num_FPR_Regs) {
2482 if (ObjectVT == MVT::f32)
2483 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2485 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2487 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2491 ArgSize = PtrByteSize;
2500 // Note that vector arguments in registers don't reserve stack space,
2501 // except in varargs functions.
2502 if (VR_idx != Num_VR_Regs) {
2503 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2504 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2506 while ((ArgOffset % 16) != 0) {
2507 ArgOffset += PtrByteSize;
2508 if (GPR_idx != Num_GPR_Regs)
2512 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2516 // Vectors are aligned.
2517 ArgOffset = ((ArgOffset+15)/16)*16;
2518 CurArgOffset = ArgOffset;
2525 // We need to load the argument to a virtual register if we determined
2526 // above that we ran out of physical registers of the appropriate type.
2528 int FI = MFI->CreateFixedObject(ObjSize,
2529 CurArgOffset + (ArgSize - ObjSize),
2531 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2532 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2533 false, false, false, 0);
2536 InVals.push_back(ArgVal);
2539 // Set the size that is at least reserved in caller of this function. Tail
2540 // call optimized functions' reserved stack space needs to be aligned so that
2541 // taking the difference between two stack areas will result in an aligned
2543 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2545 // If the function takes variable number of arguments, make a frame index for
2546 // the start of the first vararg value... for expansion of llvm.va_start.
2548 int Depth = ArgOffset;
2550 FuncInfo->setVarArgsFrameIndex(
2551 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2552 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2554 // If this function is vararg, store any remaining integer argument regs
2555 // to their spots on the stack so that they may be loaded by deferencing the
2556 // result of va_next.
2557 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2558 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2559 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2560 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2561 MachinePointerInfo(), false, false, 0);
2562 MemOps.push_back(Store);
2563 // Increment the address by four for the next argument to store
2564 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2565 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2569 if (!MemOps.empty())
2570 Chain = DAG.getNode(ISD::TokenFactor, dl,
2571 MVT::Other, &MemOps[0], MemOps.size());
2577 PPCTargetLowering::LowerFormalArguments_Darwin(
2579 CallingConv::ID CallConv, bool isVarArg,
2580 const SmallVectorImpl<ISD::InputArg>
2582 SDLoc dl, SelectionDAG &DAG,
2583 SmallVectorImpl<SDValue> &InVals) const {
2584 // TODO: add description of PPC stack frame format, or at least some docs.
2586 MachineFunction &MF = DAG.getMachineFunction();
2587 MachineFrameInfo *MFI = MF.getFrameInfo();
2588 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2590 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2591 bool isPPC64 = PtrVT == MVT::i64;
2592 // Potential tail calls could cause overwriting of argument stack slots.
2593 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2594 (CallConv == CallingConv::Fast));
2595 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2597 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2598 // Area that is at least reserved in caller of this function.
2599 unsigned MinReservedArea = ArgOffset;
2601 static const uint16_t GPR_32[] = { // 32-bit registers.
2602 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2603 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2605 static const uint16_t GPR_64[] = { // 64-bit registers.
2606 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2607 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2610 static const uint16_t *FPR = GetFPR();
2612 static const uint16_t VR[] = {
2613 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2614 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2617 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2618 const unsigned Num_FPR_Regs = 13;
2619 const unsigned Num_VR_Regs = array_lengthof( VR);
2621 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2623 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2625 // In 32-bit non-varargs functions, the stack space for vectors is after the
2626 // stack space for non-vectors. We do not use this space unless we have
2627 // too many vectors to fit in registers, something that only occurs in
2628 // constructed examples:), but we have to walk the arglist to figure
2629 // that out...for the pathological case, compute VecArgOffset as the
2630 // start of the vector parameter area. Computing VecArgOffset is the
2631 // entire point of the following loop.
2632 unsigned VecArgOffset = ArgOffset;
2633 if (!isVarArg && !isPPC64) {
2634 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2636 EVT ObjectVT = Ins[ArgNo].VT;
2637 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2639 if (Flags.isByVal()) {
2640 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2641 unsigned ObjSize = Flags.getByValSize();
2643 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2644 VecArgOffset += ArgSize;
2648 switch(ObjectVT.getSimpleVT().SimpleTy) {
2649 default: llvm_unreachable("Unhandled argument type!");
2655 case MVT::i64: // PPC64
2657 // FIXME: We are guaranteed to be !isPPC64 at this point.
2658 // Does MVT::i64 apply?
2665 // Nothing to do, we're only looking at Nonvector args here.
2670 // We've found where the vector parameter area in memory is. Skip the
2671 // first 12 parameters; these don't use that memory.
2672 VecArgOffset = ((VecArgOffset+15)/16)*16;
2673 VecArgOffset += 12*16;
2675 // Add DAG nodes to load the arguments or copy them out of registers. On
2676 // entry to a function on PPC, the arguments start after the linkage area,
2677 // although the first ones are often in registers.
2679 SmallVector<SDValue, 8> MemOps;
2680 unsigned nAltivecParamsAtEnd = 0;
2681 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2682 unsigned CurArgIdx = 0;
2683 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2685 bool needsLoad = false;
2686 EVT ObjectVT = Ins[ArgNo].VT;
2687 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2688 unsigned ArgSize = ObjSize;
2689 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2690 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2691 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2693 unsigned CurArgOffset = ArgOffset;
2695 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2696 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2697 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2698 if (isVarArg || isPPC64) {
2699 MinReservedArea = ((MinReservedArea+15)/16)*16;
2700 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2703 } else nAltivecParamsAtEnd++;
2705 // Calculate min reserved area.
2706 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2710 // FIXME the codegen can be much improved in some cases.
2711 // We do not have to keep everything in memory.
2712 if (Flags.isByVal()) {
2713 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2714 ObjSize = Flags.getByValSize();
2715 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2716 // Objects of size 1 and 2 are right justified, everything else is
2717 // left justified. This means the memory address is adjusted forwards.
2718 if (ObjSize==1 || ObjSize==2) {
2719 CurArgOffset = CurArgOffset + (4 - ObjSize);
2721 // The value of the object is its address.
2722 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2723 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2724 InVals.push_back(FIN);
2725 if (ObjSize==1 || ObjSize==2) {
2726 if (GPR_idx != Num_GPR_Regs) {
2729 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2731 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2732 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2733 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2734 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2735 MachinePointerInfo(FuncArg),
2736 ObjType, false, false, 0);
2737 MemOps.push_back(Store);
2741 ArgOffset += PtrByteSize;
2745 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2746 // Store whatever pieces of the object are in registers
2747 // to memory. ArgOffset will be the address of the beginning
2749 if (GPR_idx != Num_GPR_Regs) {
2752 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2754 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2755 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2756 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2757 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2758 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2759 MachinePointerInfo(FuncArg, j),
2761 MemOps.push_back(Store);
2763 ArgOffset += PtrByteSize;
2765 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2772 switch (ObjectVT.getSimpleVT().SimpleTy) {
2773 default: llvm_unreachable("Unhandled argument type!");
2777 if (GPR_idx != Num_GPR_Regs) {
2778 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2779 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2781 if (ObjectVT == MVT::i1)
2782 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2787 ArgSize = PtrByteSize;
2789 // All int arguments reserve stack space in the Darwin ABI.
2790 ArgOffset += PtrByteSize;
2794 case MVT::i64: // PPC64
2795 if (GPR_idx != Num_GPR_Regs) {
2796 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2797 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2799 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2800 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2801 // value to MVT::i64 and then truncate to the correct register size.
2802 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2807 ArgSize = PtrByteSize;
2809 // All int arguments reserve stack space in the Darwin ABI.
2815 // Every 4 bytes of argument space consumes one of the GPRs available for
2816 // argument passing.
2817 if (GPR_idx != Num_GPR_Regs) {
2819 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2822 if (FPR_idx != Num_FPR_Regs) {
2825 if (ObjectVT == MVT::f32)
2826 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2828 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2830 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2836 // All FP arguments reserve stack space in the Darwin ABI.
2837 ArgOffset += isPPC64 ? 8 : ObjSize;
2843 // Note that vector arguments in registers don't reserve stack space,
2844 // except in varargs functions.
2845 if (VR_idx != Num_VR_Regs) {
2846 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2847 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2849 while ((ArgOffset % 16) != 0) {
2850 ArgOffset += PtrByteSize;
2851 if (GPR_idx != Num_GPR_Regs)
2855 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2859 if (!isVarArg && !isPPC64) {
2860 // Vectors go after all the nonvectors.
2861 CurArgOffset = VecArgOffset;
2864 // Vectors are aligned.
2865 ArgOffset = ((ArgOffset+15)/16)*16;
2866 CurArgOffset = ArgOffset;
2874 // We need to load the argument to a virtual register if we determined above
2875 // that we ran out of physical registers of the appropriate type.
2877 int FI = MFI->CreateFixedObject(ObjSize,
2878 CurArgOffset + (ArgSize - ObjSize),
2880 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2881 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2882 false, false, false, 0);
2885 InVals.push_back(ArgVal);
2888 // Set the size that is at least reserved in caller of this function. Tail
2889 // call optimized functions' reserved stack space needs to be aligned so that
2890 // taking the difference between two stack areas will result in an aligned
2892 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2894 // If the function takes variable number of arguments, make a frame index for
2895 // the start of the first vararg value... for expansion of llvm.va_start.
2897 int Depth = ArgOffset;
2899 FuncInfo->setVarArgsFrameIndex(
2900 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2902 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2904 // If this function is vararg, store any remaining integer argument regs
2905 // to their spots on the stack so that they may be loaded by deferencing the
2906 // result of va_next.
2907 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2911 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2913 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2915 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2916 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2917 MachinePointerInfo(), false, false, 0);
2918 MemOps.push_back(Store);
2919 // Increment the address by four for the next argument to store
2920 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2921 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2925 if (!MemOps.empty())
2926 Chain = DAG.getNode(ISD::TokenFactor, dl,
2927 MVT::Other, &MemOps[0], MemOps.size());
2932 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2933 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2935 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2939 const SmallVectorImpl<ISD::OutputArg>
2941 const SmallVectorImpl<SDValue> &OutVals,
2942 unsigned &nAltivecParamsAtEnd) {
2943 // Count how many bytes are to be pushed on the stack, including the linkage
2944 // area, and parameter passing area. We start with 24/48 bytes, which is
2945 // prereserved space for [SP][CR][LR][3 x unused].
2946 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2947 unsigned NumOps = Outs.size();
2948 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2950 // Add up all the space actually used.
2951 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2952 // they all go in registers, but we must reserve stack space for them for
2953 // possible use by the caller. In varargs or 64-bit calls, parameters are
2954 // assigned stack space in order, with padding so Altivec parameters are
2956 nAltivecParamsAtEnd = 0;
2957 for (unsigned i = 0; i != NumOps; ++i) {
2958 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2959 EVT ArgVT = Outs[i].VT;
2960 // Varargs Altivec parameters are padded to a 16 byte boundary.
2961 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2962 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2963 if (!isVarArg && !isPPC64) {
2964 // Non-varargs Altivec parameters go after all the non-Altivec
2965 // parameters; handle those later so we know how much padding we need.
2966 nAltivecParamsAtEnd++;
2969 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2970 NumBytes = ((NumBytes+15)/16)*16;
2972 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2975 // Allow for Altivec parameters at the end, if needed.
2976 if (nAltivecParamsAtEnd) {
2977 NumBytes = ((NumBytes+15)/16)*16;
2978 NumBytes += 16*nAltivecParamsAtEnd;
2981 // The prolog code of the callee may store up to 8 GPR argument registers to
2982 // the stack, allowing va_start to index over them in memory if its varargs.
2983 // Because we cannot tell if this is needed on the caller side, we have to
2984 // conservatively assume that it is needed. As such, make sure we have at
2985 // least enough stack space for the caller to store the 8 GPRs.
2986 NumBytes = std::max(NumBytes,
2987 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2989 // Tail call needs the stack to be aligned.
2990 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2991 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2992 getFrameLowering()->getStackAlignment();
2993 unsigned AlignMask = TargetAlign-1;
2994 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3000 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3001 /// adjusted to accommodate the arguments for the tailcall.
3002 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3003 unsigned ParamSize) {
3005 if (!isTailCall) return 0;
3007 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3008 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3009 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3010 // Remember only if the new adjustement is bigger.
3011 if (SPDiff < FI->getTailCallSPDelta())
3012 FI->setTailCallSPDelta(SPDiff);
3017 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3018 /// for tail call optimization. Targets which want to do tail call
3019 /// optimization should implement this function.
3021 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3022 CallingConv::ID CalleeCC,
3024 const SmallVectorImpl<ISD::InputArg> &Ins,
3025 SelectionDAG& DAG) const {
3026 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3029 // Variable argument functions are not supported.
3033 MachineFunction &MF = DAG.getMachineFunction();
3034 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3035 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3036 // Functions containing by val parameters are not supported.
3037 for (unsigned i = 0; i != Ins.size(); i++) {
3038 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3039 if (Flags.isByVal()) return false;
3042 // Non-PIC/GOT tail calls are supported.
3043 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3046 // At the moment we can only do local tail calls (in same module, hidden
3047 // or protected) if we are generating PIC.
3048 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3049 return G->getGlobal()->hasHiddenVisibility()
3050 || G->getGlobal()->hasProtectedVisibility();
3056 /// isCallCompatibleAddress - Return the immediate to use if the specified
3057 /// 32-bit value is representable in the immediate field of a BxA instruction.
3058 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3059 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3062 int Addr = C->getZExtValue();
3063 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3064 SignExtend32<26>(Addr) != Addr)
3065 return 0; // Top 6 bits have to be sext of immediate.
3067 return DAG.getConstant((int)C->getZExtValue() >> 2,
3068 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3073 struct TailCallArgumentInfo {
3078 TailCallArgumentInfo() : FrameIdx(0) {}
3083 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3085 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3087 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3088 SmallVectorImpl<SDValue> &MemOpChains,
3090 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3091 SDValue Arg = TailCallArgs[i].Arg;
3092 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3093 int FI = TailCallArgs[i].FrameIdx;
3094 // Store relative to framepointer.
3095 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3096 MachinePointerInfo::getFixedStack(FI),
3101 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3102 /// the appropriate stack slot for the tail call optimized function call.
3103 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3104 MachineFunction &MF,
3113 // Calculate the new stack slot for the return address.
3114 int SlotSize = isPPC64 ? 8 : 4;
3115 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3117 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3118 NewRetAddrLoc, true);
3119 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3120 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3121 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3122 MachinePointerInfo::getFixedStack(NewRetAddr),
3125 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3126 // slot as the FP is never overwritten.
3129 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3130 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3132 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3133 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3134 MachinePointerInfo::getFixedStack(NewFPIdx),
3141 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3142 /// the position of the argument.
3144 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3145 SDValue Arg, int SPDiff, unsigned ArgOffset,
3146 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3147 int Offset = ArgOffset + SPDiff;
3148 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3149 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3150 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3151 SDValue FIN = DAG.getFrameIndex(FI, VT);
3152 TailCallArgumentInfo Info;
3154 Info.FrameIdxOp = FIN;
3156 TailCallArguments.push_back(Info);
3159 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3160 /// stack slot. Returns the chain as result and the loaded frame pointers in
3161 /// LROpOut/FPOpout. Used when tail calling.
3162 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3170 // Load the LR and FP stack slot for later adjusting.
3171 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3172 LROpOut = getReturnAddrFrameIndex(DAG);
3173 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3174 false, false, false, 0);
3175 Chain = SDValue(LROpOut.getNode(), 1);
3177 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3178 // slot as the FP is never overwritten.
3180 FPOpOut = getFramePointerFrameIndex(DAG);
3181 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3182 false, false, false, 0);
3183 Chain = SDValue(FPOpOut.getNode(), 1);
3189 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3190 /// by "Src" to address "Dst" of size "Size". Alignment information is
3191 /// specified by the specific parameter attribute. The copy will be passed as
3192 /// a byval function parameter.
3193 /// Sometimes what we are copying is the end of a larger object, the part that
3194 /// does not fit in registers.
3196 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3197 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3199 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3200 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3201 false, false, MachinePointerInfo(0),
3202 MachinePointerInfo(0));
3205 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3208 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3209 SDValue Arg, SDValue PtrOff, int SPDiff,
3210 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3211 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3212 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3214 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3219 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3221 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3222 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3223 DAG.getConstant(ArgOffset, PtrVT));
3225 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3226 MachinePointerInfo(), false, false, 0));
3227 // Calculate and remember argument location.
3228 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3233 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3234 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3235 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3236 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3237 MachineFunction &MF = DAG.getMachineFunction();
3239 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3240 // might overwrite each other in case of tail call optimization.
3241 SmallVector<SDValue, 8> MemOpChains2;
3242 // Do not flag preceding copytoreg stuff together with the following stuff.
3244 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3246 if (!MemOpChains2.empty())
3247 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3248 &MemOpChains2[0], MemOpChains2.size());
3250 // Store the return address to the appropriate stack slot.
3251 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3252 isPPC64, isDarwinABI, dl);
3254 // Emit callseq_end just before tailcall node.
3255 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3256 DAG.getIntPtrConstant(0, true), InFlag, dl);
3257 InFlag = Chain.getValue(1);
3261 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3262 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3263 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3264 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3265 const PPCSubtarget &PPCSubTarget) {
3267 bool isPPC64 = PPCSubTarget.isPPC64();
3268 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3270 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3271 NodeTys.push_back(MVT::Other); // Returns a chain
3272 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3274 unsigned CallOpc = PPCISD::CALL;
3276 bool needIndirectCall = true;
3277 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3278 // If this is an absolute destination address, use the munged value.
3279 Callee = SDValue(Dest, 0);
3280 needIndirectCall = false;
3283 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3284 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3285 // Use indirect calls for ALL functions calls in JIT mode, since the
3286 // far-call stubs may be outside relocation limits for a BL instruction.
3287 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3288 unsigned OpFlags = 0;
3289 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3290 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3291 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3292 (G->getGlobal()->isDeclaration() ||
3293 G->getGlobal()->isWeakForLinker())) {
3294 // PC-relative references to external symbols should go through $stub,
3295 // unless we're building with the leopard linker or later, which
3296 // automatically synthesizes these stubs.
3297 OpFlags = PPCII::MO_DARWIN_STUB;
3300 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3301 // every direct call is) turn it into a TargetGlobalAddress /
3302 // TargetExternalSymbol node so that legalize doesn't hack it.
3303 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3304 Callee.getValueType(),
3306 needIndirectCall = false;
3310 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3311 unsigned char OpFlags = 0;
3313 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3314 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3315 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3316 // PC-relative references to external symbols should go through $stub,
3317 // unless we're building with the leopard linker or later, which
3318 // automatically synthesizes these stubs.
3319 OpFlags = PPCII::MO_DARWIN_STUB;
3322 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3324 needIndirectCall = false;
3327 if (needIndirectCall) {
3328 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3329 // to do the call, we can't use PPCISD::CALL.
3330 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3332 if (isSVR4ABI && isPPC64) {
3333 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3334 // entry point, but to the function descriptor (the function entry point
3335 // address is part of the function descriptor though).
3336 // The function descriptor is a three doubleword structure with the
3337 // following fields: function entry point, TOC base address and
3338 // environment pointer.
3339 // Thus for a call through a function pointer, the following actions need
3341 // 1. Save the TOC of the caller in the TOC save area of its stack
3342 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3343 // 2. Load the address of the function entry point from the function
3345 // 3. Load the TOC of the callee from the function descriptor into r2.
3346 // 4. Load the environment pointer from the function descriptor into
3348 // 5. Branch to the function entry point address.
3349 // 6. On return of the callee, the TOC of the caller needs to be
3350 // restored (this is done in FinishCall()).
3352 // All those operations are flagged together to ensure that no other
3353 // operations can be scheduled in between. E.g. without flagging the
3354 // operations together, a TOC access in the caller could be scheduled
3355 // between the load of the callee TOC and the branch to the callee, which
3356 // results in the TOC access going through the TOC of the callee instead
3357 // of going through the TOC of the caller, which leads to incorrect code.
3359 // Load the address of the function entry point from the function
3361 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3362 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3363 InFlag.getNode() ? 3 : 2);
3364 Chain = LoadFuncPtr.getValue(1);
3365 InFlag = LoadFuncPtr.getValue(2);
3367 // Load environment pointer into r11.
3368 // Offset of the environment pointer within the function descriptor.
3369 SDValue PtrOff = DAG.getIntPtrConstant(16);
3371 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3372 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3374 Chain = LoadEnvPtr.getValue(1);
3375 InFlag = LoadEnvPtr.getValue(2);
3377 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3379 Chain = EnvVal.getValue(0);
3380 InFlag = EnvVal.getValue(1);
3382 // Load TOC of the callee into r2. We are using a target-specific load
3383 // with r2 hard coded, because the result of a target-independent load
3384 // would never go directly into r2, since r2 is a reserved register (which
3385 // prevents the register allocator from allocating it), resulting in an
3386 // additional register being allocated and an unnecessary move instruction
3388 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3389 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3391 Chain = LoadTOCPtr.getValue(0);
3392 InFlag = LoadTOCPtr.getValue(1);
3394 MTCTROps[0] = Chain;
3395 MTCTROps[1] = LoadFuncPtr;
3396 MTCTROps[2] = InFlag;
3399 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3400 2 + (InFlag.getNode() != 0));
3401 InFlag = Chain.getValue(1);
3404 NodeTys.push_back(MVT::Other);
3405 NodeTys.push_back(MVT::Glue);
3406 Ops.push_back(Chain);
3407 CallOpc = PPCISD::BCTRL;
3409 // Add use of X11 (holding environment pointer)
3410 if (isSVR4ABI && isPPC64)
3411 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3412 // Add CTR register as callee so a bctr can be emitted later.
3414 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3417 // If this is a direct call, pass the chain and the callee.
3418 if (Callee.getNode()) {
3419 Ops.push_back(Chain);
3420 Ops.push_back(Callee);
3422 // If this is a tail call add stack pointer delta.
3424 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3426 // Add argument registers to the end of the list so that they are known live
3428 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3429 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3430 RegsToPass[i].second.getValueType()));
3436 bool isLocalCall(const SDValue &Callee)
3438 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3439 return !G->getGlobal()->isDeclaration() &&
3440 !G->getGlobal()->isWeakForLinker();
3445 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3446 CallingConv::ID CallConv, bool isVarArg,
3447 const SmallVectorImpl<ISD::InputArg> &Ins,
3448 SDLoc dl, SelectionDAG &DAG,
3449 SmallVectorImpl<SDValue> &InVals) const {
3451 SmallVector<CCValAssign, 16> RVLocs;
3452 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3453 getTargetMachine(), RVLocs, *DAG.getContext());
3454 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3456 // Copy all of the result registers out of their specified physreg.
3457 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3458 CCValAssign &VA = RVLocs[i];
3459 assert(VA.isRegLoc() && "Can only return in registers!");
3461 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3462 VA.getLocReg(), VA.getLocVT(), InFlag);
3463 Chain = Val.getValue(1);
3464 InFlag = Val.getValue(2);
3466 switch (VA.getLocInfo()) {
3467 default: llvm_unreachable("Unknown loc info!");
3468 case CCValAssign::Full: break;
3469 case CCValAssign::AExt:
3470 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3472 case CCValAssign::ZExt:
3473 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3474 DAG.getValueType(VA.getValVT()));
3475 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3477 case CCValAssign::SExt:
3478 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3479 DAG.getValueType(VA.getValVT()));
3480 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3484 InVals.push_back(Val);
3491 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3492 bool isTailCall, bool isVarArg,
3494 SmallVector<std::pair<unsigned, SDValue>, 8>
3496 SDValue InFlag, SDValue Chain,
3498 int SPDiff, unsigned NumBytes,
3499 const SmallVectorImpl<ISD::InputArg> &Ins,
3500 SmallVectorImpl<SDValue> &InVals) const {
3501 std::vector<EVT> NodeTys;
3502 SmallVector<SDValue, 8> Ops;
3503 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3504 isTailCall, RegsToPass, Ops, NodeTys,
3507 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3508 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3509 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3511 // When performing tail call optimization the callee pops its arguments off
3512 // the stack. Account for this here so these bytes can be pushed back on in
3513 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3514 int BytesCalleePops =
3515 (CallConv == CallingConv::Fast &&
3516 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3518 // Add a register mask operand representing the call-preserved registers.
3519 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3520 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3521 assert(Mask && "Missing call preserved mask for calling convention");
3522 Ops.push_back(DAG.getRegisterMask(Mask));
3524 if (InFlag.getNode())
3525 Ops.push_back(InFlag);
3529 assert(((Callee.getOpcode() == ISD::Register &&
3530 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3531 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3532 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3533 isa<ConstantSDNode>(Callee)) &&
3534 "Expecting an global address, external symbol, absolute value or register");
3536 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3539 // Add a NOP immediately after the branch instruction when using the 64-bit
3540 // SVR4 ABI. At link time, if caller and callee are in a different module and
3541 // thus have a different TOC, the call will be replaced with a call to a stub
3542 // function which saves the current TOC, loads the TOC of the callee and
3543 // branches to the callee. The NOP will be replaced with a load instruction
3544 // which restores the TOC of the caller from the TOC save slot of the current
3545 // stack frame. If caller and callee belong to the same module (and have the
3546 // same TOC), the NOP will remain unchanged.
3548 bool needsTOCRestore = false;
3549 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3550 if (CallOpc == PPCISD::BCTRL) {
3551 // This is a call through a function pointer.
3552 // Restore the caller TOC from the save area into R2.
3553 // See PrepareCall() for more information about calls through function
3554 // pointers in the 64-bit SVR4 ABI.
3555 // We are using a target-specific load with r2 hard coded, because the
3556 // result of a target-independent load would never go directly into r2,
3557 // since r2 is a reserved register (which prevents the register allocator
3558 // from allocating it), resulting in an additional register being
3559 // allocated and an unnecessary move instruction being generated.
3560 needsTOCRestore = true;
3561 } else if ((CallOpc == PPCISD::CALL) &&
3562 (!isLocalCall(Callee) ||
3563 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3564 // Otherwise insert NOP for non-local calls.
3565 CallOpc = PPCISD::CALL_NOP;
3569 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3570 InFlag = Chain.getValue(1);
3572 if (needsTOCRestore) {
3573 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3574 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3575 InFlag = Chain.getValue(1);
3578 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3579 DAG.getIntPtrConstant(BytesCalleePops, true),
3582 InFlag = Chain.getValue(1);
3584 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3585 Ins, dl, DAG, InVals);
3589 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3590 SmallVectorImpl<SDValue> &InVals) const {
3591 SelectionDAG &DAG = CLI.DAG;
3593 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3594 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3595 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3596 SDValue Chain = CLI.Chain;
3597 SDValue Callee = CLI.Callee;
3598 bool &isTailCall = CLI.IsTailCall;
3599 CallingConv::ID CallConv = CLI.CallConv;
3600 bool isVarArg = CLI.IsVarArg;
3603 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3606 if (PPCSubTarget.isSVR4ABI()) {
3607 if (PPCSubTarget.isPPC64())
3608 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3609 isTailCall, Outs, OutVals, Ins,
3612 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3613 isTailCall, Outs, OutVals, Ins,
3617 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3618 isTailCall, Outs, OutVals, Ins,
3623 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3624 CallingConv::ID CallConv, bool isVarArg,
3626 const SmallVectorImpl<ISD::OutputArg> &Outs,
3627 const SmallVectorImpl<SDValue> &OutVals,
3628 const SmallVectorImpl<ISD::InputArg> &Ins,
3629 SDLoc dl, SelectionDAG &DAG,
3630 SmallVectorImpl<SDValue> &InVals) const {
3631 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3632 // of the 32-bit SVR4 ABI stack frame layout.
3634 assert((CallConv == CallingConv::C ||
3635 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3637 unsigned PtrByteSize = 4;
3639 MachineFunction &MF = DAG.getMachineFunction();
3641 // Mark this function as potentially containing a function that contains a
3642 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3643 // and restoring the callers stack pointer in this functions epilog. This is
3644 // done because by tail calling the called function might overwrite the value
3645 // in this function's (MF) stack pointer stack slot 0(SP).
3646 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3647 CallConv == CallingConv::Fast)
3648 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3650 // Count how many bytes are to be pushed on the stack, including the linkage
3651 // area, parameter list area and the part of the local variable space which
3652 // contains copies of aggregates which are passed by value.
3654 // Assign locations to all of the outgoing arguments.
3655 SmallVector<CCValAssign, 16> ArgLocs;
3656 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3657 getTargetMachine(), ArgLocs, *DAG.getContext());
3659 // Reserve space for the linkage area on the stack.
3660 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3663 // Handle fixed and variable vector arguments differently.
3664 // Fixed vector arguments go into registers as long as registers are
3665 // available. Variable vector arguments always go into memory.
3666 unsigned NumArgs = Outs.size();
3668 for (unsigned i = 0; i != NumArgs; ++i) {
3669 MVT ArgVT = Outs[i].VT;
3670 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3673 if (Outs[i].IsFixed) {
3674 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3677 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3683 errs() << "Call operand #" << i << " has unhandled type "
3684 << EVT(ArgVT).getEVTString() << "\n";
3686 llvm_unreachable(0);
3690 // All arguments are treated the same.
3691 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3694 // Assign locations to all of the outgoing aggregate by value arguments.
3695 SmallVector<CCValAssign, 16> ByValArgLocs;
3696 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3697 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3699 // Reserve stack space for the allocations in CCInfo.
3700 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3702 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3704 // Size of the linkage area, parameter list area and the part of the local
3705 // space variable where copies of aggregates which are passed by value are
3707 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3709 // Calculate by how many bytes the stack has to be adjusted in case of tail
3710 // call optimization.
3711 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3713 // Adjust the stack pointer for the new arguments...
3714 // These operations are automatically eliminated by the prolog/epilog pass
3715 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3717 SDValue CallSeqStart = Chain;
3719 // Load the return address and frame pointer so it can be moved somewhere else
3722 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3725 // Set up a copy of the stack pointer for use loading and storing any
3726 // arguments that may not fit in the registers available for argument
3728 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3730 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3731 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3732 SmallVector<SDValue, 8> MemOpChains;
3734 bool seenFloatArg = false;
3735 // Walk the register/memloc assignments, inserting copies/loads.
3736 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3739 CCValAssign &VA = ArgLocs[i];
3740 SDValue Arg = OutVals[i];
3741 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3743 if (Flags.isByVal()) {
3744 // Argument is an aggregate which is passed by value, thus we need to
3745 // create a copy of it in the local variable space of the current stack
3746 // frame (which is the stack frame of the caller) and pass the address of
3747 // this copy to the callee.
3748 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3749 CCValAssign &ByValVA = ByValArgLocs[j++];
3750 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3752 // Memory reserved in the local variable space of the callers stack frame.
3753 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3755 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3756 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3758 // Create a copy of the argument in the local area of the current
3760 SDValue MemcpyCall =
3761 CreateCopyOfByValArgument(Arg, PtrOff,
3762 CallSeqStart.getNode()->getOperand(0),
3765 // This must go outside the CALLSEQ_START..END.
3766 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3767 CallSeqStart.getNode()->getOperand(1),
3769 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3770 NewCallSeqStart.getNode());
3771 Chain = CallSeqStart = NewCallSeqStart;
3773 // Pass the address of the aggregate copy on the stack either in a
3774 // physical register or in the parameter list area of the current stack
3775 // frame to the callee.
3779 if (VA.isRegLoc()) {
3780 if (Arg.getValueType() == MVT::i1)
3781 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3783 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3784 // Put argument in a physical register.
3785 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3787 // Put argument in the parameter list area of the current stack frame.
3788 assert(VA.isMemLoc());
3789 unsigned LocMemOffset = VA.getLocMemOffset();
3792 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3793 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3795 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3796 MachinePointerInfo(),
3799 // Calculate and remember argument location.
3800 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3806 if (!MemOpChains.empty())
3807 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3808 &MemOpChains[0], MemOpChains.size());
3810 // Build a sequence of copy-to-reg nodes chained together with token chain
3811 // and flag operands which copy the outgoing args into the appropriate regs.
3813 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3814 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3815 RegsToPass[i].second, InFlag);
3816 InFlag = Chain.getValue(1);
3819 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3822 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3823 SDValue Ops[] = { Chain, InFlag };
3825 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3826 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3828 InFlag = Chain.getValue(1);
3832 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3833 false, TailCallArguments);
3835 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3836 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3840 // Copy an argument into memory, being careful to do this outside the
3841 // call sequence for the call to which the argument belongs.
3843 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3844 SDValue CallSeqStart,
3845 ISD::ArgFlagsTy Flags,
3848 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3849 CallSeqStart.getNode()->getOperand(0),
3851 // The MEMCPY must go outside the CALLSEQ_START..END.
3852 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3853 CallSeqStart.getNode()->getOperand(1),
3855 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3856 NewCallSeqStart.getNode());
3857 return NewCallSeqStart;
3861 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3862 CallingConv::ID CallConv, bool isVarArg,
3864 const SmallVectorImpl<ISD::OutputArg> &Outs,
3865 const SmallVectorImpl<SDValue> &OutVals,
3866 const SmallVectorImpl<ISD::InputArg> &Ins,
3867 SDLoc dl, SelectionDAG &DAG,
3868 SmallVectorImpl<SDValue> &InVals) const {
3870 unsigned NumOps = Outs.size();
3872 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3873 unsigned PtrByteSize = 8;
3875 MachineFunction &MF = DAG.getMachineFunction();
3877 // Mark this function as potentially containing a function that contains a
3878 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3879 // and restoring the callers stack pointer in this functions epilog. This is
3880 // done because by tail calling the called function might overwrite the value
3881 // in this function's (MF) stack pointer stack slot 0(SP).
3882 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3883 CallConv == CallingConv::Fast)
3884 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3886 unsigned nAltivecParamsAtEnd = 0;
3888 // Count how many bytes are to be pushed on the stack, including the linkage
3889 // area, and parameter passing area. We start with at least 48 bytes, which
3890 // is reserved space for [SP][CR][LR][3 x unused].
3891 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3894 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3895 Outs, OutVals, nAltivecParamsAtEnd);
3897 // Calculate by how many bytes the stack has to be adjusted in case of tail
3898 // call optimization.
3899 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3901 // To protect arguments on the stack from being clobbered in a tail call,
3902 // force all the loads to happen before doing any other lowering.
3904 Chain = DAG.getStackArgumentTokenFactor(Chain);
3906 // Adjust the stack pointer for the new arguments...
3907 // These operations are automatically eliminated by the prolog/epilog pass
3908 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3910 SDValue CallSeqStart = Chain;
3912 // Load the return address and frame pointer so it can be move somewhere else
3915 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3918 // Set up a copy of the stack pointer for use loading and storing any
3919 // arguments that may not fit in the registers available for argument
3921 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3923 // Figure out which arguments are going to go in registers, and which in
3924 // memory. Also, if this is a vararg function, floating point operations
3925 // must be stored to our stack, and loaded into integer regs as well, if
3926 // any integer regs are available for argument passing.
3927 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3928 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3930 static const uint16_t GPR[] = {
3931 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3932 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3934 static const uint16_t *FPR = GetFPR();
3936 static const uint16_t VR[] = {
3937 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3938 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3940 const unsigned NumGPRs = array_lengthof(GPR);
3941 const unsigned NumFPRs = 13;
3942 const unsigned NumVRs = array_lengthof(VR);
3944 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3945 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3947 SmallVector<SDValue, 8> MemOpChains;
3948 for (unsigned i = 0; i != NumOps; ++i) {
3949 SDValue Arg = OutVals[i];
3950 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3952 // PtrOff will be used to store the current argument to the stack if a
3953 // register cannot be found for it.
3956 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3958 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3960 // Promote integers to 64-bit values.
3961 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
3962 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3963 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3964 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3967 // FIXME memcpy is used way more than necessary. Correctness first.
3968 // Note: "by value" is code for passing a structure by value, not
3970 if (Flags.isByVal()) {
3971 // Note: Size includes alignment padding, so
3972 // struct x { short a; char b; }
3973 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3974 // These are the proper values we need for right-justifying the
3975 // aggregate in a parameter register.
3976 unsigned Size = Flags.getByValSize();
3978 // An empty aggregate parameter takes up no storage and no
3983 unsigned BVAlign = Flags.getByValAlign();
3985 if (BVAlign % PtrByteSize != 0)
3987 "ByVal alignment is not a multiple of the pointer size");
3989 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
3992 // All aggregates smaller than 8 bytes must be passed right-justified.
3993 if (Size==1 || Size==2 || Size==4) {
3994 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3995 if (GPR_idx != NumGPRs) {
3996 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3997 MachinePointerInfo(), VT,
3999 MemOpChains.push_back(Load.getValue(1));
4000 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4002 ArgOffset += PtrByteSize;
4007 if (GPR_idx == NumGPRs && Size < 8) {
4008 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4009 PtrOff.getValueType());
4010 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4011 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4014 ArgOffset += PtrByteSize;
4017 // Copy entire object into memory. There are cases where gcc-generated
4018 // code assumes it is there, even if it could be put entirely into
4019 // registers. (This is not what the doc says.)
4021 // FIXME: The above statement is likely due to a misunderstanding of the
4022 // documents. All arguments must be copied into the parameter area BY
4023 // THE CALLEE in the event that the callee takes the address of any
4024 // formal argument. That has not yet been implemented. However, it is
4025 // reasonable to use the stack area as a staging area for the register
4028 // Skip this for small aggregates, as we will use the same slot for a
4029 // right-justified copy, below.
4031 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4035 // When a register is available, pass a small aggregate right-justified.
4036 if (Size < 8 && GPR_idx != NumGPRs) {
4037 // The easiest way to get this right-justified in a register
4038 // is to copy the structure into the rightmost portion of a
4039 // local variable slot, then load the whole slot into the
4041 // FIXME: The memcpy seems to produce pretty awful code for
4042 // small aggregates, particularly for packed ones.
4043 // FIXME: It would be preferable to use the slot in the
4044 // parameter save area instead of a new local variable.
4045 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4046 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4047 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4051 // Load the slot into the register.
4052 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4053 MachinePointerInfo(),
4054 false, false, false, 0);
4055 MemOpChains.push_back(Load.getValue(1));
4056 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4058 // Done with this argument.
4059 ArgOffset += PtrByteSize;
4063 // For aggregates larger than PtrByteSize, copy the pieces of the
4064 // object that fit into registers from the parameter save area.
4065 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4066 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4067 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4068 if (GPR_idx != NumGPRs) {
4069 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4070 MachinePointerInfo(),
4071 false, false, false, 0);
4072 MemOpChains.push_back(Load.getValue(1));
4073 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4074 ArgOffset += PtrByteSize;
4076 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4083 switch (Arg.getSimpleValueType().SimpleTy) {
4084 default: llvm_unreachable("Unexpected ValueType for argument!");
4088 if (GPR_idx != NumGPRs) {
4089 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4091 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4092 true, isTailCall, false, MemOpChains,
4093 TailCallArguments, dl);
4095 ArgOffset += PtrByteSize;
4099 if (FPR_idx != NumFPRs) {
4100 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4103 // A single float or an aggregate containing only a single float
4104 // must be passed right-justified in the stack doubleword, and
4105 // in the GPR, if one is available.
4107 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4108 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4109 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4113 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4114 MachinePointerInfo(), false, false, 0);
4115 MemOpChains.push_back(Store);
4117 // Float varargs are always shadowed in available integer registers
4118 if (GPR_idx != NumGPRs) {
4119 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4120 MachinePointerInfo(), false, false,
4122 MemOpChains.push_back(Load.getValue(1));
4123 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4125 } else if (GPR_idx != NumGPRs)
4126 // If we have any FPRs remaining, we may also have GPRs remaining.
4129 // Single-precision floating-point values are mapped to the
4130 // second (rightmost) word of the stack doubleword.
4131 if (Arg.getValueType() == MVT::f32) {
4132 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4133 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4136 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4137 true, isTailCall, false, MemOpChains,
4138 TailCallArguments, dl);
4147 // These go aligned on the stack, or in the corresponding R registers
4148 // when within range. The Darwin PPC ABI doc claims they also go in
4149 // V registers; in fact gcc does this only for arguments that are
4150 // prototyped, not for those that match the ... We do it for all
4151 // arguments, seems to work.
4152 while (ArgOffset % 16 !=0) {
4153 ArgOffset += PtrByteSize;
4154 if (GPR_idx != NumGPRs)
4157 // We could elide this store in the case where the object fits
4158 // entirely in R registers. Maybe later.
4159 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4160 DAG.getConstant(ArgOffset, PtrVT));
4161 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4162 MachinePointerInfo(), false, false, 0);
4163 MemOpChains.push_back(Store);
4164 if (VR_idx != NumVRs) {
4165 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4166 MachinePointerInfo(),
4167 false, false, false, 0);
4168 MemOpChains.push_back(Load.getValue(1));
4169 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4172 for (unsigned i=0; i<16; i+=PtrByteSize) {
4173 if (GPR_idx == NumGPRs)
4175 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4176 DAG.getConstant(i, PtrVT));
4177 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4178 false, false, false, 0);
4179 MemOpChains.push_back(Load.getValue(1));
4180 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4185 // Non-varargs Altivec params generally go in registers, but have
4186 // stack space allocated at the end.
4187 if (VR_idx != NumVRs) {
4188 // Doesn't have GPR space allocated.
4189 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4191 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4192 true, isTailCall, true, MemOpChains,
4193 TailCallArguments, dl);
4200 if (!MemOpChains.empty())
4201 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4202 &MemOpChains[0], MemOpChains.size());
4204 // Check if this is an indirect call (MTCTR/BCTRL).
4205 // See PrepareCall() for more information about calls through function
4206 // pointers in the 64-bit SVR4 ABI.
4208 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4209 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4210 !isBLACompatibleAddress(Callee, DAG)) {
4211 // Load r2 into a virtual register and store it to the TOC save area.
4212 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4213 // TOC save area offset.
4214 SDValue PtrOff = DAG.getIntPtrConstant(40);
4215 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4216 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4218 // R12 must contain the address of an indirect callee. This does not
4219 // mean the MTCTR instruction must use R12; it's easier to model this
4220 // as an extra parameter, so do that.
4221 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4224 // Build a sequence of copy-to-reg nodes chained together with token chain
4225 // and flag operands which copy the outgoing args into the appropriate regs.
4227 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4228 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4229 RegsToPass[i].second, InFlag);
4230 InFlag = Chain.getValue(1);
4234 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4235 FPOp, true, TailCallArguments);
4237 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4238 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4243 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4244 CallingConv::ID CallConv, bool isVarArg,
4246 const SmallVectorImpl<ISD::OutputArg> &Outs,
4247 const SmallVectorImpl<SDValue> &OutVals,
4248 const SmallVectorImpl<ISD::InputArg> &Ins,
4249 SDLoc dl, SelectionDAG &DAG,
4250 SmallVectorImpl<SDValue> &InVals) const {
4252 unsigned NumOps = Outs.size();
4254 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4255 bool isPPC64 = PtrVT == MVT::i64;
4256 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4258 MachineFunction &MF = DAG.getMachineFunction();
4260 // Mark this function as potentially containing a function that contains a
4261 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4262 // and restoring the callers stack pointer in this functions epilog. This is
4263 // done because by tail calling the called function might overwrite the value
4264 // in this function's (MF) stack pointer stack slot 0(SP).
4265 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4266 CallConv == CallingConv::Fast)
4267 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4269 unsigned nAltivecParamsAtEnd = 0;
4271 // Count how many bytes are to be pushed on the stack, including the linkage
4272 // area, and parameter passing area. We start with 24/48 bytes, which is
4273 // prereserved space for [SP][CR][LR][3 x unused].
4275 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4277 nAltivecParamsAtEnd);
4279 // Calculate by how many bytes the stack has to be adjusted in case of tail
4280 // call optimization.
4281 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4283 // To protect arguments on the stack from being clobbered in a tail call,
4284 // force all the loads to happen before doing any other lowering.
4286 Chain = DAG.getStackArgumentTokenFactor(Chain);
4288 // Adjust the stack pointer for the new arguments...
4289 // These operations are automatically eliminated by the prolog/epilog pass
4290 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4292 SDValue CallSeqStart = Chain;
4294 // Load the return address and frame pointer so it can be move somewhere else
4297 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4300 // Set up a copy of the stack pointer for use loading and storing any
4301 // arguments that may not fit in the registers available for argument
4305 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4307 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4309 // Figure out which arguments are going to go in registers, and which in
4310 // memory. Also, if this is a vararg function, floating point operations
4311 // must be stored to our stack, and loaded into integer regs as well, if
4312 // any integer regs are available for argument passing.
4313 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4314 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4316 static const uint16_t GPR_32[] = { // 32-bit registers.
4317 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4318 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4320 static const uint16_t GPR_64[] = { // 64-bit registers.
4321 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4322 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4324 static const uint16_t *FPR = GetFPR();
4326 static const uint16_t VR[] = {
4327 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4328 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4330 const unsigned NumGPRs = array_lengthof(GPR_32);
4331 const unsigned NumFPRs = 13;
4332 const unsigned NumVRs = array_lengthof(VR);
4334 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4336 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4337 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4339 SmallVector<SDValue, 8> MemOpChains;
4340 for (unsigned i = 0; i != NumOps; ++i) {
4341 SDValue Arg = OutVals[i];
4342 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4344 // PtrOff will be used to store the current argument to the stack if a
4345 // register cannot be found for it.
4348 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4350 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4352 // On PPC64, promote integers to 64-bit values.
4353 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4354 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4355 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4356 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4359 // FIXME memcpy is used way more than necessary. Correctness first.
4360 // Note: "by value" is code for passing a structure by value, not
4362 if (Flags.isByVal()) {
4363 unsigned Size = Flags.getByValSize();
4364 // Very small objects are passed right-justified. Everything else is
4365 // passed left-justified.
4366 if (Size==1 || Size==2) {
4367 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4368 if (GPR_idx != NumGPRs) {
4369 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4370 MachinePointerInfo(), VT,
4372 MemOpChains.push_back(Load.getValue(1));
4373 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4375 ArgOffset += PtrByteSize;
4377 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4378 PtrOff.getValueType());
4379 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4380 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4383 ArgOffset += PtrByteSize;
4387 // Copy entire object into memory. There are cases where gcc-generated
4388 // code assumes it is there, even if it could be put entirely into
4389 // registers. (This is not what the doc says.)
4390 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4394 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4395 // copy the pieces of the object that fit into registers from the
4396 // parameter save area.
4397 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4398 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4399 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4400 if (GPR_idx != NumGPRs) {
4401 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4402 MachinePointerInfo(),
4403 false, false, false, 0);
4404 MemOpChains.push_back(Load.getValue(1));
4405 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4406 ArgOffset += PtrByteSize;
4408 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4415 switch (Arg.getSimpleValueType().SimpleTy) {
4416 default: llvm_unreachable("Unexpected ValueType for argument!");
4420 if (GPR_idx != NumGPRs) {
4421 if (Arg.getValueType() == MVT::i1)
4422 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4424 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4426 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4427 isPPC64, isTailCall, false, MemOpChains,
4428 TailCallArguments, dl);
4430 ArgOffset += PtrByteSize;
4434 if (FPR_idx != NumFPRs) {
4435 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4438 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4439 MachinePointerInfo(), false, false, 0);
4440 MemOpChains.push_back(Store);
4442 // Float varargs are always shadowed in available integer registers
4443 if (GPR_idx != NumGPRs) {
4444 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4445 MachinePointerInfo(), false, false,
4447 MemOpChains.push_back(Load.getValue(1));
4448 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4450 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4451 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4452 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4453 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4454 MachinePointerInfo(),
4455 false, false, false, 0);
4456 MemOpChains.push_back(Load.getValue(1));
4457 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4460 // If we have any FPRs remaining, we may also have GPRs remaining.
4461 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4463 if (GPR_idx != NumGPRs)
4465 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4466 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4470 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4471 isPPC64, isTailCall, false, MemOpChains,
4472 TailCallArguments, dl);
4476 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4483 // These go aligned on the stack, or in the corresponding R registers
4484 // when within range. The Darwin PPC ABI doc claims they also go in
4485 // V registers; in fact gcc does this only for arguments that are
4486 // prototyped, not for those that match the ... We do it for all
4487 // arguments, seems to work.
4488 while (ArgOffset % 16 !=0) {
4489 ArgOffset += PtrByteSize;
4490 if (GPR_idx != NumGPRs)
4493 // We could elide this store in the case where the object fits
4494 // entirely in R registers. Maybe later.
4495 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4496 DAG.getConstant(ArgOffset, PtrVT));
4497 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4498 MachinePointerInfo(), false, false, 0);
4499 MemOpChains.push_back(Store);
4500 if (VR_idx != NumVRs) {
4501 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4502 MachinePointerInfo(),
4503 false, false, false, 0);
4504 MemOpChains.push_back(Load.getValue(1));
4505 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4508 for (unsigned i=0; i<16; i+=PtrByteSize) {
4509 if (GPR_idx == NumGPRs)
4511 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4512 DAG.getConstant(i, PtrVT));
4513 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4514 false, false, false, 0);
4515 MemOpChains.push_back(Load.getValue(1));
4516 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4521 // Non-varargs Altivec params generally go in registers, but have
4522 // stack space allocated at the end.
4523 if (VR_idx != NumVRs) {
4524 // Doesn't have GPR space allocated.
4525 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4526 } else if (nAltivecParamsAtEnd==0) {
4527 // We are emitting Altivec params in order.
4528 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4529 isPPC64, isTailCall, true, MemOpChains,
4530 TailCallArguments, dl);
4536 // If all Altivec parameters fit in registers, as they usually do,
4537 // they get stack space following the non-Altivec parameters. We
4538 // don't track this here because nobody below needs it.
4539 // If there are more Altivec parameters than fit in registers emit
4541 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4543 // Offset is aligned; skip 1st 12 params which go in V registers.
4544 ArgOffset = ((ArgOffset+15)/16)*16;
4546 for (unsigned i = 0; i != NumOps; ++i) {
4547 SDValue Arg = OutVals[i];
4548 EVT ArgType = Outs[i].VT;
4549 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4550 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4553 // We are emitting Altivec params in order.
4554 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4555 isPPC64, isTailCall, true, MemOpChains,
4556 TailCallArguments, dl);
4563 if (!MemOpChains.empty())
4564 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4565 &MemOpChains[0], MemOpChains.size());
4567 // On Darwin, R12 must contain the address of an indirect callee. This does
4568 // not mean the MTCTR instruction must use R12; it's easier to model this as
4569 // an extra parameter, so do that.
4571 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4572 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4573 !isBLACompatibleAddress(Callee, DAG))
4574 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4575 PPC::R12), Callee));
4577 // Build a sequence of copy-to-reg nodes chained together with token chain
4578 // and flag operands which copy the outgoing args into the appropriate regs.
4580 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4581 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4582 RegsToPass[i].second, InFlag);
4583 InFlag = Chain.getValue(1);
4587 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4588 FPOp, true, TailCallArguments);
4590 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4591 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4596 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4597 MachineFunction &MF, bool isVarArg,
4598 const SmallVectorImpl<ISD::OutputArg> &Outs,
4599 LLVMContext &Context) const {
4600 SmallVector<CCValAssign, 16> RVLocs;
4601 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4603 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4607 PPCTargetLowering::LowerReturn(SDValue Chain,
4608 CallingConv::ID CallConv, bool isVarArg,
4609 const SmallVectorImpl<ISD::OutputArg> &Outs,
4610 const SmallVectorImpl<SDValue> &OutVals,
4611 SDLoc dl, SelectionDAG &DAG) const {
4613 SmallVector<CCValAssign, 16> RVLocs;
4614 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4615 getTargetMachine(), RVLocs, *DAG.getContext());
4616 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4619 SmallVector<SDValue, 4> RetOps(1, Chain);
4621 // Copy the result values into the output registers.
4622 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4623 CCValAssign &VA = RVLocs[i];
4624 assert(VA.isRegLoc() && "Can only return in registers!");
4626 SDValue Arg = OutVals[i];
4628 switch (VA.getLocInfo()) {
4629 default: llvm_unreachable("Unknown loc info!");
4630 case CCValAssign::Full: break;
4631 case CCValAssign::AExt:
4632 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4634 case CCValAssign::ZExt:
4635 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4637 case CCValAssign::SExt:
4638 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4642 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4643 Flag = Chain.getValue(1);
4644 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4647 RetOps[0] = Chain; // Update chain.
4649 // Add the flag if we have it.
4651 RetOps.push_back(Flag);
4653 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4654 &RetOps[0], RetOps.size());
4657 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4658 const PPCSubtarget &Subtarget) const {
4659 // When we pop the dynamic allocation we need to restore the SP link.
4662 // Get the corect type for pointers.
4663 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4665 // Construct the stack pointer operand.
4666 bool isPPC64 = Subtarget.isPPC64();
4667 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4668 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4670 // Get the operands for the STACKRESTORE.
4671 SDValue Chain = Op.getOperand(0);
4672 SDValue SaveSP = Op.getOperand(1);
4674 // Load the old link SP.
4675 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4676 MachinePointerInfo(),
4677 false, false, false, 0);
4679 // Restore the stack pointer.
4680 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4682 // Store the old link SP.
4683 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4690 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4691 MachineFunction &MF = DAG.getMachineFunction();
4692 bool isPPC64 = PPCSubTarget.isPPC64();
4693 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4694 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4696 // Get current frame pointer save index. The users of this index will be
4697 // primarily DYNALLOC instructions.
4698 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4699 int RASI = FI->getReturnAddrSaveIndex();
4701 // If the frame pointer save index hasn't been defined yet.
4703 // Find out what the fix offset of the frame pointer save area.
4704 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4705 // Allocate the frame index for frame pointer save area.
4706 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4708 FI->setReturnAddrSaveIndex(RASI);
4710 return DAG.getFrameIndex(RASI, PtrVT);
4714 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4715 MachineFunction &MF = DAG.getMachineFunction();
4716 bool isPPC64 = PPCSubTarget.isPPC64();
4717 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4718 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4720 // Get current frame pointer save index. The users of this index will be
4721 // primarily DYNALLOC instructions.
4722 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4723 int FPSI = FI->getFramePointerSaveIndex();
4725 // If the frame pointer save index hasn't been defined yet.
4727 // Find out what the fix offset of the frame pointer save area.
4728 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4731 // Allocate the frame index for frame pointer save area.
4732 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4734 FI->setFramePointerSaveIndex(FPSI);
4736 return DAG.getFrameIndex(FPSI, PtrVT);
4739 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4741 const PPCSubtarget &Subtarget) const {
4743 SDValue Chain = Op.getOperand(0);
4744 SDValue Size = Op.getOperand(1);
4747 // Get the corect type for pointers.
4748 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4750 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4751 DAG.getConstant(0, PtrVT), Size);
4752 // Construct a node for the frame pointer save index.
4753 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4754 // Build a DYNALLOC node.
4755 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4756 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4757 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4760 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4761 SelectionDAG &DAG) const {
4763 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4764 DAG.getVTList(MVT::i32, MVT::Other),
4765 Op.getOperand(0), Op.getOperand(1));
4768 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4769 SelectionDAG &DAG) const {
4771 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4772 Op.getOperand(0), Op.getOperand(1));
4775 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4776 assert(Op.getValueType() == MVT::i1 &&
4777 "Custom lowering only for i1 loads");
4779 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4782 LoadSDNode *LD = cast<LoadSDNode>(Op);
4784 SDValue Chain = LD->getChain();
4785 SDValue BasePtr = LD->getBasePtr();
4786 MachineMemOperand *MMO = LD->getMemOperand();
4788 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4789 BasePtr, MVT::i8, MMO);
4790 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4792 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4793 return DAG.getMergeValues(Ops, 2, dl);
4796 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4797 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4798 "Custom lowering only for i1 stores");
4800 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4803 StoreSDNode *ST = cast<StoreSDNode>(Op);
4805 SDValue Chain = ST->getChain();
4806 SDValue BasePtr = ST->getBasePtr();
4807 SDValue Value = ST->getValue();
4808 MachineMemOperand *MMO = ST->getMemOperand();
4810 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4811 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4814 // FIXME: Remove this once the ANDI glue bug is fixed:
4815 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4816 assert(Op.getValueType() == MVT::i1 &&
4817 "Custom lowering only for i1 results");
4820 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4824 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4826 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4827 // Not FP? Not a fsel.
4828 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4829 !Op.getOperand(2).getValueType().isFloatingPoint())
4832 // We might be able to do better than this under some circumstances, but in
4833 // general, fsel-based lowering of select is a finite-math-only optimization.
4834 // For more information, see section F.3 of the 2.06 ISA specification.
4835 if (!DAG.getTarget().Options.NoInfsFPMath ||
4836 !DAG.getTarget().Options.NoNaNsFPMath)
4839 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4841 EVT ResVT = Op.getValueType();
4842 EVT CmpVT = Op.getOperand(0).getValueType();
4843 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4844 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4847 // If the RHS of the comparison is a 0.0, we don't need to do the
4848 // subtraction at all.
4850 if (isFloatingPointZero(RHS))
4852 default: break; // SETUO etc aren't handled by fsel.
4856 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4857 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4858 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4859 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4860 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4861 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4862 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4865 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4868 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4869 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4870 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4873 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4876 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4877 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4878 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4879 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4884 default: break; // SETUO etc aren't handled by fsel.
4888 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4889 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4890 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4891 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4892 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4893 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4894 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4895 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
4898 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4899 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4900 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4901 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4904 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4905 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4906 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4907 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4910 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4911 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4912 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4913 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4916 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4917 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4918 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4919 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4924 // FIXME: Split this code up when LegalizeDAGTypes lands.
4925 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4927 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4928 SDValue Src = Op.getOperand(0);
4929 if (Src.getValueType() == MVT::f32)
4930 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4933 switch (Op.getSimpleValueType().SimpleTy) {
4934 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4936 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4937 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
4942 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
4943 "i64 FP_TO_UINT is supported only with FPCVT");
4944 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
4950 // Convert the FP value to an int value through memory.
4951 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
4952 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
4953 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
4954 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
4955 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
4957 // Emit a store to the stack slot.
4960 MachineFunction &MF = DAG.getMachineFunction();
4961 MachineMemOperand *MMO =
4962 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
4963 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
4964 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
4965 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
4968 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4969 MPI, false, false, 0);
4971 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4973 if (Op.getValueType() == MVT::i32 && !i32Stack) {
4974 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4975 DAG.getConstant(4, FIPtr.getValueType()));
4976 MPI = MachinePointerInfo();
4979 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
4980 false, false, false, 0);
4983 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
4984 SelectionDAG &DAG) const {
4986 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4987 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4990 if (Op.getOperand(0).getValueType() == MVT::i1)
4991 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
4992 DAG.getConstantFP(1.0, Op.getValueType()),
4993 DAG.getConstantFP(0.0, Op.getValueType()));
4995 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
4996 "UINT_TO_FP is supported only with FPCVT");
4998 // If we have FCFIDS, then use it when converting to single-precision.
4999 // Otherwise, convert to double-precision and then round.
5000 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5001 (Op.getOpcode() == ISD::UINT_TO_FP ?
5002 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5003 (Op.getOpcode() == ISD::UINT_TO_FP ?
5004 PPCISD::FCFIDU : PPCISD::FCFID);
5005 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5006 MVT::f32 : MVT::f64;
5008 if (Op.getOperand(0).getValueType() == MVT::i64) {
5009 SDValue SINT = Op.getOperand(0);
5010 // When converting to single-precision, we actually need to convert
5011 // to double-precision first and then round to single-precision.
5012 // To avoid double-rounding effects during that operation, we have
5013 // to prepare the input operand. Bits that might be truncated when
5014 // converting to double-precision are replaced by a bit that won't
5015 // be lost at this stage, but is below the single-precision rounding
5018 // However, if -enable-unsafe-fp-math is in effect, accept double
5019 // rounding to avoid the extra overhead.
5020 if (Op.getValueType() == MVT::f32 &&
5021 !PPCSubTarget.hasFPCVT() &&
5022 !DAG.getTarget().Options.UnsafeFPMath) {
5024 // Twiddle input to make sure the low 11 bits are zero. (If this
5025 // is the case, we are guaranteed the value will fit into the 53 bit
5026 // mantissa of an IEEE double-precision value without rounding.)
5027 // If any of those low 11 bits were not zero originally, make sure
5028 // bit 12 (value 2048) is set instead, so that the final rounding
5029 // to single-precision gets the correct result.
5030 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5031 SINT, DAG.getConstant(2047, MVT::i64));
5032 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5033 Round, DAG.getConstant(2047, MVT::i64));
5034 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5035 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5036 Round, DAG.getConstant(-2048, MVT::i64));
5038 // However, we cannot use that value unconditionally: if the magnitude
5039 // of the input value is small, the bit-twiddling we did above might
5040 // end up visibly changing the output. Fortunately, in that case, we
5041 // don't need to twiddle bits since the original input will convert
5042 // exactly to double-precision floating-point already. Therefore,
5043 // construct a conditional to use the original value if the top 11
5044 // bits are all sign-bit copies, and use the rounded value computed
5046 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5047 SINT, DAG.getConstant(53, MVT::i32));
5048 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5049 Cond, DAG.getConstant(1, MVT::i64));
5050 Cond = DAG.getSetCC(dl, MVT::i32,
5051 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5053 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5056 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5057 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5059 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5060 FP = DAG.getNode(ISD::FP_ROUND, dl,
5061 MVT::f32, FP, DAG.getIntPtrConstant(0));
5065 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5066 "Unhandled INT_TO_FP type in custom expander!");
5067 // Since we only generate this in 64-bit mode, we can take advantage of
5068 // 64-bit registers. In particular, sign extend the input value into the
5069 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5070 // then lfd it and fcfid it.
5071 MachineFunction &MF = DAG.getMachineFunction();
5072 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5073 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5076 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5077 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5078 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5080 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5081 MachinePointerInfo::getFixedStack(FrameIdx),
5084 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5085 "Expected an i32 store");
5086 MachineMemOperand *MMO =
5087 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5088 MachineMemOperand::MOLoad, 4, 4);
5089 SDValue Ops[] = { Store, FIdx };
5090 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5091 PPCISD::LFIWZX : PPCISD::LFIWAX,
5092 dl, DAG.getVTList(MVT::f64, MVT::Other),
5093 Ops, 2, MVT::i32, MMO);
5095 assert(PPCSubTarget.isPPC64() &&
5096 "i32->FP without LFIWAX supported only on PPC64");
5098 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5099 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5101 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5104 // STD the extended value into the stack slot.
5105 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5106 MachinePointerInfo::getFixedStack(FrameIdx),
5109 // Load the value as a double.
5110 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5111 MachinePointerInfo::getFixedStack(FrameIdx),
5112 false, false, false, 0);
5115 // FCFID it and return it.
5116 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5117 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5118 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5122 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5123 SelectionDAG &DAG) const {
5126 The rounding mode is in bits 30:31 of FPSR, and has the following
5133 FLT_ROUNDS, on the other hand, expects the following:
5140 To perform the conversion, we do:
5141 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5144 MachineFunction &MF = DAG.getMachineFunction();
5145 EVT VT = Op.getValueType();
5146 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5147 SDValue MFFSreg, InFlag;
5149 // Save FP Control Word to register
5151 MVT::f64, // return register
5152 MVT::Glue // unused in this context
5154 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5156 // Save FP register to stack slot
5157 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5158 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5159 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5160 StackSlot, MachinePointerInfo(), false, false,0);
5162 // Load FP Control Word from low 32 bits of stack slot.
5163 SDValue Four = DAG.getConstant(4, PtrVT);
5164 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5165 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5166 false, false, false, 0);
5168 // Transform as necessary
5170 DAG.getNode(ISD::AND, dl, MVT::i32,
5171 CWD, DAG.getConstant(3, MVT::i32));
5173 DAG.getNode(ISD::SRL, dl, MVT::i32,
5174 DAG.getNode(ISD::AND, dl, MVT::i32,
5175 DAG.getNode(ISD::XOR, dl, MVT::i32,
5176 CWD, DAG.getConstant(3, MVT::i32)),
5177 DAG.getConstant(3, MVT::i32)),
5178 DAG.getConstant(1, MVT::i32));
5181 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5183 return DAG.getNode((VT.getSizeInBits() < 16 ?
5184 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5187 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5188 EVT VT = Op.getValueType();
5189 unsigned BitWidth = VT.getSizeInBits();
5191 assert(Op.getNumOperands() == 3 &&
5192 VT == Op.getOperand(1).getValueType() &&
5195 // Expand into a bunch of logical ops. Note that these ops
5196 // depend on the PPC behavior for oversized shift amounts.
5197 SDValue Lo = Op.getOperand(0);
5198 SDValue Hi = Op.getOperand(1);
5199 SDValue Amt = Op.getOperand(2);
5200 EVT AmtVT = Amt.getValueType();
5202 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5203 DAG.getConstant(BitWidth, AmtVT), Amt);
5204 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5205 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5206 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5207 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5208 DAG.getConstant(-BitWidth, AmtVT));
5209 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5210 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5211 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5212 SDValue OutOps[] = { OutLo, OutHi };
5213 return DAG.getMergeValues(OutOps, 2, dl);
5216 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5217 EVT VT = Op.getValueType();
5219 unsigned BitWidth = VT.getSizeInBits();
5220 assert(Op.getNumOperands() == 3 &&
5221 VT == Op.getOperand(1).getValueType() &&
5224 // Expand into a bunch of logical ops. Note that these ops
5225 // depend on the PPC behavior for oversized shift amounts.
5226 SDValue Lo = Op.getOperand(0);
5227 SDValue Hi = Op.getOperand(1);
5228 SDValue Amt = Op.getOperand(2);
5229 EVT AmtVT = Amt.getValueType();
5231 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5232 DAG.getConstant(BitWidth, AmtVT), Amt);
5233 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5234 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5235 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5236 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5237 DAG.getConstant(-BitWidth, AmtVT));
5238 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5239 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5240 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5241 SDValue OutOps[] = { OutLo, OutHi };
5242 return DAG.getMergeValues(OutOps, 2, dl);
5245 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5247 EVT VT = Op.getValueType();
5248 unsigned BitWidth = VT.getSizeInBits();
5249 assert(Op.getNumOperands() == 3 &&
5250 VT == Op.getOperand(1).getValueType() &&
5253 // Expand into a bunch of logical ops, followed by a select_cc.
5254 SDValue Lo = Op.getOperand(0);
5255 SDValue Hi = Op.getOperand(1);
5256 SDValue Amt = Op.getOperand(2);
5257 EVT AmtVT = Amt.getValueType();
5259 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5260 DAG.getConstant(BitWidth, AmtVT), Amt);
5261 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5262 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5263 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5264 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5265 DAG.getConstant(-BitWidth, AmtVT));
5266 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5267 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5268 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5269 Tmp4, Tmp6, ISD::SETLE);
5270 SDValue OutOps[] = { OutLo, OutHi };
5271 return DAG.getMergeValues(OutOps, 2, dl);
5274 //===----------------------------------------------------------------------===//
5275 // Vector related lowering.
5278 /// BuildSplatI - Build a canonical splati of Val with an element size of
5279 /// SplatSize. Cast the result to VT.
5280 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5281 SelectionDAG &DAG, SDLoc dl) {
5282 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5284 static const EVT VTys[] = { // canonical VT to use for each size.
5285 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5288 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5290 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5294 EVT CanonicalVT = VTys[SplatSize-1];
5296 // Build a canonical splat for this value.
5297 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5298 SmallVector<SDValue, 8> Ops;
5299 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5300 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5301 &Ops[0], Ops.size());
5302 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5305 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5306 /// specified intrinsic ID.
5307 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5308 SelectionDAG &DAG, SDLoc dl,
5309 EVT DestVT = MVT::Other) {
5310 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5311 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5312 DAG.getConstant(IID, MVT::i32), Op);
5315 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5316 /// specified intrinsic ID.
5317 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5318 SelectionDAG &DAG, SDLoc dl,
5319 EVT DestVT = MVT::Other) {
5320 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5321 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5322 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5325 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5326 /// specified intrinsic ID.
5327 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5328 SDValue Op2, SelectionDAG &DAG,
5329 SDLoc dl, EVT DestVT = MVT::Other) {
5330 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5331 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5332 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5336 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5337 /// amount. The result has the specified value type.
5338 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5339 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5340 // Force LHS/RHS to be the right type.
5341 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5342 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5345 for (unsigned i = 0; i != 16; ++i)
5347 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5348 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5351 // If this is a case we can't handle, return null and let the default
5352 // expansion code take care of it. If we CAN select this case, and if it
5353 // selects to a single instruction, return Op. Otherwise, if we can codegen
5354 // this case more efficiently than a constant pool load, lower it to the
5355 // sequence of ops that should be used.
5356 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5357 SelectionDAG &DAG) const {
5359 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5360 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5362 // Check if this is a splat of a constant value.
5363 APInt APSplatBits, APSplatUndef;
5364 unsigned SplatBitSize;
5366 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5367 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5370 unsigned SplatBits = APSplatBits.getZExtValue();
5371 unsigned SplatUndef = APSplatUndef.getZExtValue();
5372 unsigned SplatSize = SplatBitSize / 8;
5374 // First, handle single instruction cases.
5377 if (SplatBits == 0) {
5378 // Canonicalize all zero vectors to be v4i32.
5379 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5380 SDValue Z = DAG.getConstant(0, MVT::i32);
5381 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5382 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5387 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5388 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5390 if (SextVal >= -16 && SextVal <= 15)
5391 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5394 // Two instruction sequences.
5396 // If this value is in the range [-32,30] and is even, use:
5397 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5398 // If this value is in the range [17,31] and is odd, use:
5399 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5400 // If this value is in the range [-31,-17] and is odd, use:
5401 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5402 // Note the last two are three-instruction sequences.
5403 if (SextVal >= -32 && SextVal <= 31) {
5404 // To avoid having these optimizations undone by constant folding,
5405 // we convert to a pseudo that will be expanded later into one of
5407 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5408 EVT VT = Op.getValueType();
5409 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5410 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5411 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5414 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5415 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5417 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5418 // Make -1 and vspltisw -1:
5419 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5421 // Make the VSLW intrinsic, computing 0x8000_0000.
5422 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5425 // xor by OnesV to invert it.
5426 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5427 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5430 // Check to see if this is a wide variety of vsplti*, binop self cases.
5431 static const signed char SplatCsts[] = {
5432 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5433 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5436 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5437 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5438 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5439 int i = SplatCsts[idx];
5441 // Figure out what shift amount will be used by altivec if shifted by i in
5443 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5445 // vsplti + shl self.
5446 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5447 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5448 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5449 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5450 Intrinsic::ppc_altivec_vslw
5452 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5453 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5456 // vsplti + srl self.
5457 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5458 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5459 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5460 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5461 Intrinsic::ppc_altivec_vsrw
5463 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5464 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5467 // vsplti + sra self.
5468 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5469 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5470 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5471 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5472 Intrinsic::ppc_altivec_vsraw
5474 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5475 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5478 // vsplti + rol self.
5479 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5480 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5481 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5482 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5483 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5484 Intrinsic::ppc_altivec_vrlw
5486 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5487 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5490 // t = vsplti c, result = vsldoi t, t, 1
5491 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5492 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5493 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5495 // t = vsplti c, result = vsldoi t, t, 2
5496 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5497 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5498 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5500 // t = vsplti c, result = vsldoi t, t, 3
5501 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5502 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5503 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5510 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5511 /// the specified operations to build the shuffle.
5512 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5513 SDValue RHS, SelectionDAG &DAG,
5515 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5516 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5517 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5520 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5532 if (OpNum == OP_COPY) {
5533 if (LHSID == (1*9+2)*9+3) return LHS;
5534 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5538 SDValue OpLHS, OpRHS;
5539 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5540 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5544 default: llvm_unreachable("Unknown i32 permute!");
5546 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5547 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5548 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5549 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5552 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5553 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5554 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5555 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5558 for (unsigned i = 0; i != 16; ++i)
5559 ShufIdxs[i] = (i&3)+0;
5562 for (unsigned i = 0; i != 16; ++i)
5563 ShufIdxs[i] = (i&3)+4;
5566 for (unsigned i = 0; i != 16; ++i)
5567 ShufIdxs[i] = (i&3)+8;
5570 for (unsigned i = 0; i != 16; ++i)
5571 ShufIdxs[i] = (i&3)+12;
5574 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5576 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5578 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5580 EVT VT = OpLHS.getValueType();
5581 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5582 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5583 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5584 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5587 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5588 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5589 /// return the code it can be lowered into. Worst case, it can always be
5590 /// lowered into a vperm.
5591 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5592 SelectionDAG &DAG) const {
5594 SDValue V1 = Op.getOperand(0);
5595 SDValue V2 = Op.getOperand(1);
5596 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5597 EVT VT = Op.getValueType();
5599 // Cases that are handled by instructions that take permute immediates
5600 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5601 // selected by the instruction selector.
5602 if (V2.getOpcode() == ISD::UNDEF) {
5603 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5604 PPC::isSplatShuffleMask(SVOp, 2) ||
5605 PPC::isSplatShuffleMask(SVOp, 4) ||
5606 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5607 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5608 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5609 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5610 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5611 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5612 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5613 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5614 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5619 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5620 // and produce a fixed permutation. If any of these match, do not lower to
5622 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5623 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5624 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5625 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5626 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5627 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5628 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5629 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5630 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5633 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5634 // perfect shuffle table to emit an optimal matching sequence.
5635 ArrayRef<int> PermMask = SVOp->getMask();
5637 unsigned PFIndexes[4];
5638 bool isFourElementShuffle = true;
5639 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5640 unsigned EltNo = 8; // Start out undef.
5641 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5642 if (PermMask[i*4+j] < 0)
5643 continue; // Undef, ignore it.
5645 unsigned ByteSource = PermMask[i*4+j];
5646 if ((ByteSource & 3) != j) {
5647 isFourElementShuffle = false;
5652 EltNo = ByteSource/4;
5653 } else if (EltNo != ByteSource/4) {
5654 isFourElementShuffle = false;
5658 PFIndexes[i] = EltNo;
5661 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5662 // perfect shuffle vector to determine if it is cost effective to do this as
5663 // discrete instructions, or whether we should use a vperm.
5664 if (isFourElementShuffle) {
5665 // Compute the index in the perfect shuffle table.
5666 unsigned PFTableIndex =
5667 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5669 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5670 unsigned Cost = (PFEntry >> 30);
5672 // Determining when to avoid vperm is tricky. Many things affect the cost
5673 // of vperm, particularly how many times the perm mask needs to be computed.
5674 // For example, if the perm mask can be hoisted out of a loop or is already
5675 // used (perhaps because there are multiple permutes with the same shuffle
5676 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5677 // the loop requires an extra register.
5679 // As a compromise, we only emit discrete instructions if the shuffle can be
5680 // generated in 3 or fewer operations. When we have loop information
5681 // available, if this block is within a loop, we should avoid using vperm
5682 // for 3-operation perms and use a constant pool load instead.
5684 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5687 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5688 // vector that will get spilled to the constant pool.
5689 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5691 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5692 // that it is in input element units, not in bytes. Convert now.
5693 EVT EltVT = V1.getValueType().getVectorElementType();
5694 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5696 SmallVector<SDValue, 16> ResultMask;
5697 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5698 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5700 for (unsigned j = 0; j != BytesPerElement; ++j)
5701 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5705 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5706 &ResultMask[0], ResultMask.size());
5707 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5710 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5711 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5712 /// information about the intrinsic.
5713 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5715 unsigned IntrinsicID =
5716 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5719 switch (IntrinsicID) {
5720 default: return false;
5721 // Comparison predicates.
5722 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5723 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5724 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5725 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5726 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5727 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5728 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5729 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5730 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5731 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5732 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5733 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5734 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5736 // Normal Comparisons.
5737 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5738 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5739 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5740 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5741 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5742 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5743 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5744 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5745 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5746 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5747 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5748 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5749 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5754 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5755 /// lower, do it, otherwise return null.
5756 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5757 SelectionDAG &DAG) const {
5758 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5759 // opcode number of the comparison.
5763 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5764 return SDValue(); // Don't custom lower most intrinsics.
5766 // If this is a non-dot comparison, make the VCMP node and we are done.
5768 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5769 Op.getOperand(1), Op.getOperand(2),
5770 DAG.getConstant(CompareOpc, MVT::i32));
5771 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5774 // Create the PPCISD altivec 'dot' comparison node.
5776 Op.getOperand(2), // LHS
5777 Op.getOperand(3), // RHS
5778 DAG.getConstant(CompareOpc, MVT::i32)
5780 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5781 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5783 // Now that we have the comparison, emit a copy from the CR to a GPR.
5784 // This is flagged to the above dot comparison.
5785 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5786 DAG.getRegister(PPC::CR6, MVT::i32),
5787 CompNode.getValue(1));
5789 // Unpack the result based on how the target uses it.
5790 unsigned BitNo; // Bit # of CR6.
5791 bool InvertBit; // Invert result?
5792 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5793 default: // Can't happen, don't crash on invalid number though.
5794 case 0: // Return the value of the EQ bit of CR6.
5795 BitNo = 0; InvertBit = false;
5797 case 1: // Return the inverted value of the EQ bit of CR6.
5798 BitNo = 0; InvertBit = true;
5800 case 2: // Return the value of the LT bit of CR6.
5801 BitNo = 2; InvertBit = false;
5803 case 3: // Return the inverted value of the LT bit of CR6.
5804 BitNo = 2; InvertBit = true;
5808 // Shift the bit into the low position.
5809 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5810 DAG.getConstant(8-(3-BitNo), MVT::i32));
5812 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5813 DAG.getConstant(1, MVT::i32));
5815 // If we are supposed to, toggle the bit.
5817 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5818 DAG.getConstant(1, MVT::i32));
5822 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5823 SelectionDAG &DAG) const {
5825 // Create a stack slot that is 16-byte aligned.
5826 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5827 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5828 EVT PtrVT = getPointerTy();
5829 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5831 // Store the input value into Value#0 of the stack slot.
5832 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5833 Op.getOperand(0), FIdx, MachinePointerInfo(),
5836 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5837 false, false, false, 0);
5840 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5842 if (Op.getValueType() == MVT::v4i32) {
5843 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5845 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5846 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5848 SDValue RHSSwap = // = vrlw RHS, 16
5849 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5851 // Shrinkify inputs to v8i16.
5852 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5853 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5854 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5856 // Low parts multiplied together, generating 32-bit results (we ignore the
5858 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5859 LHS, RHS, DAG, dl, MVT::v4i32);
5861 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5862 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5863 // Shift the high parts up 16 bits.
5864 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5866 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5867 } else if (Op.getValueType() == MVT::v8i16) {
5868 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5870 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5872 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5873 LHS, RHS, Zero, DAG, dl);
5874 } else if (Op.getValueType() == MVT::v16i8) {
5875 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5877 // Multiply the even 8-bit parts, producing 16-bit sums.
5878 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5879 LHS, RHS, DAG, dl, MVT::v8i16);
5880 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5882 // Multiply the odd 8-bit parts, producing 16-bit sums.
5883 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5884 LHS, RHS, DAG, dl, MVT::v8i16);
5885 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5887 // Merge the results together.
5889 for (unsigned i = 0; i != 8; ++i) {
5891 Ops[i*2+1] = 2*i+1+16;
5893 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5895 llvm_unreachable("Unknown mul to lower!");
5899 /// LowerOperation - Provide custom lowering hooks for some operations.
5901 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5902 switch (Op.getOpcode()) {
5903 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5904 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5905 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5906 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5907 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5908 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5909 case ISD::SETCC: return LowerSETCC(Op, DAG);
5910 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5911 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5913 return LowerVASTART(Op, DAG, PPCSubTarget);
5916 return LowerVAARG(Op, DAG, PPCSubTarget);
5919 return LowerVACOPY(Op, DAG, PPCSubTarget);
5921 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5922 case ISD::DYNAMIC_STACKALLOC:
5923 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5925 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5926 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5928 case ISD::LOAD: return LowerLOAD(Op, DAG);
5929 case ISD::STORE: return LowerSTORE(Op, DAG);
5930 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
5931 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5932 case ISD::FP_TO_UINT:
5933 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5935 case ISD::UINT_TO_FP:
5936 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5937 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5939 // Lower 64-bit shifts.
5940 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5941 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5942 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5944 // Vector-related lowering.
5945 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5946 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5947 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5948 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5949 case ISD::MUL: return LowerMUL(Op, DAG);
5951 // For counter-based loop handling.
5952 case ISD::INTRINSIC_W_CHAIN: return SDValue();
5954 // Frame & Return address.
5955 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5956 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5960 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5961 SmallVectorImpl<SDValue>&Results,
5962 SelectionDAG &DAG) const {
5963 const TargetMachine &TM = getTargetMachine();
5965 switch (N->getOpcode()) {
5967 llvm_unreachable("Do not know how to custom type legalize this operation!");
5968 case ISD::INTRINSIC_W_CHAIN: {
5969 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
5970 Intrinsic::ppc_is_decremented_ctr_nonzero)
5973 assert(N->getValueType(0) == MVT::i1 &&
5974 "Unexpected result type for CTR decrement intrinsic");
5975 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
5976 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
5977 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
5980 Results.push_back(NewInt);
5981 Results.push_back(NewInt.getValue(1));
5985 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5986 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5989 EVT VT = N->getValueType(0);
5991 if (VT == MVT::i64) {
5992 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5994 Results.push_back(NewNode);
5995 Results.push_back(NewNode.getValue(1));
5999 case ISD::FP_ROUND_INREG: {
6000 assert(N->getValueType(0) == MVT::ppcf128);
6001 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6002 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6003 MVT::f64, N->getOperand(0),
6004 DAG.getIntPtrConstant(0));
6005 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6006 MVT::f64, N->getOperand(0),
6007 DAG.getIntPtrConstant(1));
6009 // Add the two halves of the long double in round-to-zero mode.
6010 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6012 // We know the low half is about to be thrown away, so just use something
6014 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6018 case ISD::FP_TO_SINT:
6019 // LowerFP_TO_INT() can only handle f32 and f64.
6020 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6022 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6028 //===----------------------------------------------------------------------===//
6029 // Other Lowering Code
6030 //===----------------------------------------------------------------------===//
6033 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6034 bool is64bit, unsigned BinOpcode) const {
6035 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6036 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6038 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6039 MachineFunction *F = BB->getParent();
6040 MachineFunction::iterator It = BB;
6043 unsigned dest = MI->getOperand(0).getReg();
6044 unsigned ptrA = MI->getOperand(1).getReg();
6045 unsigned ptrB = MI->getOperand(2).getReg();
6046 unsigned incr = MI->getOperand(3).getReg();
6047 DebugLoc dl = MI->getDebugLoc();
6049 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6050 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6051 F->insert(It, loopMBB);
6052 F->insert(It, exitMBB);
6053 exitMBB->splice(exitMBB->begin(), BB,
6054 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6055 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6057 MachineRegisterInfo &RegInfo = F->getRegInfo();
6058 unsigned TmpReg = (!BinOpcode) ? incr :
6059 RegInfo.createVirtualRegister(
6060 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6061 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6065 // fallthrough --> loopMBB
6066 BB->addSuccessor(loopMBB);
6069 // l[wd]arx dest, ptr
6070 // add r0, dest, incr
6071 // st[wd]cx. r0, ptr
6073 // fallthrough --> exitMBB
6075 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6076 .addReg(ptrA).addReg(ptrB);
6078 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6079 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6080 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6081 BuildMI(BB, dl, TII->get(PPC::BCC))
6082 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6083 BB->addSuccessor(loopMBB);
6084 BB->addSuccessor(exitMBB);
6093 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6094 MachineBasicBlock *BB,
6095 bool is8bit, // operation
6096 unsigned BinOpcode) const {
6097 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6098 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6099 // In 64 bit mode we have to use 64 bits for addresses, even though the
6100 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6101 // registers without caring whether they're 32 or 64, but here we're
6102 // doing actual arithmetic on the addresses.
6103 bool is64bit = PPCSubTarget.isPPC64();
6104 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6106 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6107 MachineFunction *F = BB->getParent();
6108 MachineFunction::iterator It = BB;
6111 unsigned dest = MI->getOperand(0).getReg();
6112 unsigned ptrA = MI->getOperand(1).getReg();
6113 unsigned ptrB = MI->getOperand(2).getReg();
6114 unsigned incr = MI->getOperand(3).getReg();
6115 DebugLoc dl = MI->getDebugLoc();
6117 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6118 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6119 F->insert(It, loopMBB);
6120 F->insert(It, exitMBB);
6121 exitMBB->splice(exitMBB->begin(), BB,
6122 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6123 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6125 MachineRegisterInfo &RegInfo = F->getRegInfo();
6126 const TargetRegisterClass *RC =
6127 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6128 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6129 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6130 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6131 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6132 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6133 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6134 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6135 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6136 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6137 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6138 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6139 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6141 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6145 // fallthrough --> loopMBB
6146 BB->addSuccessor(loopMBB);
6148 // The 4-byte load must be aligned, while a char or short may be
6149 // anywhere in the word. Hence all this nasty bookkeeping code.
6150 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6151 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6152 // xori shift, shift1, 24 [16]
6153 // rlwinm ptr, ptr1, 0, 0, 29
6154 // slw incr2, incr, shift
6155 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6156 // slw mask, mask2, shift
6158 // lwarx tmpDest, ptr
6159 // add tmp, tmpDest, incr2
6160 // andc tmp2, tmpDest, mask
6161 // and tmp3, tmp, mask
6162 // or tmp4, tmp3, tmp2
6165 // fallthrough --> exitMBB
6166 // srw dest, tmpDest, shift
6167 if (ptrA != ZeroReg) {
6168 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6169 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6170 .addReg(ptrA).addReg(ptrB);
6174 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6175 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6176 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6177 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6179 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6180 .addReg(Ptr1Reg).addImm(0).addImm(61);
6182 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6183 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6184 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6185 .addReg(incr).addReg(ShiftReg);
6187 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6189 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6190 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6192 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6193 .addReg(Mask2Reg).addReg(ShiftReg);
6196 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6197 .addReg(ZeroReg).addReg(PtrReg);
6199 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6200 .addReg(Incr2Reg).addReg(TmpDestReg);
6201 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6202 .addReg(TmpDestReg).addReg(MaskReg);
6203 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6204 .addReg(TmpReg).addReg(MaskReg);
6205 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6206 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6207 BuildMI(BB, dl, TII->get(PPC::STWCX))
6208 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6209 BuildMI(BB, dl, TII->get(PPC::BCC))
6210 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6211 BB->addSuccessor(loopMBB);
6212 BB->addSuccessor(exitMBB);
6217 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6222 llvm::MachineBasicBlock*
6223 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6224 MachineBasicBlock *MBB) const {
6225 DebugLoc DL = MI->getDebugLoc();
6226 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6228 MachineFunction *MF = MBB->getParent();
6229 MachineRegisterInfo &MRI = MF->getRegInfo();
6231 const BasicBlock *BB = MBB->getBasicBlock();
6232 MachineFunction::iterator I = MBB;
6236 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6237 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6239 unsigned DstReg = MI->getOperand(0).getReg();
6240 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6241 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6242 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6243 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6245 MVT PVT = getPointerTy();
6246 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6247 "Invalid Pointer Size!");
6248 // For v = setjmp(buf), we generate
6251 // SjLjSetup mainMBB
6257 // buf[LabelOffset] = LR
6261 // v = phi(main, restore)
6264 MachineBasicBlock *thisMBB = MBB;
6265 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6266 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6267 MF->insert(I, mainMBB);
6268 MF->insert(I, sinkMBB);
6270 MachineInstrBuilder MIB;
6272 // Transfer the remainder of BB and its successor edges to sinkMBB.
6273 sinkMBB->splice(sinkMBB->begin(), MBB,
6274 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6275 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6277 // Note that the structure of the jmp_buf used here is not compatible
6278 // with that used by libc, and is not designed to be. Specifically, it
6279 // stores only those 'reserved' registers that LLVM does not otherwise
6280 // understand how to spill. Also, by convention, by the time this
6281 // intrinsic is called, Clang has already stored the frame address in the
6282 // first slot of the buffer and stack address in the third. Following the
6283 // X86 target code, we'll store the jump address in the second slot. We also
6284 // need to save the TOC pointer (R2) to handle jumps between shared
6285 // libraries, and that will be stored in the fourth slot. The thread
6286 // identifier (R13) is not affected.
6289 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6290 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6291 const int64_t BPOffset = 4 * PVT.getStoreSize();
6293 // Prepare IP either in reg.
6294 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6295 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6296 unsigned BufReg = MI->getOperand(1).getReg();
6298 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6299 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6303 MIB.setMemRefs(MMOBegin, MMOEnd);
6306 // Naked functions never have a base pointer, and so we use r1. For all
6307 // other functions, this decision must be delayed until during PEI.
6309 if (MF->getFunction()->getAttributes().hasAttribute(
6310 AttributeSet::FunctionIndex, Attribute::Naked))
6311 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6313 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6315 MIB = BuildMI(*thisMBB, MI, DL,
6316 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6320 MIB.setMemRefs(MMOBegin, MMOEnd);
6323 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6324 const PPCRegisterInfo *TRI =
6325 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6326 MIB.addRegMask(TRI->getNoPreservedMask());
6328 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6330 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6332 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6334 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6335 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6339 MIB = BuildMI(mainMBB, DL,
6340 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6343 if (PPCSubTarget.isPPC64()) {
6344 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6346 .addImm(LabelOffset)
6349 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6351 .addImm(LabelOffset)
6355 MIB.setMemRefs(MMOBegin, MMOEnd);
6357 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6358 mainMBB->addSuccessor(sinkMBB);
6361 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6362 TII->get(PPC::PHI), DstReg)
6363 .addReg(mainDstReg).addMBB(mainMBB)
6364 .addReg(restoreDstReg).addMBB(thisMBB);
6366 MI->eraseFromParent();
6371 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6372 MachineBasicBlock *MBB) const {
6373 DebugLoc DL = MI->getDebugLoc();
6374 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6376 MachineFunction *MF = MBB->getParent();
6377 MachineRegisterInfo &MRI = MF->getRegInfo();
6380 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6381 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6383 MVT PVT = getPointerTy();
6384 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6385 "Invalid Pointer Size!");
6387 const TargetRegisterClass *RC =
6388 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6389 unsigned Tmp = MRI.createVirtualRegister(RC);
6390 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6391 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6392 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6393 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6395 MachineInstrBuilder MIB;
6397 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6398 const int64_t SPOffset = 2 * PVT.getStoreSize();
6399 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6400 const int64_t BPOffset = 4 * PVT.getStoreSize();
6402 unsigned BufReg = MI->getOperand(0).getReg();
6404 // Reload FP (the jumped-to function may not have had a
6405 // frame pointer, and if so, then its r31 will be restored
6407 if (PVT == MVT::i64) {
6408 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6412 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6416 MIB.setMemRefs(MMOBegin, MMOEnd);
6419 if (PVT == MVT::i64) {
6420 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6421 .addImm(LabelOffset)
6424 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6425 .addImm(LabelOffset)
6428 MIB.setMemRefs(MMOBegin, MMOEnd);
6431 if (PVT == MVT::i64) {
6432 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6436 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6440 MIB.setMemRefs(MMOBegin, MMOEnd);
6443 if (PVT == MVT::i64) {
6444 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6448 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6452 MIB.setMemRefs(MMOBegin, MMOEnd);
6455 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6456 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6460 MIB.setMemRefs(MMOBegin, MMOEnd);
6464 BuildMI(*MBB, MI, DL,
6465 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6466 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6468 MI->eraseFromParent();
6473 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6474 MachineBasicBlock *BB) const {
6475 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6476 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6477 return emitEHSjLjSetJmp(MI, BB);
6478 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6479 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6480 return emitEHSjLjLongJmp(MI, BB);
6483 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6485 // To "insert" these instructions we actually have to insert their
6486 // control-flow patterns.
6487 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6488 MachineFunction::iterator It = BB;
6491 MachineFunction *F = BB->getParent();
6493 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6494 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6495 MI->getOpcode() == PPC::SELECT_I4 ||
6496 MI->getOpcode() == PPC::SELECT_I8)) {
6497 SmallVector<MachineOperand, 2> Cond;
6498 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6499 MI->getOpcode() == PPC::SELECT_CC_I8)
6500 Cond.push_back(MI->getOperand(4));
6502 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6503 Cond.push_back(MI->getOperand(1));
6505 DebugLoc dl = MI->getDebugLoc();
6506 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6507 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6508 Cond, MI->getOperand(2).getReg(),
6509 MI->getOperand(3).getReg());
6510 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6511 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6512 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6513 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6514 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6515 MI->getOpcode() == PPC::SELECT_I4 ||
6516 MI->getOpcode() == PPC::SELECT_I8 ||
6517 MI->getOpcode() == PPC::SELECT_F4 ||
6518 MI->getOpcode() == PPC::SELECT_F8 ||
6519 MI->getOpcode() == PPC::SELECT_VRRC) {
6520 // The incoming instruction knows the destination vreg to set, the
6521 // condition code register to branch on, the true/false values to
6522 // select between, and a branch opcode to use.
6527 // cmpTY ccX, r1, r2
6529 // fallthrough --> copy0MBB
6530 MachineBasicBlock *thisMBB = BB;
6531 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6532 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6533 DebugLoc dl = MI->getDebugLoc();
6534 F->insert(It, copy0MBB);
6535 F->insert(It, sinkMBB);
6537 // Transfer the remainder of BB and its successor edges to sinkMBB.
6538 sinkMBB->splice(sinkMBB->begin(), BB,
6539 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6540 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6542 // Next, add the true and fallthrough blocks as its successors.
6543 BB->addSuccessor(copy0MBB);
6544 BB->addSuccessor(sinkMBB);
6546 if (MI->getOpcode() == PPC::SELECT_I4 ||
6547 MI->getOpcode() == PPC::SELECT_I8 ||
6548 MI->getOpcode() == PPC::SELECT_F4 ||
6549 MI->getOpcode() == PPC::SELECT_F8 ||
6550 MI->getOpcode() == PPC::SELECT_VRRC) {
6551 BuildMI(BB, dl, TII->get(PPC::BC))
6552 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6554 unsigned SelectPred = MI->getOperand(4).getImm();
6555 BuildMI(BB, dl, TII->get(PPC::BCC))
6556 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6560 // %FalseValue = ...
6561 // # fallthrough to sinkMBB
6564 // Update machine-CFG edges
6565 BB->addSuccessor(sinkMBB);
6568 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6571 BuildMI(*BB, BB->begin(), dl,
6572 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6573 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6574 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6576 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6577 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6578 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6579 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6580 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6581 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6582 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6583 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6585 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6586 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6587 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6588 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6589 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6590 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6591 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6592 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6594 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6595 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6596 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6597 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6598 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6599 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6600 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6601 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6603 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6604 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6605 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6606 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6607 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6608 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6609 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6610 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6612 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6613 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6614 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6615 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6616 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6617 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6618 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6619 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6621 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6622 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6623 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6624 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6625 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6626 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6627 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6628 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6630 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6631 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6632 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6633 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6634 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6635 BB = EmitAtomicBinary(MI, BB, false, 0);
6636 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6637 BB = EmitAtomicBinary(MI, BB, true, 0);
6639 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6640 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6641 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6643 unsigned dest = MI->getOperand(0).getReg();
6644 unsigned ptrA = MI->getOperand(1).getReg();
6645 unsigned ptrB = MI->getOperand(2).getReg();
6646 unsigned oldval = MI->getOperand(3).getReg();
6647 unsigned newval = MI->getOperand(4).getReg();
6648 DebugLoc dl = MI->getDebugLoc();
6650 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6651 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6652 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6653 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6654 F->insert(It, loop1MBB);
6655 F->insert(It, loop2MBB);
6656 F->insert(It, midMBB);
6657 F->insert(It, exitMBB);
6658 exitMBB->splice(exitMBB->begin(), BB,
6659 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6660 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6664 // fallthrough --> loopMBB
6665 BB->addSuccessor(loop1MBB);
6668 // l[wd]arx dest, ptr
6669 // cmp[wd] dest, oldval
6672 // st[wd]cx. newval, ptr
6676 // st[wd]cx. dest, ptr
6679 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6680 .addReg(ptrA).addReg(ptrB);
6681 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6682 .addReg(oldval).addReg(dest);
6683 BuildMI(BB, dl, TII->get(PPC::BCC))
6684 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6685 BB->addSuccessor(loop2MBB);
6686 BB->addSuccessor(midMBB);
6689 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6690 .addReg(newval).addReg(ptrA).addReg(ptrB);
6691 BuildMI(BB, dl, TII->get(PPC::BCC))
6692 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6693 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6694 BB->addSuccessor(loop1MBB);
6695 BB->addSuccessor(exitMBB);
6698 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6699 .addReg(dest).addReg(ptrA).addReg(ptrB);
6700 BB->addSuccessor(exitMBB);
6705 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6706 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6707 // We must use 64-bit registers for addresses when targeting 64-bit,
6708 // since we're actually doing arithmetic on them. Other registers
6710 bool is64bit = PPCSubTarget.isPPC64();
6711 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6713 unsigned dest = MI->getOperand(0).getReg();
6714 unsigned ptrA = MI->getOperand(1).getReg();
6715 unsigned ptrB = MI->getOperand(2).getReg();
6716 unsigned oldval = MI->getOperand(3).getReg();
6717 unsigned newval = MI->getOperand(4).getReg();
6718 DebugLoc dl = MI->getDebugLoc();
6720 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6721 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6722 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6723 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6724 F->insert(It, loop1MBB);
6725 F->insert(It, loop2MBB);
6726 F->insert(It, midMBB);
6727 F->insert(It, exitMBB);
6728 exitMBB->splice(exitMBB->begin(), BB,
6729 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6730 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6732 MachineRegisterInfo &RegInfo = F->getRegInfo();
6733 const TargetRegisterClass *RC =
6734 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6735 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6736 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6737 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6738 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6739 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6740 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6741 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6742 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6743 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6744 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6745 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6746 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6747 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6748 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6750 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6751 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6754 // fallthrough --> loopMBB
6755 BB->addSuccessor(loop1MBB);
6757 // The 4-byte load must be aligned, while a char or short may be
6758 // anywhere in the word. Hence all this nasty bookkeeping code.
6759 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6760 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6761 // xori shift, shift1, 24 [16]
6762 // rlwinm ptr, ptr1, 0, 0, 29
6763 // slw newval2, newval, shift
6764 // slw oldval2, oldval,shift
6765 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6766 // slw mask, mask2, shift
6767 // and newval3, newval2, mask
6768 // and oldval3, oldval2, mask
6770 // lwarx tmpDest, ptr
6771 // and tmp, tmpDest, mask
6772 // cmpw tmp, oldval3
6775 // andc tmp2, tmpDest, mask
6776 // or tmp4, tmp2, newval3
6781 // stwcx. tmpDest, ptr
6783 // srw dest, tmpDest, shift
6784 if (ptrA != ZeroReg) {
6785 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6786 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6787 .addReg(ptrA).addReg(ptrB);
6791 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6792 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6793 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6794 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6796 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6797 .addReg(Ptr1Reg).addImm(0).addImm(61);
6799 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6800 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6801 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6802 .addReg(newval).addReg(ShiftReg);
6803 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6804 .addReg(oldval).addReg(ShiftReg);
6806 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6808 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6809 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6810 .addReg(Mask3Reg).addImm(65535);
6812 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6813 .addReg(Mask2Reg).addReg(ShiftReg);
6814 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6815 .addReg(NewVal2Reg).addReg(MaskReg);
6816 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6817 .addReg(OldVal2Reg).addReg(MaskReg);
6820 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6821 .addReg(ZeroReg).addReg(PtrReg);
6822 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6823 .addReg(TmpDestReg).addReg(MaskReg);
6824 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6825 .addReg(TmpReg).addReg(OldVal3Reg);
6826 BuildMI(BB, dl, TII->get(PPC::BCC))
6827 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6828 BB->addSuccessor(loop2MBB);
6829 BB->addSuccessor(midMBB);
6832 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6833 .addReg(TmpDestReg).addReg(MaskReg);
6834 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6835 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6836 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6837 .addReg(ZeroReg).addReg(PtrReg);
6838 BuildMI(BB, dl, TII->get(PPC::BCC))
6839 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6840 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6841 BB->addSuccessor(loop1MBB);
6842 BB->addSuccessor(exitMBB);
6845 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6846 .addReg(ZeroReg).addReg(PtrReg);
6847 BB->addSuccessor(exitMBB);
6852 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6854 } else if (MI->getOpcode() == PPC::FADDrtz) {
6855 // This pseudo performs an FADD with rounding mode temporarily forced
6856 // to round-to-zero. We emit this via custom inserter since the FPSCR
6857 // is not modeled at the SelectionDAG level.
6858 unsigned Dest = MI->getOperand(0).getReg();
6859 unsigned Src1 = MI->getOperand(1).getReg();
6860 unsigned Src2 = MI->getOperand(2).getReg();
6861 DebugLoc dl = MI->getDebugLoc();
6863 MachineRegisterInfo &RegInfo = F->getRegInfo();
6864 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6866 // Save FPSCR value.
6867 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6869 // Set rounding mode to round-to-zero.
6870 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6871 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6873 // Perform addition.
6874 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6876 // Restore FPSCR value.
6877 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6878 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6879 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
6880 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6881 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
6882 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6883 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
6884 PPC::ANDIo8 : PPC::ANDIo;
6885 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6886 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
6888 MachineRegisterInfo &RegInfo = F->getRegInfo();
6889 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
6890 &PPC::GPRCRegClass :
6891 &PPC::G8RCRegClass);
6893 DebugLoc dl = MI->getDebugLoc();
6894 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
6895 .addReg(MI->getOperand(1).getReg()).addImm(1);
6896 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
6897 MI->getOperand(0).getReg())
6898 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
6900 llvm_unreachable("Unexpected instr type to insert");
6903 MI->eraseFromParent(); // The pseudo instruction is gone now.
6907 //===----------------------------------------------------------------------===//
6908 // Target Optimization Hooks
6909 //===----------------------------------------------------------------------===//
6911 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6912 DAGCombinerInfo &DCI) const {
6913 if (DCI.isAfterLegalizeVectorOps())
6916 EVT VT = Op.getValueType();
6918 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6919 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6920 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6922 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6923 // For the reciprocal, we need to find the zero of the function:
6924 // F(X) = A X - 1 [which has a zero at X = 1/A]
6926 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
6927 // does not require additional intermediate precision]
6929 // Convergence is quadratic, so we essentially double the number of digits
6930 // correct after every iteration. The minimum architected relative
6931 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6932 // 23 digits and double has 52 digits.
6933 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6934 if (VT.getScalarType() == MVT::f64)
6937 SelectionDAG &DAG = DCI.DAG;
6941 DAG.getConstantFP(1.0, VT.getScalarType());
6942 if (VT.isVector()) {
6943 assert(VT.getVectorNumElements() == 4 &&
6944 "Unknown vector type");
6945 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6946 FPOne, FPOne, FPOne, FPOne);
6949 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
6950 DCI.AddToWorklist(Est.getNode());
6952 // Newton iterations: Est = Est + Est (1 - Arg * Est)
6953 for (int i = 0; i < Iterations; ++i) {
6954 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
6955 DCI.AddToWorklist(NewEst.getNode());
6957 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
6958 DCI.AddToWorklist(NewEst.getNode());
6960 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6961 DCI.AddToWorklist(NewEst.getNode());
6963 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
6964 DCI.AddToWorklist(Est.getNode());
6973 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
6974 DAGCombinerInfo &DCI) const {
6975 if (DCI.isAfterLegalizeVectorOps())
6978 EVT VT = Op.getValueType();
6980 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
6981 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
6982 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6984 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6985 // For the reciprocal sqrt, we need to find the zero of the function:
6986 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
6988 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
6989 // As a result, we precompute A/2 prior to the iteration loop.
6991 // Convergence is quadratic, so we essentially double the number of digits
6992 // correct after every iteration. The minimum architected relative
6993 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6994 // 23 digits and double has 52 digits.
6995 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6996 if (VT.getScalarType() == MVT::f64)
6999 SelectionDAG &DAG = DCI.DAG;
7002 SDValue FPThreeHalves =
7003 DAG.getConstantFP(1.5, VT.getScalarType());
7004 if (VT.isVector()) {
7005 assert(VT.getVectorNumElements() == 4 &&
7006 "Unknown vector type");
7007 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7008 FPThreeHalves, FPThreeHalves,
7009 FPThreeHalves, FPThreeHalves);
7012 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7013 DCI.AddToWorklist(Est.getNode());
7015 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7016 // this entire sequence requires only one FP constant.
7017 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7018 DCI.AddToWorklist(HalfArg.getNode());
7020 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7021 DCI.AddToWorklist(HalfArg.getNode());
7023 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7024 for (int i = 0; i < Iterations; ++i) {
7025 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7026 DCI.AddToWorklist(NewEst.getNode());
7028 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7029 DCI.AddToWorklist(NewEst.getNode());
7031 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7032 DCI.AddToWorklist(NewEst.getNode());
7034 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7035 DCI.AddToWorklist(Est.getNode());
7044 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7045 // not enforce equality of the chain operands.
7046 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7047 unsigned Bytes, int Dist,
7048 SelectionDAG &DAG) {
7049 EVT VT = LS->getMemoryVT();
7050 if (VT.getSizeInBits() / 8 != Bytes)
7053 SDValue Loc = LS->getBasePtr();
7054 SDValue BaseLoc = Base->getBasePtr();
7055 if (Loc.getOpcode() == ISD::FrameIndex) {
7056 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7058 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7059 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7060 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7061 int FS = MFI->getObjectSize(FI);
7062 int BFS = MFI->getObjectSize(BFI);
7063 if (FS != BFS || FS != (int)Bytes) return false;
7064 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7068 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7069 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7072 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7073 const GlobalValue *GV1 = NULL;
7074 const GlobalValue *GV2 = NULL;
7075 int64_t Offset1 = 0;
7076 int64_t Offset2 = 0;
7077 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7078 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7079 if (isGA1 && isGA2 && GV1 == GV2)
7080 return Offset1 == (Offset2 + Dist*Bytes);
7084 // Return true is there is a nearyby consecutive load to the one provided
7085 // (regardless of alignment). We search up and down the chain, looking though
7086 // token factors and other loads (but nothing else). As a result, a true
7087 // results indicates that it is safe to create a new consecutive load adjacent
7088 // to the load provided.
7089 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7090 SDValue Chain = LD->getChain();
7091 EVT VT = LD->getMemoryVT();
7093 SmallSet<SDNode *, 16> LoadRoots;
7094 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7095 SmallSet<SDNode *, 16> Visited;
7097 // First, search up the chain, branching to follow all token-factor operands.
7098 // If we find a consecutive load, then we're done, otherwise, record all
7099 // nodes just above the top-level loads and token factors.
7100 while (!Queue.empty()) {
7101 SDNode *ChainNext = Queue.pop_back_val();
7102 if (!Visited.insert(ChainNext))
7105 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7106 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7109 if (!Visited.count(ChainLD->getChain().getNode()))
7110 Queue.push_back(ChainLD->getChain().getNode());
7111 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7112 for (SDNode::op_iterator O = ChainNext->op_begin(),
7113 OE = ChainNext->op_end(); O != OE; ++O)
7114 if (!Visited.count(O->getNode()))
7115 Queue.push_back(O->getNode());
7117 LoadRoots.insert(ChainNext);
7120 // Second, search down the chain, starting from the top-level nodes recorded
7121 // in the first phase. These top-level nodes are the nodes just above all
7122 // loads and token factors. Starting with their uses, recursively look though
7123 // all loads (just the chain uses) and token factors to find a consecutive
7128 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7129 IE = LoadRoots.end(); I != IE; ++I) {
7130 Queue.push_back(*I);
7132 while (!Queue.empty()) {
7133 SDNode *LoadRoot = Queue.pop_back_val();
7134 if (!Visited.insert(LoadRoot))
7137 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7138 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7141 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7142 UE = LoadRoot->use_end(); UI != UE; ++UI)
7143 if (((isa<LoadSDNode>(*UI) &&
7144 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7145 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7146 Queue.push_back(*UI);
7153 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7154 DAGCombinerInfo &DCI) const {
7155 SelectionDAG &DAG = DCI.DAG;
7158 assert(PPCSubTarget.useCRBits() &&
7159 "Expecting to be tracking CR bits");
7160 // If we're tracking CR bits, we need to be careful that we don't have:
7161 // trunc(binary-ops(zext(x), zext(y)))
7163 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7164 // such that we're unnecessarily moving things into GPRs when it would be
7165 // better to keep them in CR bits.
7167 // Note that trunc here can be an actual i1 trunc, or can be the effective
7168 // truncation that comes from a setcc or select_cc.
7169 if (N->getOpcode() == ISD::TRUNCATE &&
7170 N->getValueType(0) != MVT::i1)
7173 if (N->getOperand(0).getValueType() != MVT::i32 &&
7174 N->getOperand(0).getValueType() != MVT::i64)
7177 if (N->getOpcode() == ISD::SETCC ||
7178 N->getOpcode() == ISD::SELECT_CC) {
7179 // If we're looking at a comparison, then we need to make sure that the
7180 // high bits (all except for the first) don't matter the result.
7182 cast<CondCodeSDNode>(N->getOperand(
7183 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7184 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7186 if (ISD::isSignedIntSetCC(CC)) {
7187 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7188 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7190 } else if (ISD::isUnsignedIntSetCC(CC)) {
7191 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7192 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7193 !DAG.MaskedValueIsZero(N->getOperand(1),
7194 APInt::getHighBitsSet(OpBits, OpBits-1)))
7197 // This is neither a signed nor an unsigned comparison, just make sure
7198 // that the high bits are equal.
7199 APInt Op1Zero, Op1One;
7200 APInt Op2Zero, Op2One;
7201 DAG.ComputeMaskedBits(N->getOperand(0), Op1Zero, Op1One);
7202 DAG.ComputeMaskedBits(N->getOperand(1), Op2Zero, Op2One);
7204 // We don't really care about what is known about the first bit (if
7205 // anything), so clear it in all masks prior to comparing them.
7206 Op1Zero.clearBit(0); Op1One.clearBit(0);
7207 Op2Zero.clearBit(0); Op2One.clearBit(0);
7209 if (Op1Zero != Op2Zero || Op1One != Op2One)
7214 // We now know that the higher-order bits are irrelevant, we just need to
7215 // make sure that all of the intermediate operations are bit operations, and
7216 // all inputs are extensions.
7217 if (N->getOperand(0).getOpcode() != ISD::AND &&
7218 N->getOperand(0).getOpcode() != ISD::OR &&
7219 N->getOperand(0).getOpcode() != ISD::XOR &&
7220 N->getOperand(0).getOpcode() != ISD::SELECT &&
7221 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7222 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7223 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7224 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7225 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7228 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7229 N->getOperand(1).getOpcode() != ISD::AND &&
7230 N->getOperand(1).getOpcode() != ISD::OR &&
7231 N->getOperand(1).getOpcode() != ISD::XOR &&
7232 N->getOperand(1).getOpcode() != ISD::SELECT &&
7233 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7234 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7235 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7236 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7237 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7240 SmallVector<SDValue, 4> Inputs;
7241 SmallVector<SDValue, 8> BinOps, PromOps;
7242 SmallPtrSet<SDNode *, 16> Visited;
7244 for (unsigned i = 0; i < 2; ++i) {
7245 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7246 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7247 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7248 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7249 isa<ConstantSDNode>(N->getOperand(i)))
7250 Inputs.push_back(N->getOperand(i));
7252 BinOps.push_back(N->getOperand(i));
7254 if (N->getOpcode() == ISD::TRUNCATE)
7258 // Visit all inputs, collect all binary operations (and, or, xor and
7259 // select) that are all fed by extensions.
7260 while (!BinOps.empty()) {
7261 SDValue BinOp = BinOps.back();
7264 if (!Visited.insert(BinOp.getNode()))
7267 PromOps.push_back(BinOp);
7269 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7270 // The condition of the select is not promoted.
7271 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7273 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7276 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7277 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7278 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7279 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7280 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7281 Inputs.push_back(BinOp.getOperand(i));
7282 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7283 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7284 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7285 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7286 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7287 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7288 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7289 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7290 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7291 BinOps.push_back(BinOp.getOperand(i));
7293 // We have an input that is not an extension or another binary
7294 // operation; we'll abort this transformation.
7300 // Make sure that this is a self-contained cluster of operations (which
7301 // is not quite the same thing as saying that everything has only one
7303 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7304 if (isa<ConstantSDNode>(Inputs[i]))
7307 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7308 UE = Inputs[i].getNode()->use_end();
7311 if (User != N && !Visited.count(User))
7314 // Make sure that we're not going to promote the non-output-value
7315 // operand(s) or SELECT or SELECT_CC.
7316 // FIXME: Although we could sometimes handle this, and it does occur in
7317 // practice that one of the condition inputs to the select is also one of
7318 // the outputs, we currently can't deal with this.
7319 if (User->getOpcode() == ISD::SELECT) {
7320 if (User->getOperand(0) == Inputs[i])
7322 } else if (User->getOpcode() == ISD::SELECT_CC) {
7323 if (User->getOperand(0) == Inputs[i] ||
7324 User->getOperand(1) == Inputs[i])
7330 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7331 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7332 UE = PromOps[i].getNode()->use_end();
7335 if (User != N && !Visited.count(User))
7338 // Make sure that we're not going to promote the non-output-value
7339 // operand(s) or SELECT or SELECT_CC.
7340 // FIXME: Although we could sometimes handle this, and it does occur in
7341 // practice that one of the condition inputs to the select is also one of
7342 // the outputs, we currently can't deal with this.
7343 if (User->getOpcode() == ISD::SELECT) {
7344 if (User->getOperand(0) == PromOps[i])
7346 } else if (User->getOpcode() == ISD::SELECT_CC) {
7347 if (User->getOperand(0) == PromOps[i] ||
7348 User->getOperand(1) == PromOps[i])
7354 // Replace all inputs with the extension operand.
7355 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7356 // Constants may have users outside the cluster of to-be-promoted nodes,
7357 // and so we need to replace those as we do the promotions.
7358 if (isa<ConstantSDNode>(Inputs[i]))
7361 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7364 // Replace all operations (these are all the same, but have a different
7365 // (i1) return type). DAG.getNode will validate that the types of
7366 // a binary operator match, so go through the list in reverse so that
7367 // we've likely promoted both operands first. Any intermediate truncations or
7368 // extensions disappear.
7369 while (!PromOps.empty()) {
7370 SDValue PromOp = PromOps.back();
7373 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7374 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7375 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7376 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7377 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7378 PromOp.getOperand(0).getValueType() != MVT::i1) {
7379 // The operand is not yet ready (see comment below).
7380 PromOps.insert(PromOps.begin(), PromOp);
7384 SDValue RepValue = PromOp.getOperand(0);
7385 if (isa<ConstantSDNode>(RepValue))
7386 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7388 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7393 switch (PromOp.getOpcode()) {
7394 default: C = 0; break;
7395 case ISD::SELECT: C = 1; break;
7396 case ISD::SELECT_CC: C = 2; break;
7399 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7400 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7401 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7402 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7403 // The to-be-promoted operands of this node have not yet been
7404 // promoted (this should be rare because we're going through the
7405 // list backward, but if one of the operands has several users in
7406 // this cluster of to-be-promoted nodes, it is possible).
7407 PromOps.insert(PromOps.begin(), PromOp);
7411 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7412 PromOp.getNode()->op_end());
7414 // If there are any constant inputs, make sure they're replaced now.
7415 for (unsigned i = 0; i < 2; ++i)
7416 if (isa<ConstantSDNode>(Ops[C+i]))
7417 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7419 DAG.ReplaceAllUsesOfValueWith(PromOp,
7420 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1,
7421 Ops.data(), Ops.size()));
7424 // Now we're left with the initial truncation itself.
7425 if (N->getOpcode() == ISD::TRUNCATE)
7426 return N->getOperand(0);
7428 // Otherwise, this is a comparison. The operands to be compared have just
7429 // changed type (to i1), but everything else is the same.
7430 return SDValue(N, 0);
7433 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7434 DAGCombinerInfo &DCI) const {
7435 SelectionDAG &DAG = DCI.DAG;
7438 // If we're tracking CR bits, we need to be careful that we don't have:
7439 // zext(binary-ops(trunc(x), trunc(y)))
7441 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7442 // such that we're unnecessarily moving things into CR bits that can more
7443 // efficiently stay in GPRs. Note that if we're not certain that the high
7444 // bits are set as required by the final extension, we still may need to do
7445 // some masking to get the proper behavior.
7447 // This same functionality is important on PPC64 when dealing with
7448 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7449 // the return values of functions. Because it is so similar, it is handled
7452 if (N->getValueType(0) != MVT::i32 &&
7453 N->getValueType(0) != MVT::i64)
7456 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7457 PPCSubTarget.useCRBits()) ||
7458 (N->getOperand(0).getValueType() == MVT::i32 &&
7459 PPCSubTarget.isPPC64())))
7462 if (N->getOperand(0).getOpcode() != ISD::AND &&
7463 N->getOperand(0).getOpcode() != ISD::OR &&
7464 N->getOperand(0).getOpcode() != ISD::XOR &&
7465 N->getOperand(0).getOpcode() != ISD::SELECT &&
7466 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7469 SmallVector<SDValue, 4> Inputs;
7470 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7471 SmallPtrSet<SDNode *, 16> Visited;
7473 // Visit all inputs, collect all binary operations (and, or, xor and
7474 // select) that are all fed by truncations.
7475 while (!BinOps.empty()) {
7476 SDValue BinOp = BinOps.back();
7479 if (!Visited.insert(BinOp.getNode()))
7482 PromOps.push_back(BinOp);
7484 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7485 // The condition of the select is not promoted.
7486 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7488 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7491 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7492 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7493 Inputs.push_back(BinOp.getOperand(i));
7494 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7495 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7496 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7497 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7498 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7499 BinOps.push_back(BinOp.getOperand(i));
7501 // We have an input that is not a truncation or another binary
7502 // operation; we'll abort this transformation.
7508 // Make sure that this is a self-contained cluster of operations (which
7509 // is not quite the same thing as saying that everything has only one
7511 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7512 if (isa<ConstantSDNode>(Inputs[i]))
7515 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7516 UE = Inputs[i].getNode()->use_end();
7519 if (User != N && !Visited.count(User))
7522 // Make sure that we're not going to promote the non-output-value
7523 // operand(s) or SELECT or SELECT_CC.
7524 // FIXME: Although we could sometimes handle this, and it does occur in
7525 // practice that one of the condition inputs to the select is also one of
7526 // the outputs, we currently can't deal with this.
7527 if (User->getOpcode() == ISD::SELECT) {
7528 if (User->getOperand(0) == Inputs[i])
7530 } else if (User->getOpcode() == ISD::SELECT_CC) {
7531 if (User->getOperand(0) == Inputs[i] ||
7532 User->getOperand(1) == Inputs[i])
7538 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7539 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7540 UE = PromOps[i].getNode()->use_end();
7543 if (User != N && !Visited.count(User))
7546 // Make sure that we're not going to promote the non-output-value
7547 // operand(s) or SELECT or SELECT_CC.
7548 // FIXME: Although we could sometimes handle this, and it does occur in
7549 // practice that one of the condition inputs to the select is also one of
7550 // the outputs, we currently can't deal with this.
7551 if (User->getOpcode() == ISD::SELECT) {
7552 if (User->getOperand(0) == PromOps[i])
7554 } else if (User->getOpcode() == ISD::SELECT_CC) {
7555 if (User->getOperand(0) == PromOps[i] ||
7556 User->getOperand(1) == PromOps[i])
7562 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7563 bool ReallyNeedsExt = false;
7564 if (N->getOpcode() != ISD::ANY_EXTEND) {
7565 // If all of the inputs are not already sign/zero extended, then
7566 // we'll still need to do that at the end.
7567 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7568 if (isa<ConstantSDNode>(Inputs[i]))
7572 Inputs[i].getOperand(0).getValueSizeInBits();
7573 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7575 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7576 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7577 APInt::getHighBitsSet(OpBits,
7578 OpBits-PromBits))) ||
7579 (N->getOpcode() == ISD::SIGN_EXTEND &&
7580 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7581 (OpBits-(PromBits-1)))) {
7582 ReallyNeedsExt = true;
7588 // Replace all inputs, either with the truncation operand, or a
7589 // truncation or extension to the final output type.
7590 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7591 // Constant inputs need to be replaced with the to-be-promoted nodes that
7592 // use them because they might have users outside of the cluster of
7594 if (isa<ConstantSDNode>(Inputs[i]))
7597 SDValue InSrc = Inputs[i].getOperand(0);
7598 if (Inputs[i].getValueType() == N->getValueType(0))
7599 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7600 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7601 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7602 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7603 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7604 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7605 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7607 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7608 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7611 // Replace all operations (these are all the same, but have a different
7612 // (promoted) return type). DAG.getNode will validate that the types of
7613 // a binary operator match, so go through the list in reverse so that
7614 // we've likely promoted both operands first.
7615 while (!PromOps.empty()) {
7616 SDValue PromOp = PromOps.back();
7620 switch (PromOp.getOpcode()) {
7621 default: C = 0; break;
7622 case ISD::SELECT: C = 1; break;
7623 case ISD::SELECT_CC: C = 2; break;
7626 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7627 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7628 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7629 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7630 // The to-be-promoted operands of this node have not yet been
7631 // promoted (this should be rare because we're going through the
7632 // list backward, but if one of the operands has several users in
7633 // this cluster of to-be-promoted nodes, it is possible).
7634 PromOps.insert(PromOps.begin(), PromOp);
7638 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7639 PromOp.getNode()->op_end());
7641 // If this node has constant inputs, then they'll need to be promoted here.
7642 for (unsigned i = 0; i < 2; ++i) {
7643 if (!isa<ConstantSDNode>(Ops[C+i]))
7645 if (Ops[C+i].getValueType() == N->getValueType(0))
7648 if (N->getOpcode() == ISD::SIGN_EXTEND)
7649 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7650 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7651 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7653 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7656 DAG.ReplaceAllUsesOfValueWith(PromOp,
7657 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0),
7658 Ops.data(), Ops.size()));
7661 // Now we're left with the initial extension itself.
7662 if (!ReallyNeedsExt)
7663 return N->getOperand(0);
7665 // To zero extend, just mask off everything except for the first bit (in the
7667 if (N->getOpcode() == ISD::ZERO_EXTEND)
7668 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7669 DAG.getConstant(APInt::getLowBitsSet(
7670 N->getValueSizeInBits(0), PromBits),
7671 N->getValueType(0)));
7673 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7674 "Invalid extension type");
7675 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7677 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7678 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7679 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7680 N->getOperand(0), ShiftCst), ShiftCst);
7683 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7684 DAGCombinerInfo &DCI) const {
7685 const TargetMachine &TM = getTargetMachine();
7686 SelectionDAG &DAG = DCI.DAG;
7688 switch (N->getOpcode()) {
7691 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7692 if (C->isNullValue()) // 0 << V -> 0.
7693 return N->getOperand(0);
7697 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7698 if (C->isNullValue()) // 0 >>u V -> 0.
7699 return N->getOperand(0);
7703 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7704 if (C->isNullValue() || // 0 >>s V -> 0.
7705 C->isAllOnesValue()) // -1 >>s V -> -1.
7706 return N->getOperand(0);
7709 case ISD::SIGN_EXTEND:
7710 case ISD::ZERO_EXTEND:
7711 case ISD::ANY_EXTEND:
7712 return DAGCombineExtBoolTrunc(N, DCI);
7715 case ISD::SELECT_CC:
7716 return DAGCombineTruncBoolExt(N, DCI);
7718 assert(TM.Options.UnsafeFPMath &&
7719 "Reciprocal estimates require UnsafeFPMath");
7721 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7723 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7724 if (RV.getNode() != 0) {
7725 DCI.AddToWorklist(RV.getNode());
7726 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7727 N->getOperand(0), RV);
7729 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7730 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7732 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7734 if (RV.getNode() != 0) {
7735 DCI.AddToWorklist(RV.getNode());
7736 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7737 N->getValueType(0), RV);
7738 DCI.AddToWorklist(RV.getNode());
7739 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7740 N->getOperand(0), RV);
7742 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7743 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7745 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7747 if (RV.getNode() != 0) {
7748 DCI.AddToWorklist(RV.getNode());
7749 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7750 N->getValueType(0), RV,
7751 N->getOperand(1).getOperand(1));
7752 DCI.AddToWorklist(RV.getNode());
7753 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7754 N->getOperand(0), RV);
7758 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7759 if (RV.getNode() != 0) {
7760 DCI.AddToWorklist(RV.getNode());
7761 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7762 N->getOperand(0), RV);
7768 assert(TM.Options.UnsafeFPMath &&
7769 "Reciprocal estimates require UnsafeFPMath");
7771 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7773 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7774 if (RV.getNode() != 0) {
7775 DCI.AddToWorklist(RV.getNode());
7776 RV = DAGCombineFastRecip(RV, DCI);
7777 if (RV.getNode() != 0) {
7778 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7779 // this case and force the answer to 0.
7781 EVT VT = RV.getValueType();
7783 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7784 if (VT.isVector()) {
7785 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7786 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7790 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7791 N->getOperand(0), Zero, ISD::SETEQ);
7792 DCI.AddToWorklist(ZeroCmp.getNode());
7793 DCI.AddToWorklist(RV.getNode());
7795 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7803 case ISD::SINT_TO_FP:
7804 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7805 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7806 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7807 // We allow the src/dst to be either f32/f64, but the intermediate
7808 // type must be i64.
7809 if (N->getOperand(0).getValueType() == MVT::i64 &&
7810 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7811 SDValue Val = N->getOperand(0).getOperand(0);
7812 if (Val.getValueType() == MVT::f32) {
7813 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7814 DCI.AddToWorklist(Val.getNode());
7817 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7818 DCI.AddToWorklist(Val.getNode());
7819 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7820 DCI.AddToWorklist(Val.getNode());
7821 if (N->getValueType(0) == MVT::f32) {
7822 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7823 DAG.getIntPtrConstant(0));
7824 DCI.AddToWorklist(Val.getNode());
7827 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7828 // If the intermediate type is i32, we can avoid the load/store here
7835 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7836 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7837 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7838 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7839 N->getOperand(1).getValueType() == MVT::i32 &&
7840 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7841 SDValue Val = N->getOperand(1).getOperand(0);
7842 if (Val.getValueType() == MVT::f32) {
7843 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7844 DCI.AddToWorklist(Val.getNode());
7846 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7847 DCI.AddToWorklist(Val.getNode());
7850 N->getOperand(0), Val, N->getOperand(2),
7851 DAG.getValueType(N->getOperand(1).getValueType())
7854 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7855 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7856 cast<StoreSDNode>(N)->getMemoryVT(),
7857 cast<StoreSDNode>(N)->getMemOperand());
7858 DCI.AddToWorklist(Val.getNode());
7862 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7863 if (cast<StoreSDNode>(N)->isUnindexed() &&
7864 N->getOperand(1).getOpcode() == ISD::BSWAP &&
7865 N->getOperand(1).getNode()->hasOneUse() &&
7866 (N->getOperand(1).getValueType() == MVT::i32 ||
7867 N->getOperand(1).getValueType() == MVT::i16 ||
7868 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7869 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7870 N->getOperand(1).getValueType() == MVT::i64))) {
7871 SDValue BSwapOp = N->getOperand(1).getOperand(0);
7872 // Do an any-extend to 32-bits if this is a half-word input.
7873 if (BSwapOp.getValueType() == MVT::i16)
7874 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7877 N->getOperand(0), BSwapOp, N->getOperand(2),
7878 DAG.getValueType(N->getOperand(1).getValueType())
7881 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7882 Ops, array_lengthof(Ops),
7883 cast<StoreSDNode>(N)->getMemoryVT(),
7884 cast<StoreSDNode>(N)->getMemOperand());
7888 LoadSDNode *LD = cast<LoadSDNode>(N);
7889 EVT VT = LD->getValueType(0);
7890 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
7891 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
7892 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
7893 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
7894 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
7895 VT == MVT::v4i32 || VT == MVT::v4f32) &&
7896 LD->getAlignment() < ABIAlignment) {
7897 // This is a type-legal unaligned Altivec load.
7898 SDValue Chain = LD->getChain();
7899 SDValue Ptr = LD->getBasePtr();
7901 // This implements the loading of unaligned vectors as described in
7902 // the venerable Apple Velocity Engine overview. Specifically:
7903 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
7904 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
7906 // The general idea is to expand a sequence of one or more unaligned
7907 // loads into a alignment-based permutation-control instruction (lvsl),
7908 // a series of regular vector loads (which always truncate their
7909 // input address to an aligned address), and a series of permutations.
7910 // The results of these permutations are the requested loaded values.
7911 // The trick is that the last "extra" load is not taken from the address
7912 // you might suspect (sizeof(vector) bytes after the last requested
7913 // load), but rather sizeof(vector) - 1 bytes after the last
7914 // requested vector. The point of this is to avoid a page fault if the
7915 // base address happened to be aligned. This works because if the base
7916 // address is aligned, then adding less than a full vector length will
7917 // cause the last vector in the sequence to be (re)loaded. Otherwise,
7918 // the next vector will be fetched as you might suspect was necessary.
7920 // We might be able to reuse the permutation generation from
7921 // a different base address offset from this one by an aligned amount.
7922 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
7923 // optimization later.
7924 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
7925 DAG, dl, MVT::v16i8);
7927 // Refine the alignment of the original load (a "new" load created here
7928 // which was identical to the first except for the alignment would be
7929 // merged with the existing node regardless).
7930 MachineFunction &MF = DAG.getMachineFunction();
7931 MachineMemOperand *MMO =
7932 MF.getMachineMemOperand(LD->getPointerInfo(),
7933 LD->getMemOperand()->getFlags(),
7934 LD->getMemoryVT().getStoreSize(),
7936 LD->refineAlignment(MMO);
7937 SDValue BaseLoad = SDValue(LD, 0);
7939 // Note that the value of IncOffset (which is provided to the next
7940 // load's pointer info offset value, and thus used to calculate the
7941 // alignment), and the value of IncValue (which is actually used to
7942 // increment the pointer value) are different! This is because we
7943 // require the next load to appear to be aligned, even though it
7944 // is actually offset from the base pointer by a lesser amount.
7945 int IncOffset = VT.getSizeInBits() / 8;
7946 int IncValue = IncOffset;
7948 // Walk (both up and down) the chain looking for another load at the real
7949 // (aligned) offset (the alignment of the other load does not matter in
7950 // this case). If found, then do not use the offset reduction trick, as
7951 // that will prevent the loads from being later combined (as they would
7952 // otherwise be duplicates).
7953 if (!findConsecutiveLoad(LD, DAG))
7956 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
7957 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
7960 DAG.getLoad(VT, dl, Chain, Ptr,
7961 LD->getPointerInfo().getWithOffset(IncOffset),
7962 LD->isVolatile(), LD->isNonTemporal(),
7963 LD->isInvariant(), ABIAlignment);
7965 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7966 BaseLoad.getValue(1), ExtraLoad.getValue(1));
7968 if (BaseLoad.getValueType() != MVT::v4i32)
7969 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
7971 if (ExtraLoad.getValueType() != MVT::v4i32)
7972 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
7974 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
7975 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
7977 if (VT != MVT::v4i32)
7978 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
7980 // Now we need to be really careful about how we update the users of the
7981 // original load. We cannot just call DCI.CombineTo (or
7982 // DAG.ReplaceAllUsesWith for that matter), because the load still has
7983 // uses created here (the permutation for example) that need to stay.
7984 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7986 SDUse &Use = UI.getUse();
7988 // Note: BaseLoad is checked here because it might not be N, but a
7990 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
7991 User == TF.getNode() || Use.getResNo() > 1) {
7996 SDValue To = Use.getResNo() ? TF : Perm;
7999 SmallVector<SDValue, 8> Ops;
8000 for (SDNode::op_iterator O = User->op_begin(),
8001 OE = User->op_end(); O != OE; ++O) {
8008 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
8011 return SDValue(N, 0);
8015 case ISD::INTRINSIC_WO_CHAIN:
8016 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8017 Intrinsic::ppc_altivec_lvsl &&
8018 N->getOperand(1)->getOpcode() == ISD::ADD) {
8019 SDValue Add = N->getOperand(1);
8021 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8022 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8023 Add.getValueType().getScalarType().getSizeInBits()))) {
8024 SDNode *BasePtr = Add->getOperand(0).getNode();
8025 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8026 UE = BasePtr->use_end(); UI != UE; ++UI) {
8027 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8028 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8029 Intrinsic::ppc_altivec_lvsl) {
8030 // We've found another LVSL, and this address if an aligned
8031 // multiple of that one. The results will be the same, so use the
8032 // one we've just found instead.
8034 return SDValue(*UI, 0);
8042 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8043 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8044 N->getOperand(0).hasOneUse() &&
8045 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8046 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8047 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8048 N->getValueType(0) == MVT::i64))) {
8049 SDValue Load = N->getOperand(0);
8050 LoadSDNode *LD = cast<LoadSDNode>(Load);
8051 // Create the byte-swapping load.
8053 LD->getChain(), // Chain
8054 LD->getBasePtr(), // Ptr
8055 DAG.getValueType(N->getValueType(0)) // VT
8058 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8059 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8060 MVT::i64 : MVT::i32, MVT::Other),
8061 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
8063 // If this is an i16 load, insert the truncate.
8064 SDValue ResVal = BSLoad;
8065 if (N->getValueType(0) == MVT::i16)
8066 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8068 // First, combine the bswap away. This makes the value produced by the
8070 DCI.CombineTo(N, ResVal);
8072 // Next, combine the load away, we give it a bogus result value but a real
8073 // chain result. The result value is dead because the bswap is dead.
8074 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8076 // Return N so it doesn't get rechecked!
8077 return SDValue(N, 0);
8081 case PPCISD::VCMP: {
8082 // If a VCMPo node already exists with exactly the same operands as this
8083 // node, use its result instead of this node (VCMPo computes both a CR6 and
8084 // a normal output).
8086 if (!N->getOperand(0).hasOneUse() &&
8087 !N->getOperand(1).hasOneUse() &&
8088 !N->getOperand(2).hasOneUse()) {
8090 // Scan all of the users of the LHS, looking for VCMPo's that match.
8091 SDNode *VCMPoNode = 0;
8093 SDNode *LHSN = N->getOperand(0).getNode();
8094 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8096 if (UI->getOpcode() == PPCISD::VCMPo &&
8097 UI->getOperand(1) == N->getOperand(1) &&
8098 UI->getOperand(2) == N->getOperand(2) &&
8099 UI->getOperand(0) == N->getOperand(0)) {
8104 // If there is no VCMPo node, or if the flag value has a single use, don't
8106 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8109 // Look at the (necessarily single) use of the flag value. If it has a
8110 // chain, this transformation is more complex. Note that multiple things
8111 // could use the value result, which we should ignore.
8112 SDNode *FlagUser = 0;
8113 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8114 FlagUser == 0; ++UI) {
8115 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8117 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8118 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8125 // If the user is a MFOCRF instruction, we know this is safe.
8126 // Otherwise we give up for right now.
8127 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8128 return SDValue(VCMPoNode, 0);
8133 SDValue Cond = N->getOperand(1);
8134 SDValue Target = N->getOperand(2);
8136 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8137 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8138 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8140 // We now need to make the intrinsic dead (it cannot be instruction
8142 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8143 assert(Cond.getNode()->hasOneUse() &&
8144 "Counter decrement has more than one use");
8146 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8147 N->getOperand(0), Target);
8152 // If this is a branch on an altivec predicate comparison, lower this so
8153 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8154 // lowering is done pre-legalize, because the legalizer lowers the predicate
8155 // compare down to code that is difficult to reassemble.
8156 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8157 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8159 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8160 // value. If so, pass-through the AND to get to the intrinsic.
8161 if (LHS.getOpcode() == ISD::AND &&
8162 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8163 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8164 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8165 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8166 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8168 LHS = LHS.getOperand(0);
8170 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8171 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8172 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8173 isa<ConstantSDNode>(RHS)) {
8174 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8175 "Counter decrement comparison is not EQ or NE");
8177 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8178 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8179 (CC == ISD::SETNE && !Val);
8181 // We now need to make the intrinsic dead (it cannot be instruction
8183 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8184 assert(LHS.getNode()->hasOneUse() &&
8185 "Counter decrement has more than one use");
8187 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8188 N->getOperand(0), N->getOperand(4));
8194 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8195 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8196 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8197 assert(isDot && "Can't compare against a vector result!");
8199 // If this is a comparison against something other than 0/1, then we know
8200 // that the condition is never/always true.
8201 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8202 if (Val != 0 && Val != 1) {
8203 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8204 return N->getOperand(0);
8205 // Always !=, turn it into an unconditional branch.
8206 return DAG.getNode(ISD::BR, dl, MVT::Other,
8207 N->getOperand(0), N->getOperand(4));
8210 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8212 // Create the PPCISD altivec 'dot' comparison node.
8214 LHS.getOperand(2), // LHS of compare
8215 LHS.getOperand(3), // RHS of compare
8216 DAG.getConstant(CompareOpc, MVT::i32)
8218 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8219 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
8221 // Unpack the result based on how the target uses it.
8222 PPC::Predicate CompOpc;
8223 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8224 default: // Can't happen, don't crash on invalid number though.
8225 case 0: // Branch on the value of the EQ bit of CR6.
8226 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8228 case 1: // Branch on the inverted value of the EQ bit of CR6.
8229 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8231 case 2: // Branch on the value of the LT bit of CR6.
8232 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8234 case 3: // Branch on the inverted value of the LT bit of CR6.
8235 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8239 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8240 DAG.getConstant(CompOpc, MVT::i32),
8241 DAG.getRegister(PPC::CR6, MVT::i32),
8242 N->getOperand(4), CompNode.getValue(1));
8251 //===----------------------------------------------------------------------===//
8252 // Inline Assembly Support
8253 //===----------------------------------------------------------------------===//
8255 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8258 const SelectionDAG &DAG,
8259 unsigned Depth) const {
8260 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8261 switch (Op.getOpcode()) {
8263 case PPCISD::LBRX: {
8264 // lhbrx is known to have the top bits cleared out.
8265 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8266 KnownZero = 0xFFFF0000;
8269 case ISD::INTRINSIC_WO_CHAIN: {
8270 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8272 case Intrinsic::ppc_altivec_vcmpbfp_p:
8273 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8274 case Intrinsic::ppc_altivec_vcmpequb_p:
8275 case Intrinsic::ppc_altivec_vcmpequh_p:
8276 case Intrinsic::ppc_altivec_vcmpequw_p:
8277 case Intrinsic::ppc_altivec_vcmpgefp_p:
8278 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8279 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8280 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8281 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8282 case Intrinsic::ppc_altivec_vcmpgtub_p:
8283 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8284 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8285 KnownZero = ~1U; // All bits but the low one are known to be zero.
8293 /// getConstraintType - Given a constraint, return the type of
8294 /// constraint it is for this target.
8295 PPCTargetLowering::ConstraintType
8296 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8297 if (Constraint.size() == 1) {
8298 switch (Constraint[0]) {
8305 return C_RegisterClass;
8307 // FIXME: While Z does indicate a memory constraint, it specifically
8308 // indicates an r+r address (used in conjunction with the 'y' modifier
8309 // in the replacement string). Currently, we're forcing the base
8310 // register to be r0 in the asm printer (which is interpreted as zero)
8311 // and forming the complete address in the second register. This is
8315 } else if (Constraint == "wc") { // individual CR bits.
8316 return C_RegisterClass;
8318 return TargetLowering::getConstraintType(Constraint);
8321 /// Examine constraint type and operand type and determine a weight value.
8322 /// This object must already have been set up with the operand type
8323 /// and the current alternative constraint selected.
8324 TargetLowering::ConstraintWeight
8325 PPCTargetLowering::getSingleConstraintMatchWeight(
8326 AsmOperandInfo &info, const char *constraint) const {
8327 ConstraintWeight weight = CW_Invalid;
8328 Value *CallOperandVal = info.CallOperandVal;
8329 // If we don't have a value, we can't do a match,
8330 // but allow it at the lowest weight.
8331 if (CallOperandVal == NULL)
8333 Type *type = CallOperandVal->getType();
8335 // Look at the constraint type.
8336 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8337 return CW_Register; // an individual CR bit.
8339 switch (*constraint) {
8341 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8344 if (type->isIntegerTy())
8345 weight = CW_Register;
8348 if (type->isFloatTy())
8349 weight = CW_Register;
8352 if (type->isDoubleTy())
8353 weight = CW_Register;
8356 if (type->isVectorTy())
8357 weight = CW_Register;
8360 weight = CW_Register;
8369 std::pair<unsigned, const TargetRegisterClass*>
8370 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8372 if (Constraint.size() == 1) {
8373 // GCC RS6000 Constraint Letters
8374 switch (Constraint[0]) {
8376 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8377 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8378 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8380 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8381 return std::make_pair(0U, &PPC::G8RCRegClass);
8382 return std::make_pair(0U, &PPC::GPRCRegClass);
8384 if (VT == MVT::f32 || VT == MVT::i32)
8385 return std::make_pair(0U, &PPC::F4RCRegClass);
8386 if (VT == MVT::f64 || VT == MVT::i64)
8387 return std::make_pair(0U, &PPC::F8RCRegClass);
8390 return std::make_pair(0U, &PPC::VRRCRegClass);
8392 return std::make_pair(0U, &PPC::CRRCRegClass);
8394 } else if (Constraint == "wc") { // an individual CR bit.
8395 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8398 std::pair<unsigned, const TargetRegisterClass*> R =
8399 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8401 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8402 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8403 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8405 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8406 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8407 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8408 PPC::GPRCRegClass.contains(R.first)) {
8409 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8410 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8411 PPC::sub_32, &PPC::G8RCRegClass),
8412 &PPC::G8RCRegClass);
8419 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8420 /// vector. If it is invalid, don't add anything to Ops.
8421 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8422 std::string &Constraint,
8423 std::vector<SDValue>&Ops,
8424 SelectionDAG &DAG) const {
8425 SDValue Result(0,0);
8427 // Only support length 1 constraints.
8428 if (Constraint.length() > 1) return;
8430 char Letter = Constraint[0];
8441 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8442 if (!CST) return; // Must be an immediate to match.
8443 unsigned Value = CST->getZExtValue();
8445 default: llvm_unreachable("Unknown constraint letter!");
8446 case 'I': // "I" is a signed 16-bit constant.
8447 if ((short)Value == (int)Value)
8448 Result = DAG.getTargetConstant(Value, Op.getValueType());
8450 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8451 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8452 if ((short)Value == 0)
8453 Result = DAG.getTargetConstant(Value, Op.getValueType());
8455 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8456 if ((Value >> 16) == 0)
8457 Result = DAG.getTargetConstant(Value, Op.getValueType());
8459 case 'M': // "M" is a constant that is greater than 31.
8461 Result = DAG.getTargetConstant(Value, Op.getValueType());
8463 case 'N': // "N" is a positive constant that is an exact power of two.
8464 if ((int)Value > 0 && isPowerOf2_32(Value))
8465 Result = DAG.getTargetConstant(Value, Op.getValueType());
8467 case 'O': // "O" is the constant zero.
8469 Result = DAG.getTargetConstant(Value, Op.getValueType());
8471 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8472 if ((short)-Value == (int)-Value)
8473 Result = DAG.getTargetConstant(Value, Op.getValueType());
8480 if (Result.getNode()) {
8481 Ops.push_back(Result);
8485 // Handle standard constraint letters.
8486 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8489 // isLegalAddressingMode - Return true if the addressing mode represented
8490 // by AM is legal for this target, for a load/store of the specified type.
8491 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8493 // FIXME: PPC does not allow r+i addressing modes for vectors!
8495 // PPC allows a sign-extended 16-bit immediate field.
8496 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8499 // No global is ever allowed as a base.
8503 // PPC only support r+r,
8505 case 0: // "r+i" or just "i", depending on HasBaseReg.
8508 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8510 // Otherwise we have r+r or r+i.
8513 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8515 // Allow 2*r as r+r.
8518 // No other scales are supported.
8525 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8526 SelectionDAG &DAG) const {
8527 MachineFunction &MF = DAG.getMachineFunction();
8528 MachineFrameInfo *MFI = MF.getFrameInfo();
8529 MFI->setReturnAddressIsTaken(true);
8531 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8535 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8537 // Make sure the function does not optimize away the store of the RA to
8539 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8540 FuncInfo->setLRStoreRequired();
8541 bool isPPC64 = PPCSubTarget.isPPC64();
8542 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8545 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8548 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8549 isPPC64? MVT::i64 : MVT::i32);
8550 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8551 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8553 MachinePointerInfo(), false, false, false, 0);
8556 // Just load the return address off the stack.
8557 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8558 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8559 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8562 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8563 SelectionDAG &DAG) const {
8565 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8567 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8568 bool isPPC64 = PtrVT == MVT::i64;
8570 MachineFunction &MF = DAG.getMachineFunction();
8571 MachineFrameInfo *MFI = MF.getFrameInfo();
8572 MFI->setFrameAddressIsTaken(true);
8574 // Naked functions never have a frame pointer, and so we use r1. For all
8575 // other functions, this decision must be delayed until during PEI.
8577 if (MF.getFunction()->getAttributes().hasAttribute(
8578 AttributeSet::FunctionIndex, Attribute::Naked))
8579 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8581 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8583 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8586 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8587 FrameAddr, MachinePointerInfo(), false, false,
8593 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8594 // The PowerPC target isn't yet aware of offsets.
8598 /// getOptimalMemOpType - Returns the target specific optimal type for load
8599 /// and store operations as a result of memset, memcpy, and memmove
8600 /// lowering. If DstAlign is zero that means it's safe to destination
8601 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8602 /// means there isn't a need to check it against alignment requirement,
8603 /// probably because the source does not need to be loaded. If 'IsMemset' is
8604 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8605 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8606 /// source is constant so it does not need to be loaded.
8607 /// It returns EVT::Other if the type should be determined using generic
8608 /// target-independent logic.
8609 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8610 unsigned DstAlign, unsigned SrcAlign,
8611 bool IsMemset, bool ZeroMemset,
8613 MachineFunction &MF) const {
8614 if (this->PPCSubTarget.isPPC64()) {
8621 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8624 if (DisablePPCUnaligned)
8627 // PowerPC supports unaligned memory access for simple non-vector types.
8628 // Although accessing unaligned addresses is not as efficient as accessing
8629 // aligned addresses, it is generally more efficient than manual expansion,
8630 // and generally only traps for software emulation when crossing page
8636 if (VT.getSimpleVT().isVector())
8639 if (VT == MVT::ppcf128)
8648 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8649 VT = VT.getScalarType();
8654 switch (VT.getSimpleVT().SimpleTy) {
8665 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8666 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8667 return TargetLowering::getSchedulingPreference(N);
8672 // Create a fast isel object.
8674 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8675 const TargetLibraryInfo *LibInfo) const {
8676 return PPC::createFastISel(FuncInfo, LibInfo);