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 "llvm/ADT/STLExtras.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
39 static bool CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
40 CCValAssign::LocInfo &LocInfo,
41 ISD::ArgFlagsTy &ArgFlags,
43 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
45 CCValAssign::LocInfo &LocInfo,
46 ISD::ArgFlagsTy &ArgFlags,
48 static bool CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
50 CCValAssign::LocInfo &LocInfo,
51 ISD::ArgFlagsTy &ArgFlags,
54 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
55 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
57 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
58 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
60 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
61 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
63 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
64 if (TM.getSubtargetImpl()->isDarwin())
65 return new TargetLoweringObjectFileMachO();
67 return new TargetLoweringObjectFileELF();
70 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
71 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
72 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
73 PPCRegInfo = TM.getRegisterInfo();
77 // Use _setjmp/_longjmp instead of setjmp/longjmp.
78 setUseUnderscoreSetJmp(true);
79 setUseUnderscoreLongJmp(true);
81 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
82 // arguments are at least 4/8 bytes aligned.
83 bool isPPC64 = Subtarget->isPPC64();
84 setMinStackArgumentAlignment(isPPC64 ? 8:4);
86 // Set up the register classes.
87 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
88 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
89 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
91 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
92 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
95 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
97 // PowerPC has pre-inc load and store's.
98 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
99 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
100 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
101 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
102 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
103 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
104 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
105 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
106 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
107 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
109 // This is used in the ppcf128->int sequence. Note it has different semantics
110 // from FP_ROUND: that rounds to nearest, this rounds to zero.
111 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
113 // We do not currently implement these libm ops for PowerPC.
114 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
115 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
116 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
117 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
118 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
119 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
121 // PowerPC has no SREM/UREM instructions
122 setOperationAction(ISD::SREM, MVT::i32, Expand);
123 setOperationAction(ISD::UREM, MVT::i32, Expand);
124 setOperationAction(ISD::SREM, MVT::i64, Expand);
125 setOperationAction(ISD::UREM, MVT::i64, Expand);
127 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
128 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
129 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
130 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
131 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
132 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
133 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
134 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
135 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
137 // We don't support sin/cos/sqrt/fmod/pow
138 setOperationAction(ISD::FSIN , MVT::f64, Expand);
139 setOperationAction(ISD::FCOS , MVT::f64, Expand);
140 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
141 setOperationAction(ISD::FREM , MVT::f64, Expand);
142 setOperationAction(ISD::FPOW , MVT::f64, Expand);
143 setOperationAction(ISD::FMA , MVT::f64, Legal);
144 setOperationAction(ISD::FSIN , MVT::f32, Expand);
145 setOperationAction(ISD::FCOS , MVT::f32, Expand);
146 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
147 setOperationAction(ISD::FREM , MVT::f32, Expand);
148 setOperationAction(ISD::FPOW , MVT::f32, Expand);
149 setOperationAction(ISD::FMA , MVT::f32, Legal);
151 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
153 // If we're enabling GP optimizations, use hardware square root
154 if (!Subtarget->hasFSQRT() &&
155 !(TM.Options.UnsafeFPMath &&
156 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
157 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
159 if (!Subtarget->hasFSQRT() &&
160 !(TM.Options.UnsafeFPMath &&
161 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
162 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
164 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
165 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
167 if (Subtarget->hasFPRND()) {
168 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
169 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
170 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
172 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
173 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
174 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
176 // frin does not implement "ties to even." Thus, this is safe only in
178 if (TM.Options.UnsafeFPMath) {
179 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
180 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
182 // These need to set FE_INEXACT, and use a custom inserter.
183 setOperationAction(ISD::FRINT, MVT::f64, Legal);
184 setOperationAction(ISD::FRINT, MVT::f32, Legal);
188 // PowerPC does not have BSWAP, CTPOP or CTTZ
189 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
190 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
191 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
192 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
193 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
194 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
195 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
196 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
198 if (Subtarget->hasPOPCNTD()) {
199 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
200 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
202 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
203 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
206 // PowerPC does not have ROTR
207 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
208 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
210 // PowerPC does not have Select
211 setOperationAction(ISD::SELECT, MVT::i32, Expand);
212 setOperationAction(ISD::SELECT, MVT::i64, Expand);
213 setOperationAction(ISD::SELECT, MVT::f32, Expand);
214 setOperationAction(ISD::SELECT, MVT::f64, Expand);
216 // PowerPC wants to turn select_cc of FP into fsel when possible.
217 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
218 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
220 // PowerPC wants to optimize integer setcc a bit
221 setOperationAction(ISD::SETCC, MVT::i32, Custom);
223 // PowerPC does not have BRCOND which requires SetCC
224 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
226 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
228 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
229 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
231 // PowerPC does not have [U|S]INT_TO_FP
232 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
233 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
235 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
236 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
237 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
238 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
240 // We cannot sextinreg(i1). Expand to shifts.
241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
243 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
244 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
245 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
246 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
248 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
249 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
250 // support continuation, user-level threading, and etc.. As a result, no
251 // other SjLj exception interfaces are implemented and please don't build
252 // your own exception handling based on them.
253 // LLVM/Clang supports zero-cost DWARF exception handling.
254 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
255 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
257 // We want to legalize GlobalAddress and ConstantPool nodes into the
258 // appropriate instructions to materialize the address.
259 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
260 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
261 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
262 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
263 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
264 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
265 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
266 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
267 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
268 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
271 setOperationAction(ISD::TRAP, MVT::Other, Legal);
273 // TRAMPOLINE is custom lowered.
274 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
275 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
277 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
278 setOperationAction(ISD::VASTART , MVT::Other, Custom);
280 if (Subtarget->isSVR4ABI()) {
282 // VAARG always uses double-word chunks, so promote anything smaller.
283 setOperationAction(ISD::VAARG, MVT::i1, Promote);
284 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
285 setOperationAction(ISD::VAARG, MVT::i8, Promote);
286 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
287 setOperationAction(ISD::VAARG, MVT::i16, Promote);
288 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
289 setOperationAction(ISD::VAARG, MVT::i32, Promote);
290 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
291 setOperationAction(ISD::VAARG, MVT::Other, Expand);
293 // VAARG is custom lowered with the 32-bit SVR4 ABI.
294 setOperationAction(ISD::VAARG, MVT::Other, Custom);
295 setOperationAction(ISD::VAARG, MVT::i64, Custom);
298 setOperationAction(ISD::VAARG, MVT::Other, Expand);
300 // Use the default implementation.
301 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
302 setOperationAction(ISD::VAEND , MVT::Other, Expand);
303 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
304 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
305 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
306 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
308 // We want to custom lower some of our intrinsics.
309 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
311 // Comparisons that require checking two conditions.
312 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
313 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
314 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
315 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
316 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
317 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
318 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
319 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
320 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
321 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
322 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
323 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
325 if (Subtarget->has64BitSupport()) {
326 // They also have instructions for converting between i64 and fp.
327 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
328 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
329 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
330 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
331 // This is just the low 32 bits of a (signed) fp->i64 conversion.
332 // We cannot do this with Promote because i64 is not a legal type.
333 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
335 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
336 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
338 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
339 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
342 // With the instructions enabled under FPCVT, we can do everything.
343 if (PPCSubTarget.hasFPCVT()) {
344 if (Subtarget->has64BitSupport()) {
345 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
346 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
347 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
348 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
351 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
352 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
353 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
354 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
357 if (Subtarget->use64BitRegs()) {
358 // 64-bit PowerPC implementations can support i64 types directly
359 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
360 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
361 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
362 // 64-bit PowerPC wants to expand i128 shifts itself.
363 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
364 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
365 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
367 // 32-bit PowerPC wants to expand i64 shifts itself.
368 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
369 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
370 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
373 if (Subtarget->hasAltivec()) {
374 // First set operation action for all vector types to expand. Then we
375 // will selectively turn on ones that can be effectively codegen'd.
376 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
377 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
378 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
380 // add/sub are legal for all supported vector VT's.
381 setOperationAction(ISD::ADD , VT, Legal);
382 setOperationAction(ISD::SUB , VT, Legal);
384 // We promote all shuffles to v16i8.
385 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
386 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
388 // We promote all non-typed operations to v4i32.
389 setOperationAction(ISD::AND , VT, Promote);
390 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
391 setOperationAction(ISD::OR , VT, Promote);
392 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
393 setOperationAction(ISD::XOR , VT, Promote);
394 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
395 setOperationAction(ISD::LOAD , VT, Promote);
396 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
397 setOperationAction(ISD::SELECT, VT, Promote);
398 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
399 setOperationAction(ISD::STORE, VT, Promote);
400 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
402 // No other operations are legal.
403 setOperationAction(ISD::MUL , VT, Expand);
404 setOperationAction(ISD::SDIV, VT, Expand);
405 setOperationAction(ISD::SREM, VT, Expand);
406 setOperationAction(ISD::UDIV, VT, Expand);
407 setOperationAction(ISD::UREM, VT, Expand);
408 setOperationAction(ISD::FDIV, VT, Expand);
409 setOperationAction(ISD::FNEG, VT, Expand);
410 setOperationAction(ISD::FSQRT, VT, Expand);
411 setOperationAction(ISD::FLOG, VT, Expand);
412 setOperationAction(ISD::FLOG10, VT, Expand);
413 setOperationAction(ISD::FLOG2, VT, Expand);
414 setOperationAction(ISD::FEXP, VT, Expand);
415 setOperationAction(ISD::FEXP2, VT, Expand);
416 setOperationAction(ISD::FSIN, VT, Expand);
417 setOperationAction(ISD::FCOS, VT, Expand);
418 setOperationAction(ISD::FABS, VT, Expand);
419 setOperationAction(ISD::FPOWI, VT, Expand);
420 setOperationAction(ISD::FFLOOR, VT, Expand);
421 setOperationAction(ISD::FCEIL, VT, Expand);
422 setOperationAction(ISD::FTRUNC, VT, Expand);
423 setOperationAction(ISD::FRINT, VT, Expand);
424 setOperationAction(ISD::FNEARBYINT, VT, Expand);
425 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
426 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
427 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
428 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
429 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
430 setOperationAction(ISD::UDIVREM, VT, Expand);
431 setOperationAction(ISD::SDIVREM, VT, Expand);
432 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
433 setOperationAction(ISD::FPOW, VT, Expand);
434 setOperationAction(ISD::CTPOP, VT, Expand);
435 setOperationAction(ISD::CTLZ, VT, Expand);
436 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
437 setOperationAction(ISD::CTTZ, VT, Expand);
438 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
439 setOperationAction(ISD::VSELECT, VT, Expand);
440 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
442 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
444 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
445 setTruncStoreAction(VT, InnerVT, Expand);
447 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
448 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
449 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
452 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
453 // with merges, splats, etc.
454 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
456 setOperationAction(ISD::AND , MVT::v4i32, Legal);
457 setOperationAction(ISD::OR , MVT::v4i32, Legal);
458 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
459 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
460 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
461 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
462 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
463 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
464 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
465 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
466 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
467 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
468 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
469 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
471 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
472 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
473 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
474 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
476 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
477 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
479 if (TM.Options.UnsafeFPMath) {
480 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
481 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
484 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
485 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
486 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
488 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
489 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
491 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
492 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
493 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
494 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
496 // Altivec does not contain unordered floating-point compare instructions
497 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
498 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
499 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
500 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
501 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
502 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
505 if (Subtarget->has64BitSupport()) {
506 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
507 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
510 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
511 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
512 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
513 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
515 setBooleanContents(ZeroOrOneBooleanContent);
516 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
519 setStackPointerRegisterToSaveRestore(PPC::X1);
520 setExceptionPointerRegister(PPC::X3);
521 setExceptionSelectorRegister(PPC::X4);
523 setStackPointerRegisterToSaveRestore(PPC::R1);
524 setExceptionPointerRegister(PPC::R3);
525 setExceptionSelectorRegister(PPC::R4);
528 // We have target-specific dag combine patterns for the following nodes:
529 setTargetDAGCombine(ISD::SINT_TO_FP);
530 setTargetDAGCombine(ISD::STORE);
531 setTargetDAGCombine(ISD::BR_CC);
532 setTargetDAGCombine(ISD::BSWAP);
534 // Use reciprocal estimates.
535 if (TM.Options.UnsafeFPMath) {
536 setTargetDAGCombine(ISD::FDIV);
537 setTargetDAGCombine(ISD::FSQRT);
540 // Darwin long double math library functions have $LDBL128 appended.
541 if (Subtarget->isDarwin()) {
542 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
543 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
544 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
545 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
546 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
547 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
548 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
549 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
550 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
551 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
554 setMinFunctionAlignment(2);
555 if (PPCSubTarget.isDarwin())
556 setPrefFunctionAlignment(4);
558 if (isPPC64 && Subtarget->isJITCodeModel())
559 // Temporary workaround for the inability of PPC64 JIT to handle jump
561 setSupportJumpTables(false);
563 setInsertFencesForAtomic(true);
565 setSchedulingPreference(Sched::Hybrid);
567 computeRegisterProperties();
569 // The Freescale cores does better with aggressive inlining of memcpy and
570 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
571 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
572 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
573 MaxStoresPerMemset = 32;
574 MaxStoresPerMemsetOptSize = 16;
575 MaxStoresPerMemcpy = 32;
576 MaxStoresPerMemcpyOptSize = 8;
577 MaxStoresPerMemmove = 32;
578 MaxStoresPerMemmoveOptSize = 8;
580 setPrefFunctionAlignment(4);
584 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
585 /// function arguments in the caller parameter area.
586 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
587 const TargetMachine &TM = getTargetMachine();
588 // Darwin passes everything on 4 byte boundary.
589 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
592 // 16byte and wider vectors are passed on 16byte boundary.
593 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
594 if (VTy->getBitWidth() >= 128)
597 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
598 if (PPCSubTarget.isPPC64())
604 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
607 case PPCISD::FSEL: return "PPCISD::FSEL";
608 case PPCISD::FCFID: return "PPCISD::FCFID";
609 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
610 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
611 case PPCISD::FRE: return "PPCISD::FRE";
612 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
613 case PPCISD::STFIWX: return "PPCISD::STFIWX";
614 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
615 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
616 case PPCISD::VPERM: return "PPCISD::VPERM";
617 case PPCISD::Hi: return "PPCISD::Hi";
618 case PPCISD::Lo: return "PPCISD::Lo";
619 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
620 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
621 case PPCISD::LOAD: return "PPCISD::LOAD";
622 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
623 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
624 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
625 case PPCISD::SRL: return "PPCISD::SRL";
626 case PPCISD::SRA: return "PPCISD::SRA";
627 case PPCISD::SHL: return "PPCISD::SHL";
628 case PPCISD::CALL: return "PPCISD::CALL";
629 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
630 case PPCISD::MTCTR: return "PPCISD::MTCTR";
631 case PPCISD::BCTRL: return "PPCISD::BCTRL";
632 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
633 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
634 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
635 case PPCISD::MFCR: return "PPCISD::MFCR";
636 case PPCISD::VCMP: return "PPCISD::VCMP";
637 case PPCISD::VCMPo: return "PPCISD::VCMPo";
638 case PPCISD::LBRX: return "PPCISD::LBRX";
639 case PPCISD::STBRX: return "PPCISD::STBRX";
640 case PPCISD::LARX: return "PPCISD::LARX";
641 case PPCISD::STCX: return "PPCISD::STCX";
642 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
643 case PPCISD::MFFS: return "PPCISD::MFFS";
644 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
645 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
646 case PPCISD::CR6SET: return "PPCISD::CR6SET";
647 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
648 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
649 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
650 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
651 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
652 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
653 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
654 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
655 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
656 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
657 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
658 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
659 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
660 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
661 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
662 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
666 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
669 return VT.changeVectorElementTypeToInteger();
672 //===----------------------------------------------------------------------===//
673 // Node matching predicates, for use by the tblgen matching code.
674 //===----------------------------------------------------------------------===//
676 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
677 static bool isFloatingPointZero(SDValue Op) {
678 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
679 return CFP->getValueAPF().isZero();
680 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
681 // Maybe this has already been legalized into the constant pool?
682 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
683 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
684 return CFP->getValueAPF().isZero();
689 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
690 /// true if Op is undef or if it matches the specified value.
691 static bool isConstantOrUndef(int Op, int Val) {
692 return Op < 0 || Op == Val;
695 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
696 /// VPKUHUM instruction.
697 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
699 for (unsigned i = 0; i != 16; ++i)
700 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
703 for (unsigned i = 0; i != 8; ++i)
704 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
705 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
711 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
712 /// VPKUWUM instruction.
713 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
715 for (unsigned i = 0; i != 16; i += 2)
716 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
717 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
720 for (unsigned i = 0; i != 8; i += 2)
721 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
722 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
723 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
724 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
730 /// isVMerge - Common function, used to match vmrg* shuffles.
732 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
733 unsigned LHSStart, unsigned RHSStart) {
734 assert(N->getValueType(0) == MVT::v16i8 &&
735 "PPC only supports shuffles by bytes!");
736 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
737 "Unsupported merge size!");
739 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
740 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
741 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
742 LHSStart+j+i*UnitSize) ||
743 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
744 RHSStart+j+i*UnitSize))
750 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
751 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
752 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
755 return isVMerge(N, UnitSize, 8, 24);
756 return isVMerge(N, UnitSize, 8, 8);
759 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
760 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
761 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
764 return isVMerge(N, UnitSize, 0, 16);
765 return isVMerge(N, UnitSize, 0, 0);
769 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
770 /// amount, otherwise return -1.
771 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
772 assert(N->getValueType(0) == MVT::v16i8 &&
773 "PPC only supports shuffles by bytes!");
775 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
777 // Find the first non-undef value in the shuffle mask.
779 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
782 if (i == 16) return -1; // all undef.
784 // Otherwise, check to see if the rest of the elements are consecutively
785 // numbered from this value.
786 unsigned ShiftAmt = SVOp->getMaskElt(i);
787 if (ShiftAmt < i) return -1;
791 // Check the rest of the elements to see if they are consecutive.
792 for (++i; i != 16; ++i)
793 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
796 // Check the rest of the elements to see if they are consecutive.
797 for (++i; i != 16; ++i)
798 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
804 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
805 /// specifies a splat of a single element that is suitable for input to
806 /// VSPLTB/VSPLTH/VSPLTW.
807 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
808 assert(N->getValueType(0) == MVT::v16i8 &&
809 (EltSize == 1 || EltSize == 2 || EltSize == 4));
811 // This is a splat operation if each element of the permute is the same, and
812 // if the value doesn't reference the second vector.
813 unsigned ElementBase = N->getMaskElt(0);
815 // FIXME: Handle UNDEF elements too!
816 if (ElementBase >= 16)
819 // Check that the indices are consecutive, in the case of a multi-byte element
820 // splatted with a v16i8 mask.
821 for (unsigned i = 1; i != EltSize; ++i)
822 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
825 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
826 if (N->getMaskElt(i) < 0) continue;
827 for (unsigned j = 0; j != EltSize; ++j)
828 if (N->getMaskElt(i+j) != N->getMaskElt(j))
834 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
836 bool PPC::isAllNegativeZeroVector(SDNode *N) {
837 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
839 APInt APVal, APUndef;
843 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
844 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
845 return CFP->getValueAPF().isNegZero();
850 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
851 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
852 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
853 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
854 assert(isSplatShuffleMask(SVOp, EltSize));
855 return SVOp->getMaskElt(0) / EltSize;
858 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
859 /// by using a vspltis[bhw] instruction of the specified element size, return
860 /// the constant being splatted. The ByteSize field indicates the number of
861 /// bytes of each element [124] -> [bhw].
862 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
865 // If ByteSize of the splat is bigger than the element size of the
866 // build_vector, then we have a case where we are checking for a splat where
867 // multiple elements of the buildvector are folded together into a single
868 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
869 unsigned EltSize = 16/N->getNumOperands();
870 if (EltSize < ByteSize) {
871 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
872 SDValue UniquedVals[4];
873 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
875 // See if all of the elements in the buildvector agree across.
876 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
877 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
878 // If the element isn't a constant, bail fully out.
879 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
882 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
883 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
884 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
885 return SDValue(); // no match.
888 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
889 // either constant or undef values that are identical for each chunk. See
890 // if these chunks can form into a larger vspltis*.
892 // Check to see if all of the leading entries are either 0 or -1. If
893 // neither, then this won't fit into the immediate field.
894 bool LeadingZero = true;
895 bool LeadingOnes = true;
896 for (unsigned i = 0; i != Multiple-1; ++i) {
897 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
899 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
900 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
902 // Finally, check the least significant entry.
904 if (UniquedVals[Multiple-1].getNode() == 0)
905 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
906 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
908 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
911 if (UniquedVals[Multiple-1].getNode() == 0)
912 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
913 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
914 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
915 return DAG.getTargetConstant(Val, MVT::i32);
921 // Check to see if this buildvec has a single non-undef value in its elements.
922 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
923 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
924 if (OpVal.getNode() == 0)
925 OpVal = N->getOperand(i);
926 else if (OpVal != N->getOperand(i))
930 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
932 unsigned ValSizeInBytes = EltSize;
934 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
935 Value = CN->getZExtValue();
936 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
937 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
938 Value = FloatToBits(CN->getValueAPF().convertToFloat());
941 // If the splat value is larger than the element value, then we can never do
942 // this splat. The only case that we could fit the replicated bits into our
943 // immediate field for would be zero, and we prefer to use vxor for it.
944 if (ValSizeInBytes < ByteSize) return SDValue();
946 // If the element value is larger than the splat value, cut it in half and
947 // check to see if the two halves are equal. Continue doing this until we
948 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
949 while (ValSizeInBytes > ByteSize) {
950 ValSizeInBytes >>= 1;
952 // If the top half equals the bottom half, we're still ok.
953 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
954 (Value & ((1 << (8*ValSizeInBytes))-1)))
958 // Properly sign extend the value.
959 int MaskVal = SignExtend32(Value, ByteSize * 8);
961 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
962 if (MaskVal == 0) return SDValue();
964 // Finally, if this value fits in a 5 bit sext field, return it
965 if (SignExtend32<5>(MaskVal) == MaskVal)
966 return DAG.getTargetConstant(MaskVal, MVT::i32);
970 //===----------------------------------------------------------------------===//
971 // Addressing Mode Selection
972 //===----------------------------------------------------------------------===//
974 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
975 /// or 64-bit immediate, and if the value can be accurately represented as a
976 /// sign extension from a 16-bit value. If so, this returns true and the
978 static bool isIntS16Immediate(SDNode *N, short &Imm) {
979 if (N->getOpcode() != ISD::Constant)
982 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
983 if (N->getValueType(0) == MVT::i32)
984 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
986 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
988 static bool isIntS16Immediate(SDValue Op, short &Imm) {
989 return isIntS16Immediate(Op.getNode(), Imm);
993 /// SelectAddressRegReg - Given the specified addressed, check to see if it
994 /// can be represented as an indexed [r+r] operation. Returns false if it
995 /// can be more efficiently represented with [r+imm].
996 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
998 SelectionDAG &DAG) const {
1000 if (N.getOpcode() == ISD::ADD) {
1001 if (isIntS16Immediate(N.getOperand(1), imm))
1002 return false; // r+i
1003 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1004 return false; // r+i
1006 Base = N.getOperand(0);
1007 Index = N.getOperand(1);
1009 } else if (N.getOpcode() == ISD::OR) {
1010 if (isIntS16Immediate(N.getOperand(1), imm))
1011 return false; // r+i can fold it if we can.
1013 // If this is an or of disjoint bitfields, we can codegen this as an add
1014 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1016 APInt LHSKnownZero, LHSKnownOne;
1017 APInt RHSKnownZero, RHSKnownOne;
1018 DAG.ComputeMaskedBits(N.getOperand(0),
1019 LHSKnownZero, LHSKnownOne);
1021 if (LHSKnownZero.getBoolValue()) {
1022 DAG.ComputeMaskedBits(N.getOperand(1),
1023 RHSKnownZero, RHSKnownOne);
1024 // If all of the bits are known zero on the LHS or RHS, the add won't
1026 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1027 Base = N.getOperand(0);
1028 Index = N.getOperand(1);
1037 /// Returns true if the address N can be represented by a base register plus
1038 /// a signed 16-bit displacement [r+imm], and if it is not better
1039 /// represented as reg+reg.
1040 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1042 SelectionDAG &DAG) const {
1043 // FIXME dl should come from parent load or store, not from address
1044 DebugLoc dl = N.getDebugLoc();
1045 // If this can be more profitably realized as r+r, fail.
1046 if (SelectAddressRegReg(N, Disp, Base, DAG))
1049 if (N.getOpcode() == ISD::ADD) {
1051 if (isIntS16Immediate(N.getOperand(1), imm)) {
1052 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
1053 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1054 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1056 Base = N.getOperand(0);
1058 return true; // [r+i]
1059 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1060 // Match LOAD (ADD (X, Lo(G))).
1061 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1062 && "Cannot handle constant offsets yet!");
1063 Disp = N.getOperand(1).getOperand(0); // The global address.
1064 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1065 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1066 Disp.getOpcode() == ISD::TargetConstantPool ||
1067 Disp.getOpcode() == ISD::TargetJumpTable);
1068 Base = N.getOperand(0);
1069 return true; // [&g+r]
1071 } else if (N.getOpcode() == ISD::OR) {
1073 if (isIntS16Immediate(N.getOperand(1), imm)) {
1074 // If this is an or of disjoint bitfields, we can codegen this as an add
1075 // (for better address arithmetic) if the LHS and RHS of the OR are
1076 // provably disjoint.
1077 APInt LHSKnownZero, LHSKnownOne;
1078 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1080 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1081 // If all of the bits are known zero on the LHS or RHS, the add won't
1083 Base = N.getOperand(0);
1084 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
1088 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1089 // Loading from a constant address.
1091 // If this address fits entirely in a 16-bit sext immediate field, codegen
1094 if (isIntS16Immediate(CN, Imm)) {
1095 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1096 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1097 CN->getValueType(0));
1101 // Handle 32-bit sext immediates with LIS + addr mode.
1102 if (CN->getValueType(0) == MVT::i32 ||
1103 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1104 int Addr = (int)CN->getZExtValue();
1106 // Otherwise, break this down into an LIS + disp.
1107 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1109 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1110 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1111 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1116 Disp = DAG.getTargetConstant(0, getPointerTy());
1117 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1118 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1121 return true; // [r+0]
1124 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1125 /// represented as an indexed [r+r] operation.
1126 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1128 SelectionDAG &DAG) const {
1129 // Check to see if we can easily represent this as an [r+r] address. This
1130 // will fail if it thinks that the address is more profitably represented as
1131 // reg+imm, e.g. where imm = 0.
1132 if (SelectAddressRegReg(N, Base, Index, DAG))
1135 // If the operand is an addition, always emit this as [r+r], since this is
1136 // better (for code size, and execution, as the memop does the add for free)
1137 // than emitting an explicit add.
1138 if (N.getOpcode() == ISD::ADD) {
1139 Base = N.getOperand(0);
1140 Index = N.getOperand(1);
1144 // Otherwise, do it the hard way, using R0 as the base register.
1145 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1151 /// SelectAddressRegImmShift - Returns true if the address N can be
1152 /// represented by a base register plus a signed 14-bit displacement
1153 /// [r+imm*4]. Suitable for use by STD and friends.
1154 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1156 SelectionDAG &DAG) const {
1157 // FIXME dl should come from the parent load or store, not the address
1158 DebugLoc dl = N.getDebugLoc();
1159 // If this can be more profitably realized as r+r, fail.
1160 if (SelectAddressRegReg(N, Disp, Base, DAG))
1163 if (N.getOpcode() == ISD::ADD) {
1165 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1166 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1167 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1168 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1170 Base = N.getOperand(0);
1172 return true; // [r+i]
1173 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1174 // Match LOAD (ADD (X, Lo(G))).
1175 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1176 && "Cannot handle constant offsets yet!");
1177 Disp = N.getOperand(1).getOperand(0); // The global address.
1178 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1179 Disp.getOpcode() == ISD::TargetConstantPool ||
1180 Disp.getOpcode() == ISD::TargetJumpTable);
1181 Base = N.getOperand(0);
1182 return true; // [&g+r]
1184 } else if (N.getOpcode() == ISD::OR) {
1186 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1187 // If this is an or of disjoint bitfields, we can codegen this as an add
1188 // (for better address arithmetic) if the LHS and RHS of the OR are
1189 // provably disjoint.
1190 APInt LHSKnownZero, LHSKnownOne;
1191 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1192 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1193 // If all of the bits are known zero on the LHS or RHS, the add won't
1195 Base = N.getOperand(0);
1196 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1200 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1201 // Loading from a constant address. Verify low two bits are clear.
1202 if ((CN->getZExtValue() & 3) == 0) {
1203 // If this address fits entirely in a 14-bit sext immediate field, codegen
1206 if (isIntS16Immediate(CN, Imm)) {
1207 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1208 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1209 CN->getValueType(0));
1213 // Fold the low-part of 32-bit absolute addresses into addr mode.
1214 if (CN->getValueType(0) == MVT::i32 ||
1215 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1216 int Addr = (int)CN->getZExtValue();
1218 // Otherwise, break this down into an LIS + disp.
1219 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1220 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1221 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1222 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1228 Disp = DAG.getTargetConstant(0, getPointerTy());
1229 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1230 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1233 return true; // [r+0]
1237 /// getPreIndexedAddressParts - returns true by value, base pointer and
1238 /// offset pointer and addressing mode by reference if the node's address
1239 /// can be legally represented as pre-indexed load / store address.
1240 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1242 ISD::MemIndexedMode &AM,
1243 SelectionDAG &DAG) const {
1244 if (DisablePPCPreinc) return false;
1250 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1251 Ptr = LD->getBasePtr();
1252 VT = LD->getMemoryVT();
1253 Alignment = LD->getAlignment();
1254 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1255 Ptr = ST->getBasePtr();
1256 VT = ST->getMemoryVT();
1257 Alignment = ST->getAlignment();
1262 // PowerPC doesn't have preinc load/store instructions for vectors.
1266 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1268 // Common code will reject creating a pre-inc form if the base pointer
1269 // is a frame index, or if N is a store and the base pointer is either
1270 // the same as or a predecessor of the value being stored. Check for
1271 // those situations here, and try with swapped Base/Offset instead.
1274 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1277 SDValue Val = cast<StoreSDNode>(N)->getValue();
1278 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1283 std::swap(Base, Offset);
1289 // LDU/STU use reg+imm*4, others use reg+imm.
1290 if (VT != MVT::i64) {
1292 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1295 // LDU/STU need an address with at least 4-byte alignment.
1300 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1304 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1305 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1306 // sext i32 to i64 when addr mode is r+i.
1307 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1308 LD->getExtensionType() == ISD::SEXTLOAD &&
1309 isa<ConstantSDNode>(Offset))
1317 //===----------------------------------------------------------------------===//
1318 // LowerOperation implementation
1319 //===----------------------------------------------------------------------===//
1321 /// GetLabelAccessInfo - Return true if we should reference labels using a
1322 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1323 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1324 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1325 HiOpFlags = PPCII::MO_HA16;
1326 LoOpFlags = PPCII::MO_LO16;
1328 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1329 // non-darwin platform. We don't support PIC on other platforms yet.
1330 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1331 TM.getSubtarget<PPCSubtarget>().isDarwin();
1333 HiOpFlags |= PPCII::MO_PIC_FLAG;
1334 LoOpFlags |= PPCII::MO_PIC_FLAG;
1337 // If this is a reference to a global value that requires a non-lazy-ptr, make
1338 // sure that instruction lowering adds it.
1339 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1340 HiOpFlags |= PPCII::MO_NLP_FLAG;
1341 LoOpFlags |= PPCII::MO_NLP_FLAG;
1343 if (GV->hasHiddenVisibility()) {
1344 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1345 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1352 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1353 SelectionDAG &DAG) {
1354 EVT PtrVT = HiPart.getValueType();
1355 SDValue Zero = DAG.getConstant(0, PtrVT);
1356 DebugLoc DL = HiPart.getDebugLoc();
1358 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1359 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1361 // With PIC, the first instruction is actually "GR+hi(&G)".
1363 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1364 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1366 // Generate non-pic code that has direct accesses to the constant pool.
1367 // The address of the global is just (hi(&g)+lo(&g)).
1368 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1371 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1372 SelectionDAG &DAG) const {
1373 EVT PtrVT = Op.getValueType();
1374 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1375 const Constant *C = CP->getConstVal();
1377 // 64-bit SVR4 ABI code is always position-independent.
1378 // The actual address of the GlobalValue is stored in the TOC.
1379 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1380 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1381 return DAG.getNode(PPCISD::TOC_ENTRY, CP->getDebugLoc(), MVT::i64, GA,
1382 DAG.getRegister(PPC::X2, MVT::i64));
1385 unsigned MOHiFlag, MOLoFlag;
1386 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1388 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1390 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1391 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1394 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1395 EVT PtrVT = Op.getValueType();
1396 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1398 // 64-bit SVR4 ABI code is always position-independent.
1399 // The actual address of the GlobalValue is stored in the TOC.
1400 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1401 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1402 return DAG.getNode(PPCISD::TOC_ENTRY, JT->getDebugLoc(), MVT::i64, GA,
1403 DAG.getRegister(PPC::X2, MVT::i64));
1406 unsigned MOHiFlag, MOLoFlag;
1407 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1408 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1409 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1410 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1413 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1414 SelectionDAG &DAG) const {
1415 EVT PtrVT = Op.getValueType();
1417 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1419 unsigned MOHiFlag, MOLoFlag;
1420 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1421 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1422 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1423 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1426 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1427 SelectionDAG &DAG) const {
1429 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1430 DebugLoc dl = GA->getDebugLoc();
1431 const GlobalValue *GV = GA->getGlobal();
1432 EVT PtrVT = getPointerTy();
1433 bool is64bit = PPCSubTarget.isPPC64();
1435 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1437 if (Model == TLSModel::LocalExec) {
1438 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1439 PPCII::MO_TPREL16_HA);
1440 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1441 PPCII::MO_TPREL16_LO);
1442 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1443 is64bit ? MVT::i64 : MVT::i32);
1444 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1445 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1449 llvm_unreachable("only local-exec is currently supported for ppc32");
1451 if (Model == TLSModel::InitialExec) {
1452 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1453 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1454 SDValue TPOffsetHi = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1455 PtrVT, GOTReg, TGA);
1456 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1457 PtrVT, TGA, TPOffsetHi);
1458 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGA);
1461 if (Model == TLSModel::GeneralDynamic) {
1462 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1463 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1464 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1466 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1469 // We need a chain node, and don't have one handy. The underlying
1470 // call has no side effects, so using the function entry node
1472 SDValue Chain = DAG.getEntryNode();
1473 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1474 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1475 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1476 PtrVT, ParmReg, TGA);
1477 // The return value from GET_TLS_ADDR really is in X3 already, but
1478 // some hacks are needed here to tie everything together. The extra
1479 // copies dissolve during subsequent transforms.
1480 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1481 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1484 if (Model == TLSModel::LocalDynamic) {
1485 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1486 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1487 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1489 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1492 // We need a chain node, and don't have one handy. The underlying
1493 // call has no side effects, so using the function entry node
1495 SDValue Chain = DAG.getEntryNode();
1496 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1497 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1498 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1499 PtrVT, ParmReg, TGA);
1500 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1501 // some hacks are needed here to tie everything together. The extra
1502 // copies dissolve during subsequent transforms.
1503 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1504 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1505 Chain, ParmReg, TGA);
1506 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1509 llvm_unreachable("Unknown TLS model!");
1512 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1513 SelectionDAG &DAG) const {
1514 EVT PtrVT = Op.getValueType();
1515 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1516 DebugLoc DL = GSDN->getDebugLoc();
1517 const GlobalValue *GV = GSDN->getGlobal();
1519 // 64-bit SVR4 ABI code is always position-independent.
1520 // The actual address of the GlobalValue is stored in the TOC.
1521 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1522 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1523 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1524 DAG.getRegister(PPC::X2, MVT::i64));
1527 unsigned MOHiFlag, MOLoFlag;
1528 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1531 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1533 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1535 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1537 // If the global reference is actually to a non-lazy-pointer, we have to do an
1538 // extra load to get the address of the global.
1539 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1540 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1541 false, false, false, 0);
1545 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1546 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1547 DebugLoc dl = Op.getDebugLoc();
1549 // If we're comparing for equality to zero, expose the fact that this is
1550 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1551 // fold the new nodes.
1552 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1553 if (C->isNullValue() && CC == ISD::SETEQ) {
1554 EVT VT = Op.getOperand(0).getValueType();
1555 SDValue Zext = Op.getOperand(0);
1556 if (VT.bitsLT(MVT::i32)) {
1558 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1560 unsigned Log2b = Log2_32(VT.getSizeInBits());
1561 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1562 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1563 DAG.getConstant(Log2b, MVT::i32));
1564 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1566 // Leave comparisons against 0 and -1 alone for now, since they're usually
1567 // optimized. FIXME: revisit this when we can custom lower all setcc
1569 if (C->isAllOnesValue() || C->isNullValue())
1573 // If we have an integer seteq/setne, turn it into a compare against zero
1574 // by xor'ing the rhs with the lhs, which is faster than setting a
1575 // condition register, reading it back out, and masking the correct bit. The
1576 // normal approach here uses sub to do this instead of xor. Using xor exposes
1577 // the result to other bit-twiddling opportunities.
1578 EVT LHSVT = Op.getOperand(0).getValueType();
1579 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1580 EVT VT = Op.getValueType();
1581 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1583 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1588 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1589 const PPCSubtarget &Subtarget) const {
1590 SDNode *Node = Op.getNode();
1591 EVT VT = Node->getValueType(0);
1592 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1593 SDValue InChain = Node->getOperand(0);
1594 SDValue VAListPtr = Node->getOperand(1);
1595 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1596 DebugLoc dl = Node->getDebugLoc();
1598 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1601 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1602 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1604 InChain = GprIndex.getValue(1);
1606 if (VT == MVT::i64) {
1607 // Check if GprIndex is even
1608 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1609 DAG.getConstant(1, MVT::i32));
1610 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1611 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1612 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1613 DAG.getConstant(1, MVT::i32));
1614 // Align GprIndex to be even if it isn't
1615 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1619 // fpr index is 1 byte after gpr
1620 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1621 DAG.getConstant(1, MVT::i32));
1624 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1625 FprPtr, MachinePointerInfo(SV), MVT::i8,
1627 InChain = FprIndex.getValue(1);
1629 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1630 DAG.getConstant(8, MVT::i32));
1632 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1633 DAG.getConstant(4, MVT::i32));
1636 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1637 MachinePointerInfo(), false, false,
1639 InChain = OverflowArea.getValue(1);
1641 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1642 MachinePointerInfo(), false, false,
1644 InChain = RegSaveArea.getValue(1);
1646 // select overflow_area if index > 8
1647 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1648 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1650 // adjustment constant gpr_index * 4/8
1651 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1652 VT.isInteger() ? GprIndex : FprIndex,
1653 DAG.getConstant(VT.isInteger() ? 4 : 8,
1656 // OurReg = RegSaveArea + RegConstant
1657 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1660 // Floating types are 32 bytes into RegSaveArea
1661 if (VT.isFloatingPoint())
1662 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1663 DAG.getConstant(32, MVT::i32));
1665 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1666 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1667 VT.isInteger() ? GprIndex : FprIndex,
1668 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1671 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1672 VT.isInteger() ? VAListPtr : FprPtr,
1673 MachinePointerInfo(SV),
1674 MVT::i8, false, false, 0);
1676 // determine if we should load from reg_save_area or overflow_area
1677 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1679 // increase overflow_area by 4/8 if gpr/fpr > 8
1680 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1681 DAG.getConstant(VT.isInteger() ? 4 : 8,
1684 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1687 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1689 MachinePointerInfo(),
1690 MVT::i32, false, false, 0);
1692 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1693 false, false, false, 0);
1696 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1697 SelectionDAG &DAG) const {
1698 return Op.getOperand(0);
1701 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1702 SelectionDAG &DAG) const {
1703 SDValue Chain = Op.getOperand(0);
1704 SDValue Trmp = Op.getOperand(1); // trampoline
1705 SDValue FPtr = Op.getOperand(2); // nested function
1706 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1707 DebugLoc dl = Op.getDebugLoc();
1709 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1710 bool isPPC64 = (PtrVT == MVT::i64);
1712 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1715 TargetLowering::ArgListTy Args;
1716 TargetLowering::ArgListEntry Entry;
1718 Entry.Ty = IntPtrTy;
1719 Entry.Node = Trmp; Args.push_back(Entry);
1721 // TrampSize == (isPPC64 ? 48 : 40);
1722 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1723 isPPC64 ? MVT::i64 : MVT::i32);
1724 Args.push_back(Entry);
1726 Entry.Node = FPtr; Args.push_back(Entry);
1727 Entry.Node = Nest; Args.push_back(Entry);
1729 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1730 TargetLowering::CallLoweringInfo CLI(Chain,
1731 Type::getVoidTy(*DAG.getContext()),
1732 false, false, false, false, 0,
1734 /*isTailCall=*/false,
1735 /*doesNotRet=*/false,
1736 /*isReturnValueUsed=*/true,
1737 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1739 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1741 return CallResult.second;
1744 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1745 const PPCSubtarget &Subtarget) const {
1746 MachineFunction &MF = DAG.getMachineFunction();
1747 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1749 DebugLoc dl = Op.getDebugLoc();
1751 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1752 // vastart just stores the address of the VarArgsFrameIndex slot into the
1753 // memory location argument.
1754 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1755 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1756 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1757 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1758 MachinePointerInfo(SV),
1762 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1763 // We suppose the given va_list is already allocated.
1766 // char gpr; /* index into the array of 8 GPRs
1767 // * stored in the register save area
1768 // * gpr=0 corresponds to r3,
1769 // * gpr=1 to r4, etc.
1771 // char fpr; /* index into the array of 8 FPRs
1772 // * stored in the register save area
1773 // * fpr=0 corresponds to f1,
1774 // * fpr=1 to f2, etc.
1776 // char *overflow_arg_area;
1777 // /* location on stack that holds
1778 // * the next overflow argument
1780 // char *reg_save_area;
1781 // /* where r3:r10 and f1:f8 (if saved)
1787 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1788 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1791 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1793 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1795 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1798 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1799 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1801 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1802 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1804 uint64_t FPROffset = 1;
1805 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1807 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1809 // Store first byte : number of int regs
1810 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1812 MachinePointerInfo(SV),
1813 MVT::i8, false, false, 0);
1814 uint64_t nextOffset = FPROffset;
1815 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1818 // Store second byte : number of float regs
1819 SDValue secondStore =
1820 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1821 MachinePointerInfo(SV, nextOffset), MVT::i8,
1823 nextOffset += StackOffset;
1824 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1826 // Store second word : arguments given on stack
1827 SDValue thirdStore =
1828 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1829 MachinePointerInfo(SV, nextOffset),
1831 nextOffset += FrameOffset;
1832 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1834 // Store third word : arguments given in registers
1835 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1836 MachinePointerInfo(SV, nextOffset),
1841 #include "PPCGenCallingConv.inc"
1843 static bool CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1844 CCValAssign::LocInfo &LocInfo,
1845 ISD::ArgFlagsTy &ArgFlags,
1850 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1852 CCValAssign::LocInfo &LocInfo,
1853 ISD::ArgFlagsTy &ArgFlags,
1855 static const uint16_t ArgRegs[] = {
1856 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1857 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1859 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1861 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1863 // Skip one register if the first unallocated register has an even register
1864 // number and there are still argument registers available which have not been
1865 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1866 // need to skip a register if RegNum is odd.
1867 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1868 State.AllocateReg(ArgRegs[RegNum]);
1871 // Always return false here, as this function only makes sure that the first
1872 // unallocated register has an odd register number and does not actually
1873 // allocate a register for the current argument.
1877 static bool CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1879 CCValAssign::LocInfo &LocInfo,
1880 ISD::ArgFlagsTy &ArgFlags,
1882 static const uint16_t ArgRegs[] = {
1883 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1887 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1889 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1891 // If there is only one Floating-point register left we need to put both f64
1892 // values of a split ppc_fp128 value on the stack.
1893 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1894 State.AllocateReg(ArgRegs[RegNum]);
1897 // Always return false here, as this function only makes sure that the two f64
1898 // values a ppc_fp128 value is split into are both passed in registers or both
1899 // passed on the stack and does not actually allocate a register for the
1900 // current argument.
1904 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1906 static const uint16_t *GetFPR() {
1907 static const uint16_t FPR[] = {
1908 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1909 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1915 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1917 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1918 unsigned PtrByteSize) {
1919 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1920 if (Flags.isByVal())
1921 ArgSize = Flags.getByValSize();
1922 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1928 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1929 CallingConv::ID CallConv, bool isVarArg,
1930 const SmallVectorImpl<ISD::InputArg>
1932 DebugLoc dl, SelectionDAG &DAG,
1933 SmallVectorImpl<SDValue> &InVals)
1935 if (PPCSubTarget.isSVR4ABI()) {
1936 if (PPCSubTarget.isPPC64())
1937 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1940 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1943 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1949 PPCTargetLowering::LowerFormalArguments_32SVR4(
1951 CallingConv::ID CallConv, bool isVarArg,
1952 const SmallVectorImpl<ISD::InputArg>
1954 DebugLoc dl, SelectionDAG &DAG,
1955 SmallVectorImpl<SDValue> &InVals) const {
1957 // 32-bit SVR4 ABI Stack Frame Layout:
1958 // +-----------------------------------+
1959 // +--> | Back chain |
1960 // | +-----------------------------------+
1961 // | | Floating-point register save area |
1962 // | +-----------------------------------+
1963 // | | General register save area |
1964 // | +-----------------------------------+
1965 // | | CR save word |
1966 // | +-----------------------------------+
1967 // | | VRSAVE save word |
1968 // | +-----------------------------------+
1969 // | | Alignment padding |
1970 // | +-----------------------------------+
1971 // | | Vector register save area |
1972 // | +-----------------------------------+
1973 // | | Local variable space |
1974 // | +-----------------------------------+
1975 // | | Parameter list area |
1976 // | +-----------------------------------+
1977 // | | LR save word |
1978 // | +-----------------------------------+
1979 // SP--> +--- | Back chain |
1980 // +-----------------------------------+
1983 // System V Application Binary Interface PowerPC Processor Supplement
1984 // AltiVec Technology Programming Interface Manual
1986 MachineFunction &MF = DAG.getMachineFunction();
1987 MachineFrameInfo *MFI = MF.getFrameInfo();
1988 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1990 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1991 // Potential tail calls could cause overwriting of argument stack slots.
1992 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1993 (CallConv == CallingConv::Fast));
1994 unsigned PtrByteSize = 4;
1996 // Assign locations to all of the incoming arguments.
1997 SmallVector<CCValAssign, 16> ArgLocs;
1998 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1999 getTargetMachine(), ArgLocs, *DAG.getContext());
2001 // Reserve space for the linkage area on the stack.
2002 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2004 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2006 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2007 CCValAssign &VA = ArgLocs[i];
2009 // Arguments stored in registers.
2010 if (VA.isRegLoc()) {
2011 const TargetRegisterClass *RC;
2012 EVT ValVT = VA.getValVT();
2014 switch (ValVT.getSimpleVT().SimpleTy) {
2016 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2018 RC = &PPC::GPRCRegClass;
2021 RC = &PPC::F4RCRegClass;
2024 RC = &PPC::F8RCRegClass;
2030 RC = &PPC::VRRCRegClass;
2034 // Transform the arguments stored in physical registers into virtual ones.
2035 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2036 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
2038 InVals.push_back(ArgValue);
2040 // Argument stored in memory.
2041 assert(VA.isMemLoc());
2043 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
2044 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2047 // Create load nodes to retrieve arguments from the stack.
2048 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2049 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2050 MachinePointerInfo(),
2051 false, false, false, 0));
2055 // Assign locations to all of the incoming aggregate by value arguments.
2056 // Aggregates passed by value are stored in the local variable space of the
2057 // caller's stack frame, right above the parameter list area.
2058 SmallVector<CCValAssign, 16> ByValArgLocs;
2059 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2060 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2062 // Reserve stack space for the allocations in CCInfo.
2063 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2065 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2067 // Area that is at least reserved in the caller of this function.
2068 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2070 // Set the size that is at least reserved in caller of this function. Tail
2071 // call optimized function's reserved stack space needs to be aligned so that
2072 // taking the difference between two stack areas will result in an aligned
2074 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2077 std::max(MinReservedArea,
2078 PPCFrameLowering::getMinCallFrameSize(false, false));
2080 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2081 getStackAlignment();
2082 unsigned AlignMask = TargetAlign-1;
2083 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2085 FI->setMinReservedArea(MinReservedArea);
2087 SmallVector<SDValue, 8> MemOps;
2089 // If the function takes variable number of arguments, make a frame index for
2090 // the start of the first vararg value... for expansion of llvm.va_start.
2092 static const uint16_t GPArgRegs[] = {
2093 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2094 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2096 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2098 static const uint16_t FPArgRegs[] = {
2099 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2102 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2104 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2106 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2109 // Make room for NumGPArgRegs and NumFPArgRegs.
2110 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2111 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2113 FuncInfo->setVarArgsStackOffset(
2114 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2115 CCInfo.getNextStackOffset(), true));
2117 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2118 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2120 // The fixed integer arguments of a variadic function are stored to the
2121 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2122 // the result of va_next.
2123 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2124 // Get an existing live-in vreg, or add a new one.
2125 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2127 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2129 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2130 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2131 MachinePointerInfo(), false, false, 0);
2132 MemOps.push_back(Store);
2133 // Increment the address by four for the next argument to store
2134 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2135 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2138 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2140 // The double arguments are stored to the VarArgsFrameIndex
2142 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2143 // Get an existing live-in vreg, or add a new one.
2144 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2146 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2148 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2149 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2150 MachinePointerInfo(), false, false, 0);
2151 MemOps.push_back(Store);
2152 // Increment the address by eight for the next argument to store
2153 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2155 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2159 if (!MemOps.empty())
2160 Chain = DAG.getNode(ISD::TokenFactor, dl,
2161 MVT::Other, &MemOps[0], MemOps.size());
2166 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2167 // value to MVT::i64 and then truncate to the correct register size.
2169 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2170 SelectionDAG &DAG, SDValue ArgVal,
2171 DebugLoc dl) const {
2173 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2174 DAG.getValueType(ObjectVT));
2175 else if (Flags.isZExt())
2176 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2177 DAG.getValueType(ObjectVT));
2179 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2182 // Set the size that is at least reserved in caller of this function. Tail
2183 // call optimized functions' reserved stack space needs to be aligned so that
2184 // taking the difference between two stack areas will result in an aligned
2187 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2188 unsigned nAltivecParamsAtEnd,
2189 unsigned MinReservedArea,
2190 bool isPPC64) const {
2191 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2192 // Add the Altivec parameters at the end, if needed.
2193 if (nAltivecParamsAtEnd) {
2194 MinReservedArea = ((MinReservedArea+15)/16)*16;
2195 MinReservedArea += 16*nAltivecParamsAtEnd;
2198 std::max(MinReservedArea,
2199 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2200 unsigned TargetAlign
2201 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2202 getStackAlignment();
2203 unsigned AlignMask = TargetAlign-1;
2204 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2205 FI->setMinReservedArea(MinReservedArea);
2209 PPCTargetLowering::LowerFormalArguments_64SVR4(
2211 CallingConv::ID CallConv, bool isVarArg,
2212 const SmallVectorImpl<ISD::InputArg>
2214 DebugLoc dl, SelectionDAG &DAG,
2215 SmallVectorImpl<SDValue> &InVals) const {
2216 // TODO: add description of PPC stack frame format, or at least some docs.
2218 MachineFunction &MF = DAG.getMachineFunction();
2219 MachineFrameInfo *MFI = MF.getFrameInfo();
2220 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2222 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2223 // Potential tail calls could cause overwriting of argument stack slots.
2224 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2225 (CallConv == CallingConv::Fast));
2226 unsigned PtrByteSize = 8;
2228 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2229 // Area that is at least reserved in caller of this function.
2230 unsigned MinReservedArea = ArgOffset;
2232 static const uint16_t GPR[] = {
2233 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2234 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2237 static const uint16_t *FPR = GetFPR();
2239 static const uint16_t VR[] = {
2240 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2241 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2244 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2245 const unsigned Num_FPR_Regs = 13;
2246 const unsigned Num_VR_Regs = array_lengthof(VR);
2248 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2250 // Add DAG nodes to load the arguments or copy them out of registers. On
2251 // entry to a function on PPC, the arguments start after the linkage area,
2252 // although the first ones are often in registers.
2254 SmallVector<SDValue, 8> MemOps;
2255 unsigned nAltivecParamsAtEnd = 0;
2256 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2257 unsigned CurArgIdx = 0;
2258 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2260 bool needsLoad = false;
2261 EVT ObjectVT = Ins[ArgNo].VT;
2262 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2263 unsigned ArgSize = ObjSize;
2264 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2265 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2266 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2268 unsigned CurArgOffset = ArgOffset;
2270 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2271 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2272 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2274 MinReservedArea = ((MinReservedArea+15)/16)*16;
2275 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2279 nAltivecParamsAtEnd++;
2281 // Calculate min reserved area.
2282 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2286 // FIXME the codegen can be much improved in some cases.
2287 // We do not have to keep everything in memory.
2288 if (Flags.isByVal()) {
2289 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2290 ObjSize = Flags.getByValSize();
2291 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2292 // Empty aggregate parameters do not take up registers. Examples:
2296 // etc. However, we have to provide a place-holder in InVals, so
2297 // pretend we have an 8-byte item at the current address for that
2300 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2301 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2302 InVals.push_back(FIN);
2305 // All aggregates smaller than 8 bytes must be passed right-justified.
2306 if (ObjSize < PtrByteSize)
2307 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2308 // The value of the object is its address.
2309 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2310 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2311 InVals.push_back(FIN);
2314 if (GPR_idx != Num_GPR_Regs) {
2315 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2316 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2319 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2320 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2321 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2322 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2323 MachinePointerInfo(FuncArg, CurArgOffset),
2324 ObjType, false, false, 0);
2326 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2327 // store the whole register as-is to the parameter save area
2328 // slot. The address of the parameter was already calculated
2329 // above (InVals.push_back(FIN)) to be the right-justified
2330 // offset within the slot. For this store, we need a new
2331 // frame index that points at the beginning of the slot.
2332 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2333 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2334 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2335 MachinePointerInfo(FuncArg, ArgOffset),
2339 MemOps.push_back(Store);
2342 // Whether we copied from a register or not, advance the offset
2343 // into the parameter save area by a full doubleword.
2344 ArgOffset += PtrByteSize;
2348 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2349 // Store whatever pieces of the object are in registers
2350 // to memory. ArgOffset will be the address of the beginning
2352 if (GPR_idx != Num_GPR_Regs) {
2354 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2355 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2356 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2357 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2358 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2359 MachinePointerInfo(FuncArg, ArgOffset),
2361 MemOps.push_back(Store);
2363 ArgOffset += PtrByteSize;
2365 ArgOffset += ArgSize - j;
2372 switch (ObjectVT.getSimpleVT().SimpleTy) {
2373 default: llvm_unreachable("Unhandled argument type!");
2376 if (GPR_idx != Num_GPR_Regs) {
2377 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2378 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2380 if (ObjectVT == MVT::i32)
2381 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2382 // value to MVT::i64 and then truncate to the correct register size.
2383 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2388 ArgSize = PtrByteSize;
2395 // Every 8 bytes of argument space consumes one of the GPRs available for
2396 // argument passing.
2397 if (GPR_idx != Num_GPR_Regs) {
2400 if (FPR_idx != Num_FPR_Regs) {
2403 if (ObjectVT == MVT::f32)
2404 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2406 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2408 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2412 ArgSize = PtrByteSize;
2421 // Note that vector arguments in registers don't reserve stack space,
2422 // except in varargs functions.
2423 if (VR_idx != Num_VR_Regs) {
2424 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2425 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2427 while ((ArgOffset % 16) != 0) {
2428 ArgOffset += PtrByteSize;
2429 if (GPR_idx != Num_GPR_Regs)
2433 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2437 // Vectors are aligned.
2438 ArgOffset = ((ArgOffset+15)/16)*16;
2439 CurArgOffset = ArgOffset;
2446 // We need to load the argument to a virtual register if we determined
2447 // above that we ran out of physical registers of the appropriate type.
2449 int FI = MFI->CreateFixedObject(ObjSize,
2450 CurArgOffset + (ArgSize - ObjSize),
2452 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2453 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2454 false, false, false, 0);
2457 InVals.push_back(ArgVal);
2460 // Set the size that is at least reserved in caller of this function. Tail
2461 // call optimized functions' reserved stack space needs to be aligned so that
2462 // taking the difference between two stack areas will result in an aligned
2464 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2466 // If the function takes variable number of arguments, make a frame index for
2467 // the start of the first vararg value... for expansion of llvm.va_start.
2469 int Depth = ArgOffset;
2471 FuncInfo->setVarArgsFrameIndex(
2472 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2473 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2475 // If this function is vararg, store any remaining integer argument regs
2476 // to their spots on the stack so that they may be loaded by deferencing the
2477 // result of va_next.
2478 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2479 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2480 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2481 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2482 MachinePointerInfo(), false, false, 0);
2483 MemOps.push_back(Store);
2484 // Increment the address by four for the next argument to store
2485 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2486 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2490 if (!MemOps.empty())
2491 Chain = DAG.getNode(ISD::TokenFactor, dl,
2492 MVT::Other, &MemOps[0], MemOps.size());
2498 PPCTargetLowering::LowerFormalArguments_Darwin(
2500 CallingConv::ID CallConv, bool isVarArg,
2501 const SmallVectorImpl<ISD::InputArg>
2503 DebugLoc dl, SelectionDAG &DAG,
2504 SmallVectorImpl<SDValue> &InVals) const {
2505 // TODO: add description of PPC stack frame format, or at least some docs.
2507 MachineFunction &MF = DAG.getMachineFunction();
2508 MachineFrameInfo *MFI = MF.getFrameInfo();
2509 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2511 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2512 bool isPPC64 = PtrVT == MVT::i64;
2513 // Potential tail calls could cause overwriting of argument stack slots.
2514 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2515 (CallConv == CallingConv::Fast));
2516 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2518 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2519 // Area that is at least reserved in caller of this function.
2520 unsigned MinReservedArea = ArgOffset;
2522 static const uint16_t GPR_32[] = { // 32-bit registers.
2523 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2524 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2526 static const uint16_t GPR_64[] = { // 64-bit registers.
2527 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2528 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2531 static const uint16_t *FPR = GetFPR();
2533 static const uint16_t VR[] = {
2534 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2535 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2538 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2539 const unsigned Num_FPR_Regs = 13;
2540 const unsigned Num_VR_Regs = array_lengthof( VR);
2542 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2544 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2546 // In 32-bit non-varargs functions, the stack space for vectors is after the
2547 // stack space for non-vectors. We do not use this space unless we have
2548 // too many vectors to fit in registers, something that only occurs in
2549 // constructed examples:), but we have to walk the arglist to figure
2550 // that out...for the pathological case, compute VecArgOffset as the
2551 // start of the vector parameter area. Computing VecArgOffset is the
2552 // entire point of the following loop.
2553 unsigned VecArgOffset = ArgOffset;
2554 if (!isVarArg && !isPPC64) {
2555 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2557 EVT ObjectVT = Ins[ArgNo].VT;
2558 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2560 if (Flags.isByVal()) {
2561 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2562 unsigned ObjSize = Flags.getByValSize();
2564 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2565 VecArgOffset += ArgSize;
2569 switch(ObjectVT.getSimpleVT().SimpleTy) {
2570 default: llvm_unreachable("Unhandled argument type!");
2575 case MVT::i64: // PPC64
2577 // FIXME: We are guaranteed to be !isPPC64 at this point.
2578 // Does MVT::i64 apply?
2585 // Nothing to do, we're only looking at Nonvector args here.
2590 // We've found where the vector parameter area in memory is. Skip the
2591 // first 12 parameters; these don't use that memory.
2592 VecArgOffset = ((VecArgOffset+15)/16)*16;
2593 VecArgOffset += 12*16;
2595 // Add DAG nodes to load the arguments or copy them out of registers. On
2596 // entry to a function on PPC, the arguments start after the linkage area,
2597 // although the first ones are often in registers.
2599 SmallVector<SDValue, 8> MemOps;
2600 unsigned nAltivecParamsAtEnd = 0;
2601 // FIXME: FuncArg and Ins[ArgNo] must reference the same argument.
2602 // When passing anonymous aggregates, this is currently not true.
2603 // See LowerFormalArguments_64SVR4 for a fix.
2604 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2605 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2607 bool needsLoad = false;
2608 EVT ObjectVT = Ins[ArgNo].VT;
2609 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2610 unsigned ArgSize = ObjSize;
2611 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2613 unsigned CurArgOffset = ArgOffset;
2615 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2616 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2617 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2618 if (isVarArg || isPPC64) {
2619 MinReservedArea = ((MinReservedArea+15)/16)*16;
2620 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2623 } else nAltivecParamsAtEnd++;
2625 // Calculate min reserved area.
2626 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2630 // FIXME the codegen can be much improved in some cases.
2631 // We do not have to keep everything in memory.
2632 if (Flags.isByVal()) {
2633 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2634 ObjSize = Flags.getByValSize();
2635 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2636 // Objects of size 1 and 2 are right justified, everything else is
2637 // left justified. This means the memory address is adjusted forwards.
2638 if (ObjSize==1 || ObjSize==2) {
2639 CurArgOffset = CurArgOffset + (4 - ObjSize);
2641 // The value of the object is its address.
2642 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2643 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2644 InVals.push_back(FIN);
2645 if (ObjSize==1 || ObjSize==2) {
2646 if (GPR_idx != Num_GPR_Regs) {
2649 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2651 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2652 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2653 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2654 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2655 MachinePointerInfo(FuncArg,
2657 ObjType, false, false, 0);
2658 MemOps.push_back(Store);
2662 ArgOffset += PtrByteSize;
2666 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2667 // Store whatever pieces of the object are in registers
2668 // to memory. ArgOffset will be the address of the beginning
2670 if (GPR_idx != Num_GPR_Regs) {
2673 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2675 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2676 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2677 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2678 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2679 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2680 MachinePointerInfo(FuncArg, ArgOffset),
2682 MemOps.push_back(Store);
2684 ArgOffset += PtrByteSize;
2686 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2693 switch (ObjectVT.getSimpleVT().SimpleTy) {
2694 default: llvm_unreachable("Unhandled argument type!");
2697 if (GPR_idx != Num_GPR_Regs) {
2698 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2699 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2703 ArgSize = PtrByteSize;
2705 // All int arguments reserve stack space in the Darwin ABI.
2706 ArgOffset += PtrByteSize;
2710 case MVT::i64: // PPC64
2711 if (GPR_idx != Num_GPR_Regs) {
2712 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2713 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2715 if (ObjectVT == MVT::i32)
2716 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2717 // value to MVT::i64 and then truncate to the correct register size.
2718 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2723 ArgSize = PtrByteSize;
2725 // All int arguments reserve stack space in the Darwin ABI.
2731 // Every 4 bytes of argument space consumes one of the GPRs available for
2732 // argument passing.
2733 if (GPR_idx != Num_GPR_Regs) {
2735 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2738 if (FPR_idx != Num_FPR_Regs) {
2741 if (ObjectVT == MVT::f32)
2742 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2744 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2746 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2752 // All FP arguments reserve stack space in the Darwin ABI.
2753 ArgOffset += isPPC64 ? 8 : ObjSize;
2759 // Note that vector arguments in registers don't reserve stack space,
2760 // except in varargs functions.
2761 if (VR_idx != Num_VR_Regs) {
2762 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2763 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2765 while ((ArgOffset % 16) != 0) {
2766 ArgOffset += PtrByteSize;
2767 if (GPR_idx != Num_GPR_Regs)
2771 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2775 if (!isVarArg && !isPPC64) {
2776 // Vectors go after all the nonvectors.
2777 CurArgOffset = VecArgOffset;
2780 // Vectors are aligned.
2781 ArgOffset = ((ArgOffset+15)/16)*16;
2782 CurArgOffset = ArgOffset;
2790 // We need to load the argument to a virtual register if we determined above
2791 // that we ran out of physical registers of the appropriate type.
2793 int FI = MFI->CreateFixedObject(ObjSize,
2794 CurArgOffset + (ArgSize - ObjSize),
2796 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2797 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2798 false, false, false, 0);
2801 InVals.push_back(ArgVal);
2804 // Set the size that is at least reserved in caller of this function. Tail
2805 // call optimized functions' reserved stack space needs to be aligned so that
2806 // taking the difference between two stack areas will result in an aligned
2808 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2810 // If the function takes variable number of arguments, make a frame index for
2811 // the start of the first vararg value... for expansion of llvm.va_start.
2813 int Depth = ArgOffset;
2815 FuncInfo->setVarArgsFrameIndex(
2816 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2818 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2820 // If this function is vararg, store any remaining integer argument regs
2821 // to their spots on the stack so that they may be loaded by deferencing the
2822 // result of va_next.
2823 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2827 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2829 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2831 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2832 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2833 MachinePointerInfo(), false, false, 0);
2834 MemOps.push_back(Store);
2835 // Increment the address by four for the next argument to store
2836 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2837 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2841 if (!MemOps.empty())
2842 Chain = DAG.getNode(ISD::TokenFactor, dl,
2843 MVT::Other, &MemOps[0], MemOps.size());
2848 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2849 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2851 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2855 const SmallVectorImpl<ISD::OutputArg>
2857 const SmallVectorImpl<SDValue> &OutVals,
2858 unsigned &nAltivecParamsAtEnd) {
2859 // Count how many bytes are to be pushed on the stack, including the linkage
2860 // area, and parameter passing area. We start with 24/48 bytes, which is
2861 // prereserved space for [SP][CR][LR][3 x unused].
2862 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2863 unsigned NumOps = Outs.size();
2864 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2866 // Add up all the space actually used.
2867 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2868 // they all go in registers, but we must reserve stack space for them for
2869 // possible use by the caller. In varargs or 64-bit calls, parameters are
2870 // assigned stack space in order, with padding so Altivec parameters are
2872 nAltivecParamsAtEnd = 0;
2873 for (unsigned i = 0; i != NumOps; ++i) {
2874 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2875 EVT ArgVT = Outs[i].VT;
2876 // Varargs Altivec parameters are padded to a 16 byte boundary.
2877 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2878 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2879 if (!isVarArg && !isPPC64) {
2880 // Non-varargs Altivec parameters go after all the non-Altivec
2881 // parameters; handle those later so we know how much padding we need.
2882 nAltivecParamsAtEnd++;
2885 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2886 NumBytes = ((NumBytes+15)/16)*16;
2888 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2891 // Allow for Altivec parameters at the end, if needed.
2892 if (nAltivecParamsAtEnd) {
2893 NumBytes = ((NumBytes+15)/16)*16;
2894 NumBytes += 16*nAltivecParamsAtEnd;
2897 // The prolog code of the callee may store up to 8 GPR argument registers to
2898 // the stack, allowing va_start to index over them in memory if its varargs.
2899 // Because we cannot tell if this is needed on the caller side, we have to
2900 // conservatively assume that it is needed. As such, make sure we have at
2901 // least enough stack space for the caller to store the 8 GPRs.
2902 NumBytes = std::max(NumBytes,
2903 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2905 // Tail call needs the stack to be aligned.
2906 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2907 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2908 getFrameLowering()->getStackAlignment();
2909 unsigned AlignMask = TargetAlign-1;
2910 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2916 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2917 /// adjusted to accommodate the arguments for the tailcall.
2918 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2919 unsigned ParamSize) {
2921 if (!isTailCall) return 0;
2923 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2924 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2925 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2926 // Remember only if the new adjustement is bigger.
2927 if (SPDiff < FI->getTailCallSPDelta())
2928 FI->setTailCallSPDelta(SPDiff);
2933 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2934 /// for tail call optimization. Targets which want to do tail call
2935 /// optimization should implement this function.
2937 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2938 CallingConv::ID CalleeCC,
2940 const SmallVectorImpl<ISD::InputArg> &Ins,
2941 SelectionDAG& DAG) const {
2942 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2945 // Variable argument functions are not supported.
2949 MachineFunction &MF = DAG.getMachineFunction();
2950 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2951 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2952 // Functions containing by val parameters are not supported.
2953 for (unsigned i = 0; i != Ins.size(); i++) {
2954 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2955 if (Flags.isByVal()) return false;
2958 // Non PIC/GOT tail calls are supported.
2959 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2962 // At the moment we can only do local tail calls (in same module, hidden
2963 // or protected) if we are generating PIC.
2964 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2965 return G->getGlobal()->hasHiddenVisibility()
2966 || G->getGlobal()->hasProtectedVisibility();
2972 /// isCallCompatibleAddress - Return the immediate to use if the specified
2973 /// 32-bit value is representable in the immediate field of a BxA instruction.
2974 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2975 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2978 int Addr = C->getZExtValue();
2979 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2980 SignExtend32<26>(Addr) != Addr)
2981 return 0; // Top 6 bits have to be sext of immediate.
2983 return DAG.getConstant((int)C->getZExtValue() >> 2,
2984 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2989 struct TailCallArgumentInfo {
2994 TailCallArgumentInfo() : FrameIdx(0) {}
2999 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3001 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3003 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
3004 SmallVector<SDValue, 8> &MemOpChains,
3006 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3007 SDValue Arg = TailCallArgs[i].Arg;
3008 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3009 int FI = TailCallArgs[i].FrameIdx;
3010 // Store relative to framepointer.
3011 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3012 MachinePointerInfo::getFixedStack(FI),
3017 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3018 /// the appropriate stack slot for the tail call optimized function call.
3019 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3020 MachineFunction &MF,
3029 // Calculate the new stack slot for the return address.
3030 int SlotSize = isPPC64 ? 8 : 4;
3031 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3033 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3034 NewRetAddrLoc, true);
3035 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3036 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3037 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3038 MachinePointerInfo::getFixedStack(NewRetAddr),
3041 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3042 // slot as the FP is never overwritten.
3045 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3046 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3048 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3049 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3050 MachinePointerInfo::getFixedStack(NewFPIdx),
3057 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3058 /// the position of the argument.
3060 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3061 SDValue Arg, int SPDiff, unsigned ArgOffset,
3062 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
3063 int Offset = ArgOffset + SPDiff;
3064 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3065 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3066 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3067 SDValue FIN = DAG.getFrameIndex(FI, VT);
3068 TailCallArgumentInfo Info;
3070 Info.FrameIdxOp = FIN;
3072 TailCallArguments.push_back(Info);
3075 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3076 /// stack slot. Returns the chain as result and the loaded frame pointers in
3077 /// LROpOut/FPOpout. Used when tail calling.
3078 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3084 DebugLoc dl) const {
3086 // Load the LR and FP stack slot for later adjusting.
3087 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3088 LROpOut = getReturnAddrFrameIndex(DAG);
3089 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3090 false, false, false, 0);
3091 Chain = SDValue(LROpOut.getNode(), 1);
3093 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3094 // slot as the FP is never overwritten.
3096 FPOpOut = getFramePointerFrameIndex(DAG);
3097 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3098 false, false, false, 0);
3099 Chain = SDValue(FPOpOut.getNode(), 1);
3105 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3106 /// by "Src" to address "Dst" of size "Size". Alignment information is
3107 /// specified by the specific parameter attribute. The copy will be passed as
3108 /// a byval function parameter.
3109 /// Sometimes what we are copying is the end of a larger object, the part that
3110 /// does not fit in registers.
3112 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3113 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3115 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3116 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3117 false, false, MachinePointerInfo(0),
3118 MachinePointerInfo(0));
3121 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3124 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3125 SDValue Arg, SDValue PtrOff, int SPDiff,
3126 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3127 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
3128 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
3130 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3135 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3137 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3138 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3139 DAG.getConstant(ArgOffset, PtrVT));
3141 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3142 MachinePointerInfo(), false, false, 0));
3143 // Calculate and remember argument location.
3144 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3149 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3150 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3151 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3152 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
3153 MachineFunction &MF = DAG.getMachineFunction();
3155 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3156 // might overwrite each other in case of tail call optimization.
3157 SmallVector<SDValue, 8> MemOpChains2;
3158 // Do not flag preceding copytoreg stuff together with the following stuff.
3160 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3162 if (!MemOpChains2.empty())
3163 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3164 &MemOpChains2[0], MemOpChains2.size());
3166 // Store the return address to the appropriate stack slot.
3167 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3168 isPPC64, isDarwinABI, dl);
3170 // Emit callseq_end just before tailcall node.
3171 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3172 DAG.getIntPtrConstant(0, true), InFlag);
3173 InFlag = Chain.getValue(1);
3177 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3178 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
3179 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
3180 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
3181 const PPCSubtarget &PPCSubTarget) {
3183 bool isPPC64 = PPCSubTarget.isPPC64();
3184 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3186 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3187 NodeTys.push_back(MVT::Other); // Returns a chain
3188 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3190 unsigned CallOpc = PPCISD::CALL;
3192 bool needIndirectCall = true;
3193 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3194 // If this is an absolute destination address, use the munged value.
3195 Callee = SDValue(Dest, 0);
3196 needIndirectCall = false;
3199 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3200 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3201 // Use indirect calls for ALL functions calls in JIT mode, since the
3202 // far-call stubs may be outside relocation limits for a BL instruction.
3203 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3204 unsigned OpFlags = 0;
3205 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3206 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3207 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3208 (G->getGlobal()->isDeclaration() ||
3209 G->getGlobal()->isWeakForLinker())) {
3210 // PC-relative references to external symbols should go through $stub,
3211 // unless we're building with the leopard linker or later, which
3212 // automatically synthesizes these stubs.
3213 OpFlags = PPCII::MO_DARWIN_STUB;
3216 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3217 // every direct call is) turn it into a TargetGlobalAddress /
3218 // TargetExternalSymbol node so that legalize doesn't hack it.
3219 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3220 Callee.getValueType(),
3222 needIndirectCall = false;
3226 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3227 unsigned char OpFlags = 0;
3229 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3230 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3231 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3232 // PC-relative references to external symbols should go through $stub,
3233 // unless we're building with the leopard linker or later, which
3234 // automatically synthesizes these stubs.
3235 OpFlags = PPCII::MO_DARWIN_STUB;
3238 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3240 needIndirectCall = false;
3243 if (needIndirectCall) {
3244 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3245 // to do the call, we can't use PPCISD::CALL.
3246 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3248 if (isSVR4ABI && isPPC64) {
3249 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3250 // entry point, but to the function descriptor (the function entry point
3251 // address is part of the function descriptor though).
3252 // The function descriptor is a three doubleword structure with the
3253 // following fields: function entry point, TOC base address and
3254 // environment pointer.
3255 // Thus for a call through a function pointer, the following actions need
3257 // 1. Save the TOC of the caller in the TOC save area of its stack
3258 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3259 // 2. Load the address of the function entry point from the function
3261 // 3. Load the TOC of the callee from the function descriptor into r2.
3262 // 4. Load the environment pointer from the function descriptor into
3264 // 5. Branch to the function entry point address.
3265 // 6. On return of the callee, the TOC of the caller needs to be
3266 // restored (this is done in FinishCall()).
3268 // All those operations are flagged together to ensure that no other
3269 // operations can be scheduled in between. E.g. without flagging the
3270 // operations together, a TOC access in the caller could be scheduled
3271 // between the load of the callee TOC and the branch to the callee, which
3272 // results in the TOC access going through the TOC of the callee instead
3273 // of going through the TOC of the caller, which leads to incorrect code.
3275 // Load the address of the function entry point from the function
3277 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3278 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3279 InFlag.getNode() ? 3 : 2);
3280 Chain = LoadFuncPtr.getValue(1);
3281 InFlag = LoadFuncPtr.getValue(2);
3283 // Load environment pointer into r11.
3284 // Offset of the environment pointer within the function descriptor.
3285 SDValue PtrOff = DAG.getIntPtrConstant(16);
3287 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3288 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3290 Chain = LoadEnvPtr.getValue(1);
3291 InFlag = LoadEnvPtr.getValue(2);
3293 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3295 Chain = EnvVal.getValue(0);
3296 InFlag = EnvVal.getValue(1);
3298 // Load TOC of the callee into r2. We are using a target-specific load
3299 // with r2 hard coded, because the result of a target-independent load
3300 // would never go directly into r2, since r2 is a reserved register (which
3301 // prevents the register allocator from allocating it), resulting in an
3302 // additional register being allocated and an unnecessary move instruction
3304 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3305 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3307 Chain = LoadTOCPtr.getValue(0);
3308 InFlag = LoadTOCPtr.getValue(1);
3310 MTCTROps[0] = Chain;
3311 MTCTROps[1] = LoadFuncPtr;
3312 MTCTROps[2] = InFlag;
3315 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3316 2 + (InFlag.getNode() != 0));
3317 InFlag = Chain.getValue(1);
3320 NodeTys.push_back(MVT::Other);
3321 NodeTys.push_back(MVT::Glue);
3322 Ops.push_back(Chain);
3323 CallOpc = PPCISD::BCTRL;
3325 // Add use of X11 (holding environment pointer)
3326 if (isSVR4ABI && isPPC64)
3327 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3328 // Add CTR register as callee so a bctr can be emitted later.
3330 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3333 // If this is a direct call, pass the chain and the callee.
3334 if (Callee.getNode()) {
3335 Ops.push_back(Chain);
3336 Ops.push_back(Callee);
3338 // If this is a tail call add stack pointer delta.
3340 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3342 // Add argument registers to the end of the list so that they are known live
3344 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3345 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3346 RegsToPass[i].second.getValueType()));
3352 bool isLocalCall(const SDValue &Callee)
3354 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3355 return !G->getGlobal()->isDeclaration() &&
3356 !G->getGlobal()->isWeakForLinker();
3361 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3362 CallingConv::ID CallConv, bool isVarArg,
3363 const SmallVectorImpl<ISD::InputArg> &Ins,
3364 DebugLoc dl, SelectionDAG &DAG,
3365 SmallVectorImpl<SDValue> &InVals) const {
3367 SmallVector<CCValAssign, 16> RVLocs;
3368 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3369 getTargetMachine(), RVLocs, *DAG.getContext());
3370 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3372 // Copy all of the result registers out of their specified physreg.
3373 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3374 CCValAssign &VA = RVLocs[i];
3375 assert(VA.isRegLoc() && "Can only return in registers!");
3377 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3378 VA.getLocReg(), VA.getLocVT(), InFlag);
3379 Chain = Val.getValue(1);
3380 InFlag = Val.getValue(2);
3382 switch (VA.getLocInfo()) {
3383 default: llvm_unreachable("Unknown loc info!");
3384 case CCValAssign::Full: break;
3385 case CCValAssign::AExt:
3386 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3388 case CCValAssign::ZExt:
3389 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3390 DAG.getValueType(VA.getValVT()));
3391 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3393 case CCValAssign::SExt:
3394 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3395 DAG.getValueType(VA.getValVT()));
3396 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3400 InVals.push_back(Val);
3407 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
3408 bool isTailCall, bool isVarArg,
3410 SmallVector<std::pair<unsigned, SDValue>, 8>
3412 SDValue InFlag, SDValue Chain,
3414 int SPDiff, unsigned NumBytes,
3415 const SmallVectorImpl<ISD::InputArg> &Ins,
3416 SmallVectorImpl<SDValue> &InVals) const {
3417 std::vector<EVT> NodeTys;
3418 SmallVector<SDValue, 8> Ops;
3419 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3420 isTailCall, RegsToPass, Ops, NodeTys,
3423 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3424 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3425 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3427 // When performing tail call optimization the callee pops its arguments off
3428 // the stack. Account for this here so these bytes can be pushed back on in
3429 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3430 int BytesCalleePops =
3431 (CallConv == CallingConv::Fast &&
3432 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3434 // Add a register mask operand representing the call-preserved registers.
3435 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3436 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3437 assert(Mask && "Missing call preserved mask for calling convention");
3438 Ops.push_back(DAG.getRegisterMask(Mask));
3440 if (InFlag.getNode())
3441 Ops.push_back(InFlag);
3445 assert(((Callee.getOpcode() == ISD::Register &&
3446 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3447 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3448 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3449 isa<ConstantSDNode>(Callee)) &&
3450 "Expecting an global address, external symbol, absolute value or register");
3452 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3455 // Add a NOP immediately after the branch instruction when using the 64-bit
3456 // SVR4 ABI. At link time, if caller and callee are in a different module and
3457 // thus have a different TOC, the call will be replaced with a call to a stub
3458 // function which saves the current TOC, loads the TOC of the callee and
3459 // branches to the callee. The NOP will be replaced with a load instruction
3460 // which restores the TOC of the caller from the TOC save slot of the current
3461 // stack frame. If caller and callee belong to the same module (and have the
3462 // same TOC), the NOP will remain unchanged.
3464 bool needsTOCRestore = false;
3465 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3466 if (CallOpc == PPCISD::BCTRL) {
3467 // This is a call through a function pointer.
3468 // Restore the caller TOC from the save area into R2.
3469 // See PrepareCall() for more information about calls through function
3470 // pointers in the 64-bit SVR4 ABI.
3471 // We are using a target-specific load with r2 hard coded, because the
3472 // result of a target-independent load would never go directly into r2,
3473 // since r2 is a reserved register (which prevents the register allocator
3474 // from allocating it), resulting in an additional register being
3475 // allocated and an unnecessary move instruction being generated.
3476 needsTOCRestore = true;
3477 } else if ((CallOpc == PPCISD::CALL) && !isLocalCall(Callee)) {
3478 // Otherwise insert NOP for non-local calls.
3479 CallOpc = PPCISD::CALL_NOP;
3483 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3484 InFlag = Chain.getValue(1);
3486 if (needsTOCRestore) {
3487 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3488 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3489 InFlag = Chain.getValue(1);
3492 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3493 DAG.getIntPtrConstant(BytesCalleePops, true),
3496 InFlag = Chain.getValue(1);
3498 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3499 Ins, dl, DAG, InVals);
3503 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3504 SmallVectorImpl<SDValue> &InVals) const {
3505 SelectionDAG &DAG = CLI.DAG;
3506 DebugLoc &dl = CLI.DL;
3507 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3508 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3509 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3510 SDValue Chain = CLI.Chain;
3511 SDValue Callee = CLI.Callee;
3512 bool &isTailCall = CLI.IsTailCall;
3513 CallingConv::ID CallConv = CLI.CallConv;
3514 bool isVarArg = CLI.IsVarArg;
3517 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3520 if (PPCSubTarget.isSVR4ABI()) {
3521 if (PPCSubTarget.isPPC64())
3522 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3523 isTailCall, Outs, OutVals, Ins,
3526 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3527 isTailCall, Outs, OutVals, Ins,
3531 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3532 isTailCall, Outs, OutVals, Ins,
3537 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3538 CallingConv::ID CallConv, bool isVarArg,
3540 const SmallVectorImpl<ISD::OutputArg> &Outs,
3541 const SmallVectorImpl<SDValue> &OutVals,
3542 const SmallVectorImpl<ISD::InputArg> &Ins,
3543 DebugLoc dl, SelectionDAG &DAG,
3544 SmallVectorImpl<SDValue> &InVals) const {
3545 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3546 // of the 32-bit SVR4 ABI stack frame layout.
3548 assert((CallConv == CallingConv::C ||
3549 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3551 unsigned PtrByteSize = 4;
3553 MachineFunction &MF = DAG.getMachineFunction();
3555 // Mark this function as potentially containing a function that contains a
3556 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3557 // and restoring the callers stack pointer in this functions epilog. This is
3558 // done because by tail calling the called function might overwrite the value
3559 // in this function's (MF) stack pointer stack slot 0(SP).
3560 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3561 CallConv == CallingConv::Fast)
3562 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3564 // Count how many bytes are to be pushed on the stack, including the linkage
3565 // area, parameter list area and the part of the local variable space which
3566 // contains copies of aggregates which are passed by value.
3568 // Assign locations to all of the outgoing arguments.
3569 SmallVector<CCValAssign, 16> ArgLocs;
3570 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3571 getTargetMachine(), ArgLocs, *DAG.getContext());
3573 // Reserve space for the linkage area on the stack.
3574 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3577 // Handle fixed and variable vector arguments differently.
3578 // Fixed vector arguments go into registers as long as registers are
3579 // available. Variable vector arguments always go into memory.
3580 unsigned NumArgs = Outs.size();
3582 for (unsigned i = 0; i != NumArgs; ++i) {
3583 MVT ArgVT = Outs[i].VT;
3584 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3587 if (Outs[i].IsFixed) {
3588 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3591 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3597 errs() << "Call operand #" << i << " has unhandled type "
3598 << EVT(ArgVT).getEVTString() << "\n";
3600 llvm_unreachable(0);
3604 // All arguments are treated the same.
3605 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3608 // Assign locations to all of the outgoing aggregate by value arguments.
3609 SmallVector<CCValAssign, 16> ByValArgLocs;
3610 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3611 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3613 // Reserve stack space for the allocations in CCInfo.
3614 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3616 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3618 // Size of the linkage area, parameter list area and the part of the local
3619 // space variable where copies of aggregates which are passed by value are
3621 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3623 // Calculate by how many bytes the stack has to be adjusted in case of tail
3624 // call optimization.
3625 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3627 // Adjust the stack pointer for the new arguments...
3628 // These operations are automatically eliminated by the prolog/epilog pass
3629 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3630 SDValue CallSeqStart = Chain;
3632 // Load the return address and frame pointer so it can be moved somewhere else
3635 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3638 // Set up a copy of the stack pointer for use loading and storing any
3639 // arguments that may not fit in the registers available for argument
3641 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3643 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3644 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3645 SmallVector<SDValue, 8> MemOpChains;
3647 bool seenFloatArg = false;
3648 // Walk the register/memloc assignments, inserting copies/loads.
3649 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3652 CCValAssign &VA = ArgLocs[i];
3653 SDValue Arg = OutVals[i];
3654 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3656 if (Flags.isByVal()) {
3657 // Argument is an aggregate which is passed by value, thus we need to
3658 // create a copy of it in the local variable space of the current stack
3659 // frame (which is the stack frame of the caller) and pass the address of
3660 // this copy to the callee.
3661 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3662 CCValAssign &ByValVA = ByValArgLocs[j++];
3663 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3665 // Memory reserved in the local variable space of the callers stack frame.
3666 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3668 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3669 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3671 // Create a copy of the argument in the local area of the current
3673 SDValue MemcpyCall =
3674 CreateCopyOfByValArgument(Arg, PtrOff,
3675 CallSeqStart.getNode()->getOperand(0),
3678 // This must go outside the CALLSEQ_START..END.
3679 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3680 CallSeqStart.getNode()->getOperand(1));
3681 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3682 NewCallSeqStart.getNode());
3683 Chain = CallSeqStart = NewCallSeqStart;
3685 // Pass the address of the aggregate copy on the stack either in a
3686 // physical register or in the parameter list area of the current stack
3687 // frame to the callee.
3691 if (VA.isRegLoc()) {
3692 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3693 // Put argument in a physical register.
3694 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3696 // Put argument in the parameter list area of the current stack frame.
3697 assert(VA.isMemLoc());
3698 unsigned LocMemOffset = VA.getLocMemOffset();
3701 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3702 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3704 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3705 MachinePointerInfo(),
3708 // Calculate and remember argument location.
3709 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3715 if (!MemOpChains.empty())
3716 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3717 &MemOpChains[0], MemOpChains.size());
3719 // Build a sequence of copy-to-reg nodes chained together with token chain
3720 // and flag operands which copy the outgoing args into the appropriate regs.
3722 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3723 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3724 RegsToPass[i].second, InFlag);
3725 InFlag = Chain.getValue(1);
3728 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3731 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3732 SDValue Ops[] = { Chain, InFlag };
3734 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3735 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3737 InFlag = Chain.getValue(1);
3741 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3742 false, TailCallArguments);
3744 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3745 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3749 // Copy an argument into memory, being careful to do this outside the
3750 // call sequence for the call to which the argument belongs.
3752 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3753 SDValue CallSeqStart,
3754 ISD::ArgFlagsTy Flags,
3756 DebugLoc dl) const {
3757 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3758 CallSeqStart.getNode()->getOperand(0),
3760 // The MEMCPY must go outside the CALLSEQ_START..END.
3761 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3762 CallSeqStart.getNode()->getOperand(1));
3763 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3764 NewCallSeqStart.getNode());
3765 return NewCallSeqStart;
3769 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3770 CallingConv::ID CallConv, bool isVarArg,
3772 const SmallVectorImpl<ISD::OutputArg> &Outs,
3773 const SmallVectorImpl<SDValue> &OutVals,
3774 const SmallVectorImpl<ISD::InputArg> &Ins,
3775 DebugLoc dl, SelectionDAG &DAG,
3776 SmallVectorImpl<SDValue> &InVals) const {
3778 unsigned NumOps = Outs.size();
3780 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3781 unsigned PtrByteSize = 8;
3783 MachineFunction &MF = DAG.getMachineFunction();
3785 // Mark this function as potentially containing a function that contains a
3786 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3787 // and restoring the callers stack pointer in this functions epilog. This is
3788 // done because by tail calling the called function might overwrite the value
3789 // in this function's (MF) stack pointer stack slot 0(SP).
3790 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3791 CallConv == CallingConv::Fast)
3792 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3794 unsigned nAltivecParamsAtEnd = 0;
3796 // Count how many bytes are to be pushed on the stack, including the linkage
3797 // area, and parameter passing area. We start with at least 48 bytes, which
3798 // is reserved space for [SP][CR][LR][3 x unused].
3799 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3802 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3803 Outs, OutVals, nAltivecParamsAtEnd);
3805 // Calculate by how many bytes the stack has to be adjusted in case of tail
3806 // call optimization.
3807 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3809 // To protect arguments on the stack from being clobbered in a tail call,
3810 // force all the loads to happen before doing any other lowering.
3812 Chain = DAG.getStackArgumentTokenFactor(Chain);
3814 // Adjust the stack pointer for the new arguments...
3815 // These operations are automatically eliminated by the prolog/epilog pass
3816 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3817 SDValue CallSeqStart = Chain;
3819 // Load the return address and frame pointer so it can be move somewhere else
3822 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3825 // Set up a copy of the stack pointer for use loading and storing any
3826 // arguments that may not fit in the registers available for argument
3828 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3830 // Figure out which arguments are going to go in registers, and which in
3831 // memory. Also, if this is a vararg function, floating point operations
3832 // must be stored to our stack, and loaded into integer regs as well, if
3833 // any integer regs are available for argument passing.
3834 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3835 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3837 static const uint16_t GPR[] = {
3838 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3839 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3841 static const uint16_t *FPR = GetFPR();
3843 static const uint16_t VR[] = {
3844 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3845 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3847 const unsigned NumGPRs = array_lengthof(GPR);
3848 const unsigned NumFPRs = 13;
3849 const unsigned NumVRs = array_lengthof(VR);
3851 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3852 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3854 SmallVector<SDValue, 8> MemOpChains;
3855 for (unsigned i = 0; i != NumOps; ++i) {
3856 SDValue Arg = OutVals[i];
3857 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3859 // PtrOff will be used to store the current argument to the stack if a
3860 // register cannot be found for it.
3863 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3865 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3867 // Promote integers to 64-bit values.
3868 if (Arg.getValueType() == MVT::i32) {
3869 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3870 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3871 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3874 // FIXME memcpy is used way more than necessary. Correctness first.
3875 // Note: "by value" is code for passing a structure by value, not
3877 if (Flags.isByVal()) {
3878 // Note: Size includes alignment padding, so
3879 // struct x { short a; char b; }
3880 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3881 // These are the proper values we need for right-justifying the
3882 // aggregate in a parameter register.
3883 unsigned Size = Flags.getByValSize();
3885 // An empty aggregate parameter takes up no storage and no
3890 // All aggregates smaller than 8 bytes must be passed right-justified.
3891 if (Size==1 || Size==2 || Size==4) {
3892 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3893 if (GPR_idx != NumGPRs) {
3894 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3895 MachinePointerInfo(), VT,
3897 MemOpChains.push_back(Load.getValue(1));
3898 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3900 ArgOffset += PtrByteSize;
3905 if (GPR_idx == NumGPRs && Size < 8) {
3906 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3907 PtrOff.getValueType());
3908 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3909 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3912 ArgOffset += PtrByteSize;
3915 // Copy entire object into memory. There are cases where gcc-generated
3916 // code assumes it is there, even if it could be put entirely into
3917 // registers. (This is not what the doc says.)
3919 // FIXME: The above statement is likely due to a misunderstanding of the
3920 // documents. All arguments must be copied into the parameter area BY
3921 // THE CALLEE in the event that the callee takes the address of any
3922 // formal argument. That has not yet been implemented. However, it is
3923 // reasonable to use the stack area as a staging area for the register
3926 // Skip this for small aggregates, as we will use the same slot for a
3927 // right-justified copy, below.
3929 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3933 // When a register is available, pass a small aggregate right-justified.
3934 if (Size < 8 && GPR_idx != NumGPRs) {
3935 // The easiest way to get this right-justified in a register
3936 // is to copy the structure into the rightmost portion of a
3937 // local variable slot, then load the whole slot into the
3939 // FIXME: The memcpy seems to produce pretty awful code for
3940 // small aggregates, particularly for packed ones.
3941 // FIXME: It would be preferable to use the slot in the
3942 // parameter save area instead of a new local variable.
3943 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3944 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3945 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3949 // Load the slot into the register.
3950 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3951 MachinePointerInfo(),
3952 false, false, false, 0);
3953 MemOpChains.push_back(Load.getValue(1));
3954 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3956 // Done with this argument.
3957 ArgOffset += PtrByteSize;
3961 // For aggregates larger than PtrByteSize, copy the pieces of the
3962 // object that fit into registers from the parameter save area.
3963 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3964 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3965 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3966 if (GPR_idx != NumGPRs) {
3967 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3968 MachinePointerInfo(),
3969 false, false, false, 0);
3970 MemOpChains.push_back(Load.getValue(1));
3971 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3972 ArgOffset += PtrByteSize;
3974 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3981 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3982 default: llvm_unreachable("Unexpected ValueType for argument!");
3985 if (GPR_idx != NumGPRs) {
3986 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3988 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3989 true, isTailCall, false, MemOpChains,
3990 TailCallArguments, dl);
3992 ArgOffset += PtrByteSize;
3996 if (FPR_idx != NumFPRs) {
3997 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4000 // A single float or an aggregate containing only a single float
4001 // must be passed right-justified in the stack doubleword, and
4002 // in the GPR, if one is available.
4004 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
4005 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4006 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4010 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4011 MachinePointerInfo(), false, false, 0);
4012 MemOpChains.push_back(Store);
4014 // Float varargs are always shadowed in available integer registers
4015 if (GPR_idx != NumGPRs) {
4016 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4017 MachinePointerInfo(), false, false,
4019 MemOpChains.push_back(Load.getValue(1));
4020 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4022 } else if (GPR_idx != NumGPRs)
4023 // If we have any FPRs remaining, we may also have GPRs remaining.
4026 // Single-precision floating-point values are mapped to the
4027 // second (rightmost) word of the stack doubleword.
4028 if (Arg.getValueType() == MVT::f32) {
4029 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4030 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4033 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4034 true, isTailCall, false, MemOpChains,
4035 TailCallArguments, dl);
4044 // These go aligned on the stack, or in the corresponding R registers
4045 // when within range. The Darwin PPC ABI doc claims they also go in
4046 // V registers; in fact gcc does this only for arguments that are
4047 // prototyped, not for those that match the ... We do it for all
4048 // arguments, seems to work.
4049 while (ArgOffset % 16 !=0) {
4050 ArgOffset += PtrByteSize;
4051 if (GPR_idx != NumGPRs)
4054 // We could elide this store in the case where the object fits
4055 // entirely in R registers. Maybe later.
4056 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4057 DAG.getConstant(ArgOffset, PtrVT));
4058 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4059 MachinePointerInfo(), false, false, 0);
4060 MemOpChains.push_back(Store);
4061 if (VR_idx != NumVRs) {
4062 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4063 MachinePointerInfo(),
4064 false, false, false, 0);
4065 MemOpChains.push_back(Load.getValue(1));
4066 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4069 for (unsigned i=0; i<16; i+=PtrByteSize) {
4070 if (GPR_idx == NumGPRs)
4072 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4073 DAG.getConstant(i, PtrVT));
4074 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4075 false, false, false, 0);
4076 MemOpChains.push_back(Load.getValue(1));
4077 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4082 // Non-varargs Altivec params generally go in registers, but have
4083 // stack space allocated at the end.
4084 if (VR_idx != NumVRs) {
4085 // Doesn't have GPR space allocated.
4086 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4088 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4089 true, isTailCall, true, MemOpChains,
4090 TailCallArguments, dl);
4097 if (!MemOpChains.empty())
4098 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4099 &MemOpChains[0], MemOpChains.size());
4101 // Check if this is an indirect call (MTCTR/BCTRL).
4102 // See PrepareCall() for more information about calls through function
4103 // pointers in the 64-bit SVR4 ABI.
4105 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4106 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4107 !isBLACompatibleAddress(Callee, DAG)) {
4108 // Load r2 into a virtual register and store it to the TOC save area.
4109 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4110 // TOC save area offset.
4111 SDValue PtrOff = DAG.getIntPtrConstant(40);
4112 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4113 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4115 // R12 must contain the address of an indirect callee. This does not
4116 // mean the MTCTR instruction must use R12; it's easier to model this
4117 // as an extra parameter, so do that.
4118 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4121 // Build a sequence of copy-to-reg nodes chained together with token chain
4122 // and flag operands which copy the outgoing args into the appropriate regs.
4124 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4125 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4126 RegsToPass[i].second, InFlag);
4127 InFlag = Chain.getValue(1);
4131 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4132 FPOp, true, TailCallArguments);
4134 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4135 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4140 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4141 CallingConv::ID CallConv, bool isVarArg,
4143 const SmallVectorImpl<ISD::OutputArg> &Outs,
4144 const SmallVectorImpl<SDValue> &OutVals,
4145 const SmallVectorImpl<ISD::InputArg> &Ins,
4146 DebugLoc dl, SelectionDAG &DAG,
4147 SmallVectorImpl<SDValue> &InVals) const {
4149 unsigned NumOps = Outs.size();
4151 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4152 bool isPPC64 = PtrVT == MVT::i64;
4153 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4155 MachineFunction &MF = DAG.getMachineFunction();
4157 // Mark this function as potentially containing a function that contains a
4158 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4159 // and restoring the callers stack pointer in this functions epilog. This is
4160 // done because by tail calling the called function might overwrite the value
4161 // in this function's (MF) stack pointer stack slot 0(SP).
4162 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4163 CallConv == CallingConv::Fast)
4164 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4166 unsigned nAltivecParamsAtEnd = 0;
4168 // Count how many bytes are to be pushed on the stack, including the linkage
4169 // area, and parameter passing area. We start with 24/48 bytes, which is
4170 // prereserved space for [SP][CR][LR][3 x unused].
4172 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4174 nAltivecParamsAtEnd);
4176 // Calculate by how many bytes the stack has to be adjusted in case of tail
4177 // call optimization.
4178 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4180 // To protect arguments on the stack from being clobbered in a tail call,
4181 // force all the loads to happen before doing any other lowering.
4183 Chain = DAG.getStackArgumentTokenFactor(Chain);
4185 // Adjust the stack pointer for the new arguments...
4186 // These operations are automatically eliminated by the prolog/epilog pass
4187 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
4188 SDValue CallSeqStart = Chain;
4190 // Load the return address and frame pointer so it can be move somewhere else
4193 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4196 // Set up a copy of the stack pointer for use loading and storing any
4197 // arguments that may not fit in the registers available for argument
4201 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4203 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4205 // Figure out which arguments are going to go in registers, and which in
4206 // memory. Also, if this is a vararg function, floating point operations
4207 // must be stored to our stack, and loaded into integer regs as well, if
4208 // any integer regs are available for argument passing.
4209 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4210 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4212 static const uint16_t GPR_32[] = { // 32-bit registers.
4213 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4214 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4216 static const uint16_t GPR_64[] = { // 64-bit registers.
4217 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4218 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4220 static const uint16_t *FPR = GetFPR();
4222 static const uint16_t VR[] = {
4223 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4224 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4226 const unsigned NumGPRs = array_lengthof(GPR_32);
4227 const unsigned NumFPRs = 13;
4228 const unsigned NumVRs = array_lengthof(VR);
4230 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4232 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4233 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4235 SmallVector<SDValue, 8> MemOpChains;
4236 for (unsigned i = 0; i != NumOps; ++i) {
4237 SDValue Arg = OutVals[i];
4238 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4240 // PtrOff will be used to store the current argument to the stack if a
4241 // register cannot be found for it.
4244 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4246 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4248 // On PPC64, promote integers to 64-bit values.
4249 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4250 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4251 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4252 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4255 // FIXME memcpy is used way more than necessary. Correctness first.
4256 // Note: "by value" is code for passing a structure by value, not
4258 if (Flags.isByVal()) {
4259 unsigned Size = Flags.getByValSize();
4260 // Very small objects are passed right-justified. Everything else is
4261 // passed left-justified.
4262 if (Size==1 || Size==2) {
4263 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4264 if (GPR_idx != NumGPRs) {
4265 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4266 MachinePointerInfo(), VT,
4268 MemOpChains.push_back(Load.getValue(1));
4269 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4271 ArgOffset += PtrByteSize;
4273 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4274 PtrOff.getValueType());
4275 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4276 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4279 ArgOffset += PtrByteSize;
4283 // Copy entire object into memory. There are cases where gcc-generated
4284 // code assumes it is there, even if it could be put entirely into
4285 // registers. (This is not what the doc says.)
4286 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4290 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4291 // copy the pieces of the object that fit into registers from the
4292 // parameter save area.
4293 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4294 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4295 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4296 if (GPR_idx != NumGPRs) {
4297 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4298 MachinePointerInfo(),
4299 false, false, false, 0);
4300 MemOpChains.push_back(Load.getValue(1));
4301 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4302 ArgOffset += PtrByteSize;
4304 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4311 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4312 default: llvm_unreachable("Unexpected ValueType for argument!");
4315 if (GPR_idx != NumGPRs) {
4316 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4318 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4319 isPPC64, isTailCall, false, MemOpChains,
4320 TailCallArguments, dl);
4322 ArgOffset += PtrByteSize;
4326 if (FPR_idx != NumFPRs) {
4327 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4330 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4331 MachinePointerInfo(), false, false, 0);
4332 MemOpChains.push_back(Store);
4334 // Float varargs are always shadowed in available integer registers
4335 if (GPR_idx != NumGPRs) {
4336 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4337 MachinePointerInfo(), false, false,
4339 MemOpChains.push_back(Load.getValue(1));
4340 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4342 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4343 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4344 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4345 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4346 MachinePointerInfo(),
4347 false, false, false, 0);
4348 MemOpChains.push_back(Load.getValue(1));
4349 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4352 // If we have any FPRs remaining, we may also have GPRs remaining.
4353 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4355 if (GPR_idx != NumGPRs)
4357 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4358 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4362 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4363 isPPC64, isTailCall, false, MemOpChains,
4364 TailCallArguments, dl);
4368 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4375 // These go aligned on the stack, or in the corresponding R registers
4376 // when within range. The Darwin PPC ABI doc claims they also go in
4377 // V registers; in fact gcc does this only for arguments that are
4378 // prototyped, not for those that match the ... We do it for all
4379 // arguments, seems to work.
4380 while (ArgOffset % 16 !=0) {
4381 ArgOffset += PtrByteSize;
4382 if (GPR_idx != NumGPRs)
4385 // We could elide this store in the case where the object fits
4386 // entirely in R registers. Maybe later.
4387 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4388 DAG.getConstant(ArgOffset, PtrVT));
4389 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4390 MachinePointerInfo(), false, false, 0);
4391 MemOpChains.push_back(Store);
4392 if (VR_idx != NumVRs) {
4393 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4394 MachinePointerInfo(),
4395 false, false, false, 0);
4396 MemOpChains.push_back(Load.getValue(1));
4397 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4400 for (unsigned i=0; i<16; i+=PtrByteSize) {
4401 if (GPR_idx == NumGPRs)
4403 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4404 DAG.getConstant(i, PtrVT));
4405 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4406 false, false, false, 0);
4407 MemOpChains.push_back(Load.getValue(1));
4408 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4413 // Non-varargs Altivec params generally go in registers, but have
4414 // stack space allocated at the end.
4415 if (VR_idx != NumVRs) {
4416 // Doesn't have GPR space allocated.
4417 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4418 } else if (nAltivecParamsAtEnd==0) {
4419 // We are emitting Altivec params in order.
4420 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4421 isPPC64, isTailCall, true, MemOpChains,
4422 TailCallArguments, dl);
4428 // If all Altivec parameters fit in registers, as they usually do,
4429 // they get stack space following the non-Altivec parameters. We
4430 // don't track this here because nobody below needs it.
4431 // If there are more Altivec parameters than fit in registers emit
4433 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4435 // Offset is aligned; skip 1st 12 params which go in V registers.
4436 ArgOffset = ((ArgOffset+15)/16)*16;
4438 for (unsigned i = 0; i != NumOps; ++i) {
4439 SDValue Arg = OutVals[i];
4440 EVT ArgType = Outs[i].VT;
4441 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4442 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4445 // We are emitting Altivec params in order.
4446 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4447 isPPC64, isTailCall, true, MemOpChains,
4448 TailCallArguments, dl);
4455 if (!MemOpChains.empty())
4456 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4457 &MemOpChains[0], MemOpChains.size());
4459 // On Darwin, R12 must contain the address of an indirect callee. This does
4460 // not mean the MTCTR instruction must use R12; it's easier to model this as
4461 // an extra parameter, so do that.
4463 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4464 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4465 !isBLACompatibleAddress(Callee, DAG))
4466 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4467 PPC::R12), Callee));
4469 // Build a sequence of copy-to-reg nodes chained together with token chain
4470 // and flag operands which copy the outgoing args into the appropriate regs.
4472 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4473 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4474 RegsToPass[i].second, InFlag);
4475 InFlag = Chain.getValue(1);
4479 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4480 FPOp, true, TailCallArguments);
4482 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4483 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4488 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4489 MachineFunction &MF, bool isVarArg,
4490 const SmallVectorImpl<ISD::OutputArg> &Outs,
4491 LLVMContext &Context) const {
4492 SmallVector<CCValAssign, 16> RVLocs;
4493 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4495 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4499 PPCTargetLowering::LowerReturn(SDValue Chain,
4500 CallingConv::ID CallConv, bool isVarArg,
4501 const SmallVectorImpl<ISD::OutputArg> &Outs,
4502 const SmallVectorImpl<SDValue> &OutVals,
4503 DebugLoc dl, SelectionDAG &DAG) const {
4505 SmallVector<CCValAssign, 16> RVLocs;
4506 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4507 getTargetMachine(), RVLocs, *DAG.getContext());
4508 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4511 SmallVector<SDValue, 4> RetOps(1, Chain);
4513 // Copy the result values into the output registers.
4514 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4515 CCValAssign &VA = RVLocs[i];
4516 assert(VA.isRegLoc() && "Can only return in registers!");
4518 SDValue Arg = OutVals[i];
4520 switch (VA.getLocInfo()) {
4521 default: llvm_unreachable("Unknown loc info!");
4522 case CCValAssign::Full: break;
4523 case CCValAssign::AExt:
4524 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4526 case CCValAssign::ZExt:
4527 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4529 case CCValAssign::SExt:
4530 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4534 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4535 Flag = Chain.getValue(1);
4536 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4539 RetOps[0] = Chain; // Update chain.
4541 // Add the flag if we have it.
4543 RetOps.push_back(Flag);
4545 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4546 &RetOps[0], RetOps.size());
4549 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4550 const PPCSubtarget &Subtarget) const {
4551 // When we pop the dynamic allocation we need to restore the SP link.
4552 DebugLoc dl = Op.getDebugLoc();
4554 // Get the corect type for pointers.
4555 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4557 // Construct the stack pointer operand.
4558 bool isPPC64 = Subtarget.isPPC64();
4559 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4560 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4562 // Get the operands for the STACKRESTORE.
4563 SDValue Chain = Op.getOperand(0);
4564 SDValue SaveSP = Op.getOperand(1);
4566 // Load the old link SP.
4567 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4568 MachinePointerInfo(),
4569 false, false, false, 0);
4571 // Restore the stack pointer.
4572 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4574 // Store the old link SP.
4575 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4582 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4583 MachineFunction &MF = DAG.getMachineFunction();
4584 bool isPPC64 = PPCSubTarget.isPPC64();
4585 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4586 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4588 // Get current frame pointer save index. The users of this index will be
4589 // primarily DYNALLOC instructions.
4590 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4591 int RASI = FI->getReturnAddrSaveIndex();
4593 // If the frame pointer save index hasn't been defined yet.
4595 // Find out what the fix offset of the frame pointer save area.
4596 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4597 // Allocate the frame index for frame pointer save area.
4598 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4600 FI->setReturnAddrSaveIndex(RASI);
4602 return DAG.getFrameIndex(RASI, PtrVT);
4606 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4607 MachineFunction &MF = DAG.getMachineFunction();
4608 bool isPPC64 = PPCSubTarget.isPPC64();
4609 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4610 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4612 // Get current frame pointer save index. The users of this index will be
4613 // primarily DYNALLOC instructions.
4614 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4615 int FPSI = FI->getFramePointerSaveIndex();
4617 // If the frame pointer save index hasn't been defined yet.
4619 // Find out what the fix offset of the frame pointer save area.
4620 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4623 // Allocate the frame index for frame pointer save area.
4624 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4626 FI->setFramePointerSaveIndex(FPSI);
4628 return DAG.getFrameIndex(FPSI, PtrVT);
4631 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4633 const PPCSubtarget &Subtarget) const {
4635 SDValue Chain = Op.getOperand(0);
4636 SDValue Size = Op.getOperand(1);
4637 DebugLoc dl = Op.getDebugLoc();
4639 // Get the corect type for pointers.
4640 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4642 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4643 DAG.getConstant(0, PtrVT), Size);
4644 // Construct a node for the frame pointer save index.
4645 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4646 // Build a DYNALLOC node.
4647 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4648 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4649 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4652 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4653 SelectionDAG &DAG) const {
4654 DebugLoc DL = Op.getDebugLoc();
4655 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4656 DAG.getVTList(MVT::i32, MVT::Other),
4657 Op.getOperand(0), Op.getOperand(1));
4660 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4661 SelectionDAG &DAG) const {
4662 DebugLoc DL = Op.getDebugLoc();
4663 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4664 Op.getOperand(0), Op.getOperand(1));
4667 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4669 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4670 // Not FP? Not a fsel.
4671 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4672 !Op.getOperand(2).getValueType().isFloatingPoint())
4675 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4677 // Cannot handle SETEQ/SETNE.
4678 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
4680 EVT ResVT = Op.getValueType();
4681 EVT CmpVT = Op.getOperand(0).getValueType();
4682 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4683 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4684 DebugLoc dl = Op.getDebugLoc();
4686 // If the RHS of the comparison is a 0.0, we don't need to do the
4687 // subtraction at all.
4688 if (isFloatingPointZero(RHS))
4690 default: break; // SETUO etc aren't handled by fsel.
4693 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4696 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4697 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4698 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4701 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4704 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4705 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4706 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4707 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4712 default: break; // SETUO etc aren't handled by fsel.
4715 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4716 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4717 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4718 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4721 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4722 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4723 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4724 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4727 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4728 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4729 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4730 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4733 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4734 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4735 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4736 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4741 // FIXME: Split this code up when LegalizeDAGTypes lands.
4742 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4743 DebugLoc dl) const {
4744 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4745 SDValue Src = Op.getOperand(0);
4746 if (Src.getValueType() == MVT::f32)
4747 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4750 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4751 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4753 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4754 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
4759 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
4760 "i64 FP_TO_UINT is supported only with FPCVT");
4761 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
4767 // Convert the FP value to an int value through memory.
4768 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
4769 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
4770 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
4771 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
4772 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
4774 // Emit a store to the stack slot.
4777 MachineFunction &MF = DAG.getMachineFunction();
4778 MachineMemOperand *MMO =
4779 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
4780 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
4781 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
4782 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
4785 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4786 MPI, false, false, 0);
4788 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4790 if (Op.getValueType() == MVT::i32 && !i32Stack) {
4791 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4792 DAG.getConstant(4, FIPtr.getValueType()));
4793 MPI = MachinePointerInfo();
4796 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
4797 false, false, false, 0);
4800 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
4801 SelectionDAG &DAG) const {
4802 DebugLoc dl = Op.getDebugLoc();
4803 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4804 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4807 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
4808 "UINT_TO_FP is supported only with FPCVT");
4810 // If we have FCFIDS, then use it when converting to single-precision.
4811 // Otherwise, convert to double-precision and then round.
4812 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4813 (Op.getOpcode() == ISD::UINT_TO_FP ?
4814 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
4815 (Op.getOpcode() == ISD::UINT_TO_FP ?
4816 PPCISD::FCFIDU : PPCISD::FCFID);
4817 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4818 MVT::f32 : MVT::f64;
4820 if (Op.getOperand(0).getValueType() == MVT::i64) {
4821 SDValue SINT = Op.getOperand(0);
4822 // When converting to single-precision, we actually need to convert
4823 // to double-precision first and then round to single-precision.
4824 // To avoid double-rounding effects during that operation, we have
4825 // to prepare the input operand. Bits that might be truncated when
4826 // converting to double-precision are replaced by a bit that won't
4827 // be lost at this stage, but is below the single-precision rounding
4830 // However, if -enable-unsafe-fp-math is in effect, accept double
4831 // rounding to avoid the extra overhead.
4832 if (Op.getValueType() == MVT::f32 &&
4833 !PPCSubTarget.hasFPCVT() &&
4834 !DAG.getTarget().Options.UnsafeFPMath) {
4836 // Twiddle input to make sure the low 11 bits are zero. (If this
4837 // is the case, we are guaranteed the value will fit into the 53 bit
4838 // mantissa of an IEEE double-precision value without rounding.)
4839 // If any of those low 11 bits were not zero originally, make sure
4840 // bit 12 (value 2048) is set instead, so that the final rounding
4841 // to single-precision gets the correct result.
4842 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4843 SINT, DAG.getConstant(2047, MVT::i64));
4844 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4845 Round, DAG.getConstant(2047, MVT::i64));
4846 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4847 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4848 Round, DAG.getConstant(-2048, MVT::i64));
4850 // However, we cannot use that value unconditionally: if the magnitude
4851 // of the input value is small, the bit-twiddling we did above might
4852 // end up visibly changing the output. Fortunately, in that case, we
4853 // don't need to twiddle bits since the original input will convert
4854 // exactly to double-precision floating-point already. Therefore,
4855 // construct a conditional to use the original value if the top 11
4856 // bits are all sign-bit copies, and use the rounded value computed
4858 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4859 SINT, DAG.getConstant(53, MVT::i32));
4860 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4861 Cond, DAG.getConstant(1, MVT::i64));
4862 Cond = DAG.getSetCC(dl, MVT::i32,
4863 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4865 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4868 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4869 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
4871 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
4872 FP = DAG.getNode(ISD::FP_ROUND, dl,
4873 MVT::f32, FP, DAG.getIntPtrConstant(0));
4877 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4878 "Unhandled INT_TO_FP type in custom expander!");
4879 // Since we only generate this in 64-bit mode, we can take advantage of
4880 // 64-bit registers. In particular, sign extend the input value into the
4881 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4882 // then lfd it and fcfid it.
4883 MachineFunction &MF = DAG.getMachineFunction();
4884 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4885 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4888 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
4889 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
4890 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4892 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
4893 MachinePointerInfo::getFixedStack(FrameIdx),
4896 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
4897 "Expected an i32 store");
4898 MachineMemOperand *MMO =
4899 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4900 MachineMemOperand::MOLoad, 4, 4);
4901 SDValue Ops[] = { Store, FIdx };
4902 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
4903 PPCISD::LFIWZX : PPCISD::LFIWAX,
4904 dl, DAG.getVTList(MVT::f64, MVT::Other),
4905 Ops, 2, MVT::i32, MMO);
4907 assert(PPCSubTarget.isPPC64() &&
4908 "i32->FP without LFIWAX supported only on PPC64");
4910 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4911 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4913 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
4916 // STD the extended value into the stack slot.
4917 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
4918 MachinePointerInfo::getFixedStack(FrameIdx),
4921 // Load the value as a double.
4922 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
4923 MachinePointerInfo::getFixedStack(FrameIdx),
4924 false, false, false, 0);
4927 // FCFID it and return it.
4928 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
4929 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
4930 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4934 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4935 SelectionDAG &DAG) const {
4936 DebugLoc dl = Op.getDebugLoc();
4938 The rounding mode is in bits 30:31 of FPSR, and has the following
4945 FLT_ROUNDS, on the other hand, expects the following:
4952 To perform the conversion, we do:
4953 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4956 MachineFunction &MF = DAG.getMachineFunction();
4957 EVT VT = Op.getValueType();
4958 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4959 SDValue MFFSreg, InFlag;
4961 // Save FP Control Word to register
4963 MVT::f64, // return register
4964 MVT::Glue // unused in this context
4966 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4968 // Save FP register to stack slot
4969 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
4970 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
4971 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
4972 StackSlot, MachinePointerInfo(), false, false,0);
4974 // Load FP Control Word from low 32 bits of stack slot.
4975 SDValue Four = DAG.getConstant(4, PtrVT);
4976 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
4977 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
4978 false, false, false, 0);
4980 // Transform as necessary
4982 DAG.getNode(ISD::AND, dl, MVT::i32,
4983 CWD, DAG.getConstant(3, MVT::i32));
4985 DAG.getNode(ISD::SRL, dl, MVT::i32,
4986 DAG.getNode(ISD::AND, dl, MVT::i32,
4987 DAG.getNode(ISD::XOR, dl, MVT::i32,
4988 CWD, DAG.getConstant(3, MVT::i32)),
4989 DAG.getConstant(3, MVT::i32)),
4990 DAG.getConstant(1, MVT::i32));
4993 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
4995 return DAG.getNode((VT.getSizeInBits() < 16 ?
4996 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
4999 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5000 EVT VT = Op.getValueType();
5001 unsigned BitWidth = VT.getSizeInBits();
5002 DebugLoc dl = Op.getDebugLoc();
5003 assert(Op.getNumOperands() == 3 &&
5004 VT == Op.getOperand(1).getValueType() &&
5007 // Expand into a bunch of logical ops. Note that these ops
5008 // depend on the PPC behavior for oversized shift amounts.
5009 SDValue Lo = Op.getOperand(0);
5010 SDValue Hi = Op.getOperand(1);
5011 SDValue Amt = Op.getOperand(2);
5012 EVT AmtVT = Amt.getValueType();
5014 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5015 DAG.getConstant(BitWidth, AmtVT), Amt);
5016 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5017 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5018 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5019 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5020 DAG.getConstant(-BitWidth, AmtVT));
5021 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5022 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5023 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5024 SDValue OutOps[] = { OutLo, OutHi };
5025 return DAG.getMergeValues(OutOps, 2, dl);
5028 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5029 EVT VT = Op.getValueType();
5030 DebugLoc dl = Op.getDebugLoc();
5031 unsigned BitWidth = VT.getSizeInBits();
5032 assert(Op.getNumOperands() == 3 &&
5033 VT == Op.getOperand(1).getValueType() &&
5036 // Expand into a bunch of logical ops. Note that these ops
5037 // depend on the PPC behavior for oversized shift amounts.
5038 SDValue Lo = Op.getOperand(0);
5039 SDValue Hi = Op.getOperand(1);
5040 SDValue Amt = Op.getOperand(2);
5041 EVT AmtVT = Amt.getValueType();
5043 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5044 DAG.getConstant(BitWidth, AmtVT), Amt);
5045 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5046 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5047 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5048 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5049 DAG.getConstant(-BitWidth, AmtVT));
5050 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5051 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5052 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5053 SDValue OutOps[] = { OutLo, OutHi };
5054 return DAG.getMergeValues(OutOps, 2, dl);
5057 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5058 DebugLoc dl = Op.getDebugLoc();
5059 EVT VT = Op.getValueType();
5060 unsigned BitWidth = VT.getSizeInBits();
5061 assert(Op.getNumOperands() == 3 &&
5062 VT == Op.getOperand(1).getValueType() &&
5065 // Expand into a bunch of logical ops, followed by a select_cc.
5066 SDValue Lo = Op.getOperand(0);
5067 SDValue Hi = Op.getOperand(1);
5068 SDValue Amt = Op.getOperand(2);
5069 EVT AmtVT = Amt.getValueType();
5071 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5072 DAG.getConstant(BitWidth, AmtVT), Amt);
5073 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5074 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5075 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5076 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5077 DAG.getConstant(-BitWidth, AmtVT));
5078 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5079 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5080 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5081 Tmp4, Tmp6, ISD::SETLE);
5082 SDValue OutOps[] = { OutLo, OutHi };
5083 return DAG.getMergeValues(OutOps, 2, dl);
5086 //===----------------------------------------------------------------------===//
5087 // Vector related lowering.
5090 /// BuildSplatI - Build a canonical splati of Val with an element size of
5091 /// SplatSize. Cast the result to VT.
5092 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5093 SelectionDAG &DAG, DebugLoc dl) {
5094 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5096 static const EVT VTys[] = { // canonical VT to use for each size.
5097 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5100 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5102 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5106 EVT CanonicalVT = VTys[SplatSize-1];
5108 // Build a canonical splat for this value.
5109 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5110 SmallVector<SDValue, 8> Ops;
5111 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5112 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5113 &Ops[0], Ops.size());
5114 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5117 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5118 /// specified intrinsic ID.
5119 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5120 SelectionDAG &DAG, DebugLoc dl,
5121 EVT DestVT = MVT::Other) {
5122 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5123 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5124 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5127 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5128 /// specified intrinsic ID.
5129 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5130 SDValue Op2, SelectionDAG &DAG,
5131 DebugLoc dl, EVT DestVT = MVT::Other) {
5132 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5133 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5134 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5138 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5139 /// amount. The result has the specified value type.
5140 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5141 EVT VT, SelectionDAG &DAG, DebugLoc dl) {
5142 // Force LHS/RHS to be the right type.
5143 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5144 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5147 for (unsigned i = 0; i != 16; ++i)
5149 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5150 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5153 // If this is a case we can't handle, return null and let the default
5154 // expansion code take care of it. If we CAN select this case, and if it
5155 // selects to a single instruction, return Op. Otherwise, if we can codegen
5156 // this case more efficiently than a constant pool load, lower it to the
5157 // sequence of ops that should be used.
5158 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5159 SelectionDAG &DAG) const {
5160 DebugLoc dl = Op.getDebugLoc();
5161 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5162 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5164 // Check if this is a splat of a constant value.
5165 APInt APSplatBits, APSplatUndef;
5166 unsigned SplatBitSize;
5168 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5169 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5172 unsigned SplatBits = APSplatBits.getZExtValue();
5173 unsigned SplatUndef = APSplatUndef.getZExtValue();
5174 unsigned SplatSize = SplatBitSize / 8;
5176 // First, handle single instruction cases.
5179 if (SplatBits == 0) {
5180 // Canonicalize all zero vectors to be v4i32.
5181 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5182 SDValue Z = DAG.getConstant(0, MVT::i32);
5183 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5184 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5189 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5190 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5192 if (SextVal >= -16 && SextVal <= 15)
5193 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5196 // Two instruction sequences.
5198 // If this value is in the range [-32,30] and is even, use:
5199 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5200 // If this value is in the range [17,31] and is odd, use:
5201 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5202 // If this value is in the range [-31,-17] and is odd, use:
5203 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5204 // Note the last two are three-instruction sequences.
5205 if (SextVal >= -32 && SextVal <= 31) {
5206 // To avoid having these optimizations undone by constant folding,
5207 // we convert to a pseudo that will be expanded later into one of
5209 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5210 EVT VT = Op.getValueType();
5211 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5212 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5213 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5216 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5217 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5219 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5220 // Make -1 and vspltisw -1:
5221 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5223 // Make the VSLW intrinsic, computing 0x8000_0000.
5224 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5227 // xor by OnesV to invert it.
5228 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5229 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5232 // Check to see if this is a wide variety of vsplti*, binop self cases.
5233 static const signed char SplatCsts[] = {
5234 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5235 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5238 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5239 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5240 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5241 int i = SplatCsts[idx];
5243 // Figure out what shift amount will be used by altivec if shifted by i in
5245 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5247 // vsplti + shl self.
5248 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5249 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5250 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5251 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5252 Intrinsic::ppc_altivec_vslw
5254 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5255 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5258 // vsplti + srl self.
5259 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5260 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5261 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5262 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5263 Intrinsic::ppc_altivec_vsrw
5265 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5266 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5269 // vsplti + sra self.
5270 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5271 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5272 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5273 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5274 Intrinsic::ppc_altivec_vsraw
5276 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5277 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5280 // vsplti + rol self.
5281 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5282 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5283 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5284 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5285 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5286 Intrinsic::ppc_altivec_vrlw
5288 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5289 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5292 // t = vsplti c, result = vsldoi t, t, 1
5293 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5294 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5295 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5297 // t = vsplti c, result = vsldoi t, t, 2
5298 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5299 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5300 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5302 // t = vsplti c, result = vsldoi t, t, 3
5303 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5304 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5305 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5312 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5313 /// the specified operations to build the shuffle.
5314 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5315 SDValue RHS, SelectionDAG &DAG,
5317 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5318 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5319 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5322 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5334 if (OpNum == OP_COPY) {
5335 if (LHSID == (1*9+2)*9+3) return LHS;
5336 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5340 SDValue OpLHS, OpRHS;
5341 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5342 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5346 default: llvm_unreachable("Unknown i32 permute!");
5348 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5349 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5350 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5351 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5354 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5355 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5356 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5357 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5360 for (unsigned i = 0; i != 16; ++i)
5361 ShufIdxs[i] = (i&3)+0;
5364 for (unsigned i = 0; i != 16; ++i)
5365 ShufIdxs[i] = (i&3)+4;
5368 for (unsigned i = 0; i != 16; ++i)
5369 ShufIdxs[i] = (i&3)+8;
5372 for (unsigned i = 0; i != 16; ++i)
5373 ShufIdxs[i] = (i&3)+12;
5376 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5378 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5380 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5382 EVT VT = OpLHS.getValueType();
5383 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5384 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5385 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5386 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5389 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5390 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5391 /// return the code it can be lowered into. Worst case, it can always be
5392 /// lowered into a vperm.
5393 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5394 SelectionDAG &DAG) const {
5395 DebugLoc dl = Op.getDebugLoc();
5396 SDValue V1 = Op.getOperand(0);
5397 SDValue V2 = Op.getOperand(1);
5398 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5399 EVT VT = Op.getValueType();
5401 // Cases that are handled by instructions that take permute immediates
5402 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5403 // selected by the instruction selector.
5404 if (V2.getOpcode() == ISD::UNDEF) {
5405 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5406 PPC::isSplatShuffleMask(SVOp, 2) ||
5407 PPC::isSplatShuffleMask(SVOp, 4) ||
5408 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5409 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5410 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5411 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5412 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5413 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5414 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5415 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5416 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5421 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5422 // and produce a fixed permutation. If any of these match, do not lower to
5424 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5425 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5426 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5427 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5428 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5429 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5430 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5431 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5432 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5435 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5436 // perfect shuffle table to emit an optimal matching sequence.
5437 ArrayRef<int> PermMask = SVOp->getMask();
5439 unsigned PFIndexes[4];
5440 bool isFourElementShuffle = true;
5441 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5442 unsigned EltNo = 8; // Start out undef.
5443 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5444 if (PermMask[i*4+j] < 0)
5445 continue; // Undef, ignore it.
5447 unsigned ByteSource = PermMask[i*4+j];
5448 if ((ByteSource & 3) != j) {
5449 isFourElementShuffle = false;
5454 EltNo = ByteSource/4;
5455 } else if (EltNo != ByteSource/4) {
5456 isFourElementShuffle = false;
5460 PFIndexes[i] = EltNo;
5463 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5464 // perfect shuffle vector to determine if it is cost effective to do this as
5465 // discrete instructions, or whether we should use a vperm.
5466 if (isFourElementShuffle) {
5467 // Compute the index in the perfect shuffle table.
5468 unsigned PFTableIndex =
5469 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5471 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5472 unsigned Cost = (PFEntry >> 30);
5474 // Determining when to avoid vperm is tricky. Many things affect the cost
5475 // of vperm, particularly how many times the perm mask needs to be computed.
5476 // For example, if the perm mask can be hoisted out of a loop or is already
5477 // used (perhaps because there are multiple permutes with the same shuffle
5478 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5479 // the loop requires an extra register.
5481 // As a compromise, we only emit discrete instructions if the shuffle can be
5482 // generated in 3 or fewer operations. When we have loop information
5483 // available, if this block is within a loop, we should avoid using vperm
5484 // for 3-operation perms and use a constant pool load instead.
5486 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5489 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5490 // vector that will get spilled to the constant pool.
5491 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5493 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5494 // that it is in input element units, not in bytes. Convert now.
5495 EVT EltVT = V1.getValueType().getVectorElementType();
5496 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5498 SmallVector<SDValue, 16> ResultMask;
5499 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5500 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5502 for (unsigned j = 0; j != BytesPerElement; ++j)
5503 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5507 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5508 &ResultMask[0], ResultMask.size());
5509 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5512 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5513 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5514 /// information about the intrinsic.
5515 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5517 unsigned IntrinsicID =
5518 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5521 switch (IntrinsicID) {
5522 default: return false;
5523 // Comparison predicates.
5524 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5525 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5526 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5527 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5528 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5529 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5530 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5531 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5532 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5533 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5534 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5535 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5536 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5538 // Normal Comparisons.
5539 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5540 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5541 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5542 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5543 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5544 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5545 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5546 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5547 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5548 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5549 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5550 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5551 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5556 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5557 /// lower, do it, otherwise return null.
5558 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5559 SelectionDAG &DAG) const {
5560 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5561 // opcode number of the comparison.
5562 DebugLoc dl = Op.getDebugLoc();
5565 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5566 return SDValue(); // Don't custom lower most intrinsics.
5568 // If this is a non-dot comparison, make the VCMP node and we are done.
5570 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5571 Op.getOperand(1), Op.getOperand(2),
5572 DAG.getConstant(CompareOpc, MVT::i32));
5573 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5576 // Create the PPCISD altivec 'dot' comparison node.
5578 Op.getOperand(2), // LHS
5579 Op.getOperand(3), // RHS
5580 DAG.getConstant(CompareOpc, MVT::i32)
5582 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5583 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5585 // Now that we have the comparison, emit a copy from the CR to a GPR.
5586 // This is flagged to the above dot comparison.
5587 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
5588 DAG.getRegister(PPC::CR6, MVT::i32),
5589 CompNode.getValue(1));
5591 // Unpack the result based on how the target uses it.
5592 unsigned BitNo; // Bit # of CR6.
5593 bool InvertBit; // Invert result?
5594 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5595 default: // Can't happen, don't crash on invalid number though.
5596 case 0: // Return the value of the EQ bit of CR6.
5597 BitNo = 0; InvertBit = false;
5599 case 1: // Return the inverted value of the EQ bit of CR6.
5600 BitNo = 0; InvertBit = true;
5602 case 2: // Return the value of the LT bit of CR6.
5603 BitNo = 2; InvertBit = false;
5605 case 3: // Return the inverted value of the LT bit of CR6.
5606 BitNo = 2; InvertBit = true;
5610 // Shift the bit into the low position.
5611 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5612 DAG.getConstant(8-(3-BitNo), MVT::i32));
5614 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5615 DAG.getConstant(1, MVT::i32));
5617 // If we are supposed to, toggle the bit.
5619 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5620 DAG.getConstant(1, MVT::i32));
5624 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5625 SelectionDAG &DAG) const {
5626 DebugLoc dl = Op.getDebugLoc();
5627 // Create a stack slot that is 16-byte aligned.
5628 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5629 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5630 EVT PtrVT = getPointerTy();
5631 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5633 // Store the input value into Value#0 of the stack slot.
5634 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5635 Op.getOperand(0), FIdx, MachinePointerInfo(),
5638 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5639 false, false, false, 0);
5642 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5643 DebugLoc dl = Op.getDebugLoc();
5644 if (Op.getValueType() == MVT::v4i32) {
5645 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5647 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5648 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5650 SDValue RHSSwap = // = vrlw RHS, 16
5651 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5653 // Shrinkify inputs to v8i16.
5654 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5655 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5656 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5658 // Low parts multiplied together, generating 32-bit results (we ignore the
5660 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5661 LHS, RHS, DAG, dl, MVT::v4i32);
5663 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5664 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5665 // Shift the high parts up 16 bits.
5666 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5668 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5669 } else if (Op.getValueType() == MVT::v8i16) {
5670 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5672 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5674 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5675 LHS, RHS, Zero, DAG, dl);
5676 } else if (Op.getValueType() == MVT::v16i8) {
5677 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5679 // Multiply the even 8-bit parts, producing 16-bit sums.
5680 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5681 LHS, RHS, DAG, dl, MVT::v8i16);
5682 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5684 // Multiply the odd 8-bit parts, producing 16-bit sums.
5685 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5686 LHS, RHS, DAG, dl, MVT::v8i16);
5687 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5689 // Merge the results together.
5691 for (unsigned i = 0; i != 8; ++i) {
5693 Ops[i*2+1] = 2*i+1+16;
5695 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5697 llvm_unreachable("Unknown mul to lower!");
5701 /// LowerOperation - Provide custom lowering hooks for some operations.
5703 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5704 switch (Op.getOpcode()) {
5705 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5706 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5707 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5708 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5709 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5710 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5711 case ISD::SETCC: return LowerSETCC(Op, DAG);
5712 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5713 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5715 return LowerVASTART(Op, DAG, PPCSubTarget);
5718 return LowerVAARG(Op, DAG, PPCSubTarget);
5720 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5721 case ISD::DYNAMIC_STACKALLOC:
5722 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5724 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5725 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5727 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5728 case ISD::FP_TO_UINT:
5729 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5731 case ISD::UINT_TO_FP:
5732 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5733 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5735 // Lower 64-bit shifts.
5736 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5737 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5738 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5740 // Vector-related lowering.
5741 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5742 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5743 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5744 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5745 case ISD::MUL: return LowerMUL(Op, DAG);
5747 // Frame & Return address.
5748 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5749 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5753 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5754 SmallVectorImpl<SDValue>&Results,
5755 SelectionDAG &DAG) const {
5756 const TargetMachine &TM = getTargetMachine();
5757 DebugLoc dl = N->getDebugLoc();
5758 switch (N->getOpcode()) {
5760 llvm_unreachable("Do not know how to custom type legalize this operation!");
5762 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5763 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5766 EVT VT = N->getValueType(0);
5768 if (VT == MVT::i64) {
5769 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5771 Results.push_back(NewNode);
5772 Results.push_back(NewNode.getValue(1));
5776 case ISD::FP_ROUND_INREG: {
5777 assert(N->getValueType(0) == MVT::ppcf128);
5778 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5779 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5780 MVT::f64, N->getOperand(0),
5781 DAG.getIntPtrConstant(0));
5782 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5783 MVT::f64, N->getOperand(0),
5784 DAG.getIntPtrConstant(1));
5786 // Add the two halves of the long double in round-to-zero mode.
5787 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
5789 // We know the low half is about to be thrown away, so just use something
5791 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5795 case ISD::FP_TO_SINT:
5796 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5802 //===----------------------------------------------------------------------===//
5803 // Other Lowering Code
5804 //===----------------------------------------------------------------------===//
5807 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5808 bool is64bit, unsigned BinOpcode) const {
5809 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5810 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5812 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5813 MachineFunction *F = BB->getParent();
5814 MachineFunction::iterator It = BB;
5817 unsigned dest = MI->getOperand(0).getReg();
5818 unsigned ptrA = MI->getOperand(1).getReg();
5819 unsigned ptrB = MI->getOperand(2).getReg();
5820 unsigned incr = MI->getOperand(3).getReg();
5821 DebugLoc dl = MI->getDebugLoc();
5823 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5824 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5825 F->insert(It, loopMBB);
5826 F->insert(It, exitMBB);
5827 exitMBB->splice(exitMBB->begin(), BB,
5828 llvm::next(MachineBasicBlock::iterator(MI)),
5830 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5832 MachineRegisterInfo &RegInfo = F->getRegInfo();
5833 unsigned TmpReg = (!BinOpcode) ? incr :
5834 RegInfo.createVirtualRegister(
5835 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5836 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5840 // fallthrough --> loopMBB
5841 BB->addSuccessor(loopMBB);
5844 // l[wd]arx dest, ptr
5845 // add r0, dest, incr
5846 // st[wd]cx. r0, ptr
5848 // fallthrough --> exitMBB
5850 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5851 .addReg(ptrA).addReg(ptrB);
5853 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5854 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5855 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5856 BuildMI(BB, dl, TII->get(PPC::BCC))
5857 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5858 BB->addSuccessor(loopMBB);
5859 BB->addSuccessor(exitMBB);
5868 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5869 MachineBasicBlock *BB,
5870 bool is8bit, // operation
5871 unsigned BinOpcode) const {
5872 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5873 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5874 // In 64 bit mode we have to use 64 bits for addresses, even though the
5875 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5876 // registers without caring whether they're 32 or 64, but here we're
5877 // doing actual arithmetic on the addresses.
5878 bool is64bit = PPCSubTarget.isPPC64();
5879 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
5881 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5882 MachineFunction *F = BB->getParent();
5883 MachineFunction::iterator It = BB;
5886 unsigned dest = MI->getOperand(0).getReg();
5887 unsigned ptrA = MI->getOperand(1).getReg();
5888 unsigned ptrB = MI->getOperand(2).getReg();
5889 unsigned incr = MI->getOperand(3).getReg();
5890 DebugLoc dl = MI->getDebugLoc();
5892 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5893 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5894 F->insert(It, loopMBB);
5895 F->insert(It, exitMBB);
5896 exitMBB->splice(exitMBB->begin(), BB,
5897 llvm::next(MachineBasicBlock::iterator(MI)),
5899 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5901 MachineRegisterInfo &RegInfo = F->getRegInfo();
5902 const TargetRegisterClass *RC =
5903 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5904 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5905 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5906 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5907 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5908 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5909 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5910 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5911 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5912 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5913 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5914 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5915 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5917 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5921 // fallthrough --> loopMBB
5922 BB->addSuccessor(loopMBB);
5924 // The 4-byte load must be aligned, while a char or short may be
5925 // anywhere in the word. Hence all this nasty bookkeeping code.
5926 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5927 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5928 // xori shift, shift1, 24 [16]
5929 // rlwinm ptr, ptr1, 0, 0, 29
5930 // slw incr2, incr, shift
5931 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5932 // slw mask, mask2, shift
5934 // lwarx tmpDest, ptr
5935 // add tmp, tmpDest, incr2
5936 // andc tmp2, tmpDest, mask
5937 // and tmp3, tmp, mask
5938 // or tmp4, tmp3, tmp2
5941 // fallthrough --> exitMBB
5942 // srw dest, tmpDest, shift
5943 if (ptrA != ZeroReg) {
5944 Ptr1Reg = RegInfo.createVirtualRegister(RC);
5945 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5946 .addReg(ptrA).addReg(ptrB);
5950 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5951 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5952 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5953 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5955 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5956 .addReg(Ptr1Reg).addImm(0).addImm(61);
5958 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5959 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5960 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
5961 .addReg(incr).addReg(ShiftReg);
5963 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5965 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5966 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
5968 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5969 .addReg(Mask2Reg).addReg(ShiftReg);
5972 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5973 .addReg(ZeroReg).addReg(PtrReg);
5975 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
5976 .addReg(Incr2Reg).addReg(TmpDestReg);
5977 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
5978 .addReg(TmpDestReg).addReg(MaskReg);
5979 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
5980 .addReg(TmpReg).addReg(MaskReg);
5981 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
5982 .addReg(Tmp3Reg).addReg(Tmp2Reg);
5983 BuildMI(BB, dl, TII->get(PPC::STWCX))
5984 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
5985 BuildMI(BB, dl, TII->get(PPC::BCC))
5986 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5987 BB->addSuccessor(loopMBB);
5988 BB->addSuccessor(exitMBB);
5993 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
5998 llvm::MachineBasicBlock*
5999 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6000 MachineBasicBlock *MBB) const {
6001 DebugLoc DL = MI->getDebugLoc();
6002 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6004 MachineFunction *MF = MBB->getParent();
6005 MachineRegisterInfo &MRI = MF->getRegInfo();
6007 const BasicBlock *BB = MBB->getBasicBlock();
6008 MachineFunction::iterator I = MBB;
6012 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6013 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6015 unsigned DstReg = MI->getOperand(0).getReg();
6016 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6017 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6018 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6019 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6021 MVT PVT = getPointerTy();
6022 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6023 "Invalid Pointer Size!");
6024 // For v = setjmp(buf), we generate
6027 // SjLjSetup mainMBB
6033 // buf[LabelOffset] = LR
6037 // v = phi(main, restore)
6040 MachineBasicBlock *thisMBB = MBB;
6041 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6042 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6043 MF->insert(I, mainMBB);
6044 MF->insert(I, sinkMBB);
6046 MachineInstrBuilder MIB;
6048 // Transfer the remainder of BB and its successor edges to sinkMBB.
6049 sinkMBB->splice(sinkMBB->begin(), MBB,
6050 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
6051 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6053 // Note that the structure of the jmp_buf used here is not compatible
6054 // with that used by libc, and is not designed to be. Specifically, it
6055 // stores only those 'reserved' registers that LLVM does not otherwise
6056 // understand how to spill. Also, by convention, by the time this
6057 // intrinsic is called, Clang has already stored the frame address in the
6058 // first slot of the buffer and stack address in the third. Following the
6059 // X86 target code, we'll store the jump address in the second slot. We also
6060 // need to save the TOC pointer (R2) to handle jumps between shared
6061 // libraries, and that will be stored in the fourth slot. The thread
6062 // identifier (R13) is not affected.
6065 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6066 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6068 // Prepare IP either in reg.
6069 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6070 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6071 unsigned BufReg = MI->getOperand(1).getReg();
6073 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6074 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6076 .addImm(TOCOffset / 4)
6079 MIB.setMemRefs(MMOBegin, MMOEnd);
6083 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6084 MIB.addRegMask(PPCRegInfo->getNoPreservedMask());
6086 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6088 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6090 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6092 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6093 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6097 MIB = BuildMI(mainMBB, DL,
6098 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6101 if (PPCSubTarget.isPPC64()) {
6102 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6104 .addImm(LabelOffset / 4)
6107 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6109 .addImm(LabelOffset)
6113 MIB.setMemRefs(MMOBegin, MMOEnd);
6115 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6116 mainMBB->addSuccessor(sinkMBB);
6119 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6120 TII->get(PPC::PHI), DstReg)
6121 .addReg(mainDstReg).addMBB(mainMBB)
6122 .addReg(restoreDstReg).addMBB(thisMBB);
6124 MI->eraseFromParent();
6129 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6130 MachineBasicBlock *MBB) const {
6131 DebugLoc DL = MI->getDebugLoc();
6132 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6134 MachineFunction *MF = MBB->getParent();
6135 MachineRegisterInfo &MRI = MF->getRegInfo();
6138 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6139 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6141 MVT PVT = getPointerTy();
6142 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6143 "Invalid Pointer Size!");
6145 const TargetRegisterClass *RC =
6146 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6147 unsigned Tmp = MRI.createVirtualRegister(RC);
6148 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6149 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6150 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6152 MachineInstrBuilder MIB;
6154 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6155 const int64_t SPOffset = 2 * PVT.getStoreSize();
6156 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6158 unsigned BufReg = MI->getOperand(0).getReg();
6160 // Reload FP (the jumped-to function may not have had a
6161 // frame pointer, and if so, then its r31 will be restored
6163 if (PVT == MVT::i64) {
6164 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6168 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6172 MIB.setMemRefs(MMOBegin, MMOEnd);
6175 if (PVT == MVT::i64) {
6176 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6177 .addImm(LabelOffset / 4)
6180 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6181 .addImm(LabelOffset)
6184 MIB.setMemRefs(MMOBegin, MMOEnd);
6187 if (PVT == MVT::i64) {
6188 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6189 .addImm(SPOffset / 4)
6192 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6196 MIB.setMemRefs(MMOBegin, MMOEnd);
6198 // FIXME: When we also support base pointers, that register must also be
6202 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6203 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6204 .addImm(TOCOffset / 4)
6207 MIB.setMemRefs(MMOBegin, MMOEnd);
6211 BuildMI(*MBB, MI, DL,
6212 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6213 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6215 MI->eraseFromParent();
6220 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6221 MachineBasicBlock *BB) const {
6222 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6223 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6224 return emitEHSjLjSetJmp(MI, BB);
6225 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6226 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6227 return emitEHSjLjLongJmp(MI, BB);
6230 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6232 // To "insert" these instructions we actually have to insert their
6233 // control-flow patterns.
6234 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6235 MachineFunction::iterator It = BB;
6238 MachineFunction *F = BB->getParent();
6240 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6241 MI->getOpcode() == PPC::SELECT_CC_I8)) {
6242 unsigned OpCode = MI->getOpcode() == PPC::SELECT_CC_I8 ?
6243 PPC::ISEL8 : PPC::ISEL;
6244 unsigned SelectPred = MI->getOperand(4).getImm();
6245 DebugLoc dl = MI->getDebugLoc();
6249 switch (SelectPred) {
6250 default: llvm_unreachable("invalid predicate for isel");
6251 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
6252 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
6253 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
6254 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
6255 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
6256 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
6257 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
6258 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
6261 BuildMI(*BB, MI, dl, TII->get(OpCode), MI->getOperand(0).getReg())
6262 .addReg(MI->getOperand(SwapOps? 3 : 2).getReg())
6263 .addReg(MI->getOperand(SwapOps? 2 : 3).getReg())
6264 .addReg(MI->getOperand(1).getReg(), 0, SubIdx);
6265 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6266 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6267 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6268 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6269 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
6272 // The incoming instruction knows the destination vreg to set, the
6273 // condition code register to branch on, the true/false values to
6274 // select between, and a branch opcode to use.
6279 // cmpTY ccX, r1, r2
6281 // fallthrough --> copy0MBB
6282 MachineBasicBlock *thisMBB = BB;
6283 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6284 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6285 unsigned SelectPred = MI->getOperand(4).getImm();
6286 DebugLoc dl = MI->getDebugLoc();
6287 F->insert(It, copy0MBB);
6288 F->insert(It, sinkMBB);
6290 // Transfer the remainder of BB and its successor edges to sinkMBB.
6291 sinkMBB->splice(sinkMBB->begin(), BB,
6292 llvm::next(MachineBasicBlock::iterator(MI)),
6294 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6296 // Next, add the true and fallthrough blocks as its successors.
6297 BB->addSuccessor(copy0MBB);
6298 BB->addSuccessor(sinkMBB);
6300 BuildMI(BB, dl, TII->get(PPC::BCC))
6301 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6304 // %FalseValue = ...
6305 // # fallthrough to sinkMBB
6308 // Update machine-CFG edges
6309 BB->addSuccessor(sinkMBB);
6312 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6315 BuildMI(*BB, BB->begin(), dl,
6316 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6317 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6318 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6320 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6321 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6322 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6323 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6324 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6325 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6326 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6327 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6329 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6330 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6331 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6332 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6333 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6334 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6335 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6336 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6338 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6339 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6340 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6341 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6342 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6343 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6344 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6345 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6347 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6348 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6349 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6350 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6351 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6352 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6353 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6354 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6356 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6357 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6358 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6359 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6360 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6361 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6362 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6363 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6365 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6366 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6367 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6368 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6369 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6370 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6371 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6372 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6374 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6375 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6376 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6377 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6378 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6379 BB = EmitAtomicBinary(MI, BB, false, 0);
6380 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6381 BB = EmitAtomicBinary(MI, BB, true, 0);
6383 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6384 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6385 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6387 unsigned dest = MI->getOperand(0).getReg();
6388 unsigned ptrA = MI->getOperand(1).getReg();
6389 unsigned ptrB = MI->getOperand(2).getReg();
6390 unsigned oldval = MI->getOperand(3).getReg();
6391 unsigned newval = MI->getOperand(4).getReg();
6392 DebugLoc dl = MI->getDebugLoc();
6394 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6395 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6396 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6397 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6398 F->insert(It, loop1MBB);
6399 F->insert(It, loop2MBB);
6400 F->insert(It, midMBB);
6401 F->insert(It, exitMBB);
6402 exitMBB->splice(exitMBB->begin(), BB,
6403 llvm::next(MachineBasicBlock::iterator(MI)),
6405 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6409 // fallthrough --> loopMBB
6410 BB->addSuccessor(loop1MBB);
6413 // l[wd]arx dest, ptr
6414 // cmp[wd] dest, oldval
6417 // st[wd]cx. newval, ptr
6421 // st[wd]cx. dest, ptr
6424 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6425 .addReg(ptrA).addReg(ptrB);
6426 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6427 .addReg(oldval).addReg(dest);
6428 BuildMI(BB, dl, TII->get(PPC::BCC))
6429 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6430 BB->addSuccessor(loop2MBB);
6431 BB->addSuccessor(midMBB);
6434 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6435 .addReg(newval).addReg(ptrA).addReg(ptrB);
6436 BuildMI(BB, dl, TII->get(PPC::BCC))
6437 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6438 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6439 BB->addSuccessor(loop1MBB);
6440 BB->addSuccessor(exitMBB);
6443 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6444 .addReg(dest).addReg(ptrA).addReg(ptrB);
6445 BB->addSuccessor(exitMBB);
6450 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6451 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6452 // We must use 64-bit registers for addresses when targeting 64-bit,
6453 // since we're actually doing arithmetic on them. Other registers
6455 bool is64bit = PPCSubTarget.isPPC64();
6456 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6458 unsigned dest = MI->getOperand(0).getReg();
6459 unsigned ptrA = MI->getOperand(1).getReg();
6460 unsigned ptrB = MI->getOperand(2).getReg();
6461 unsigned oldval = MI->getOperand(3).getReg();
6462 unsigned newval = MI->getOperand(4).getReg();
6463 DebugLoc dl = MI->getDebugLoc();
6465 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6466 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6467 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6468 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6469 F->insert(It, loop1MBB);
6470 F->insert(It, loop2MBB);
6471 F->insert(It, midMBB);
6472 F->insert(It, exitMBB);
6473 exitMBB->splice(exitMBB->begin(), BB,
6474 llvm::next(MachineBasicBlock::iterator(MI)),
6476 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6478 MachineRegisterInfo &RegInfo = F->getRegInfo();
6479 const TargetRegisterClass *RC =
6480 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6481 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6482 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6483 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6484 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6485 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6486 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6487 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6488 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6489 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6490 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6491 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6492 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6493 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6494 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6496 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6497 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6500 // fallthrough --> loopMBB
6501 BB->addSuccessor(loop1MBB);
6503 // The 4-byte load must be aligned, while a char or short may be
6504 // anywhere in the word. Hence all this nasty bookkeeping code.
6505 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6506 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6507 // xori shift, shift1, 24 [16]
6508 // rlwinm ptr, ptr1, 0, 0, 29
6509 // slw newval2, newval, shift
6510 // slw oldval2, oldval,shift
6511 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6512 // slw mask, mask2, shift
6513 // and newval3, newval2, mask
6514 // and oldval3, oldval2, mask
6516 // lwarx tmpDest, ptr
6517 // and tmp, tmpDest, mask
6518 // cmpw tmp, oldval3
6521 // andc tmp2, tmpDest, mask
6522 // or tmp4, tmp2, newval3
6527 // stwcx. tmpDest, ptr
6529 // srw dest, tmpDest, shift
6530 if (ptrA != ZeroReg) {
6531 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6532 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6533 .addReg(ptrA).addReg(ptrB);
6537 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6538 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6539 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6540 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6542 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6543 .addReg(Ptr1Reg).addImm(0).addImm(61);
6545 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6546 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6547 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6548 .addReg(newval).addReg(ShiftReg);
6549 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6550 .addReg(oldval).addReg(ShiftReg);
6552 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6554 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6555 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6556 .addReg(Mask3Reg).addImm(65535);
6558 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6559 .addReg(Mask2Reg).addReg(ShiftReg);
6560 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6561 .addReg(NewVal2Reg).addReg(MaskReg);
6562 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6563 .addReg(OldVal2Reg).addReg(MaskReg);
6566 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6567 .addReg(ZeroReg).addReg(PtrReg);
6568 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6569 .addReg(TmpDestReg).addReg(MaskReg);
6570 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6571 .addReg(TmpReg).addReg(OldVal3Reg);
6572 BuildMI(BB, dl, TII->get(PPC::BCC))
6573 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6574 BB->addSuccessor(loop2MBB);
6575 BB->addSuccessor(midMBB);
6578 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6579 .addReg(TmpDestReg).addReg(MaskReg);
6580 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6581 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6582 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6583 .addReg(ZeroReg).addReg(PtrReg);
6584 BuildMI(BB, dl, TII->get(PPC::BCC))
6585 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6586 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6587 BB->addSuccessor(loop1MBB);
6588 BB->addSuccessor(exitMBB);
6591 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6592 .addReg(ZeroReg).addReg(PtrReg);
6593 BB->addSuccessor(exitMBB);
6598 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6600 } else if (MI->getOpcode() == PPC::FADDrtz) {
6601 // This pseudo performs an FADD with rounding mode temporarily forced
6602 // to round-to-zero. We emit this via custom inserter since the FPSCR
6603 // is not modeled at the SelectionDAG level.
6604 unsigned Dest = MI->getOperand(0).getReg();
6605 unsigned Src1 = MI->getOperand(1).getReg();
6606 unsigned Src2 = MI->getOperand(2).getReg();
6607 DebugLoc dl = MI->getDebugLoc();
6609 MachineRegisterInfo &RegInfo = F->getRegInfo();
6610 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6612 // Save FPSCR value.
6613 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6615 // Set rounding mode to round-to-zero.
6616 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6617 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6619 // Perform addition.
6620 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6622 // Restore FPSCR value.
6623 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6624 } else if (MI->getOpcode() == PPC::FRINDrint ||
6625 MI->getOpcode() == PPC::FRINSrint) {
6626 bool isf32 = MI->getOpcode() == PPC::FRINSrint;
6627 unsigned Dest = MI->getOperand(0).getReg();
6628 unsigned Src = MI->getOperand(1).getReg();
6629 DebugLoc dl = MI->getDebugLoc();
6631 MachineRegisterInfo &RegInfo = F->getRegInfo();
6632 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
6634 // Perform the rounding.
6635 BuildMI(*BB, MI, dl, TII->get(isf32 ? PPC::FRINS : PPC::FRIND), Dest)
6638 // Compare the results.
6639 BuildMI(*BB, MI, dl, TII->get(isf32 ? PPC::FCMPUS : PPC::FCMPUD), CRReg)
6640 .addReg(Dest).addReg(Src);
6642 // If the results were not equal, then set the FPSCR XX bit.
6643 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6644 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6645 F->insert(It, midMBB);
6646 F->insert(It, exitMBB);
6647 exitMBB->splice(exitMBB->begin(), BB,
6648 llvm::next(MachineBasicBlock::iterator(MI)),
6650 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6652 BuildMI(*BB, MI, dl, TII->get(PPC::BCC))
6653 .addImm(PPC::PRED_EQ).addReg(CRReg).addMBB(exitMBB);
6655 BB->addSuccessor(midMBB);
6656 BB->addSuccessor(exitMBB);
6660 // Set the FPSCR XX bit (FE_INEXACT). Note that we cannot just set
6661 // the FI bit here because that will not automatically set XX also,
6662 // and XX is what libm interprets as the FE_INEXACT flag.
6663 BuildMI(BB, dl, TII->get(PPC::MTFSB1)).addImm(/* 38 - 32 = */ 6);
6664 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6666 BB->addSuccessor(exitMBB);
6670 llvm_unreachable("Unexpected instr type to insert");
6673 MI->eraseFromParent(); // The pseudo instruction is gone now.
6677 //===----------------------------------------------------------------------===//
6678 // Target Optimization Hooks
6679 //===----------------------------------------------------------------------===//
6681 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6682 DAGCombinerInfo &DCI) const {
6683 if (DCI.isAfterLegalizeVectorOps())
6686 EVT VT = Op.getValueType();
6688 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6689 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6690 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6692 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6693 // For the reciprocal, we need to find the zero of the function:
6694 // F(X) = A X - 1 [which has a zero at X = 1/A]
6696 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
6697 // does not require additional intermediate precision]
6699 // Convergence is quadratic, so we essentially double the number of digits
6700 // correct after every iteration. The minimum architected relative
6701 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6702 // 23 digits and double has 52 digits.
6703 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6704 if (VT.getScalarType() == MVT::f64)
6707 SelectionDAG &DAG = DCI.DAG;
6708 DebugLoc dl = Op.getDebugLoc();
6711 DAG.getConstantFP(1.0, VT.getScalarType());
6712 if (VT.isVector()) {
6713 assert(VT.getVectorNumElements() == 4 &&
6714 "Unknown vector type");
6715 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6716 FPOne, FPOne, FPOne, FPOne);
6719 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
6720 DCI.AddToWorklist(Est.getNode());
6722 // Newton iterations: Est = Est + Est (1 - Arg * Est)
6723 for (int i = 0; i < Iterations; ++i) {
6724 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
6725 DCI.AddToWorklist(NewEst.getNode());
6727 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
6728 DCI.AddToWorklist(NewEst.getNode());
6730 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6731 DCI.AddToWorklist(NewEst.getNode());
6733 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
6734 DCI.AddToWorklist(Est.getNode());
6743 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
6744 DAGCombinerInfo &DCI) const {
6745 if (DCI.isAfterLegalizeVectorOps())
6748 EVT VT = Op.getValueType();
6750 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
6751 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
6752 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6754 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6755 // For the reciprocal sqrt, we need to find the zero of the function:
6756 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
6758 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
6759 // As a result, we precompute A/2 prior to the iteration loop.
6761 // Convergence is quadratic, so we essentially double the number of digits
6762 // correct after every iteration. The minimum architected relative
6763 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6764 // 23 digits and double has 52 digits.
6765 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6766 if (VT.getScalarType() == MVT::f64)
6769 SelectionDAG &DAG = DCI.DAG;
6770 DebugLoc dl = Op.getDebugLoc();
6772 SDValue FPThreeHalves =
6773 DAG.getConstantFP(1.5, VT.getScalarType());
6774 if (VT.isVector()) {
6775 assert(VT.getVectorNumElements() == 4 &&
6776 "Unknown vector type");
6777 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6778 FPThreeHalves, FPThreeHalves,
6779 FPThreeHalves, FPThreeHalves);
6782 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
6783 DCI.AddToWorklist(Est.getNode());
6785 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
6786 // this entire sequence requires only one FP constant.
6787 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
6788 DCI.AddToWorklist(HalfArg.getNode());
6790 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
6791 DCI.AddToWorklist(HalfArg.getNode());
6793 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
6794 for (int i = 0; i < Iterations; ++i) {
6795 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
6796 DCI.AddToWorklist(NewEst.getNode());
6798 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
6799 DCI.AddToWorklist(NewEst.getNode());
6801 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
6802 DCI.AddToWorklist(NewEst.getNode());
6804 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6805 DCI.AddToWorklist(Est.getNode());
6814 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6815 DAGCombinerInfo &DCI) const {
6816 const TargetMachine &TM = getTargetMachine();
6817 SelectionDAG &DAG = DCI.DAG;
6818 DebugLoc dl = N->getDebugLoc();
6819 switch (N->getOpcode()) {
6822 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6823 if (C->isNullValue()) // 0 << V -> 0.
6824 return N->getOperand(0);
6828 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6829 if (C->isNullValue()) // 0 >>u V -> 0.
6830 return N->getOperand(0);
6834 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6835 if (C->isNullValue() || // 0 >>s V -> 0.
6836 C->isAllOnesValue()) // -1 >>s V -> -1.
6837 return N->getOperand(0);
6841 assert(TM.Options.UnsafeFPMath &&
6842 "Reciprocal estimates require UnsafeFPMath");
6844 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
6846 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
6847 if (RV.getNode() != 0) {
6848 DCI.AddToWorklist(RV.getNode());
6849 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6850 N->getOperand(0), RV);
6852 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
6853 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
6855 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
6857 if (RV.getNode() != 0) {
6858 DCI.AddToWorklist(RV.getNode());
6859 RV = DAG.getNode(ISD::FP_EXTEND, N->getOperand(1).getDebugLoc(),
6860 N->getValueType(0), RV);
6861 DCI.AddToWorklist(RV.getNode());
6862 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6863 N->getOperand(0), RV);
6865 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
6866 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
6868 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
6870 if (RV.getNode() != 0) {
6871 DCI.AddToWorklist(RV.getNode());
6872 RV = DAG.getNode(ISD::FP_ROUND, N->getOperand(1).getDebugLoc(),
6873 N->getValueType(0), RV,
6874 N->getOperand(1).getOperand(1));
6875 DCI.AddToWorklist(RV.getNode());
6876 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6877 N->getOperand(0), RV);
6881 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
6882 if (RV.getNode() != 0) {
6883 DCI.AddToWorklist(RV.getNode());
6884 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6885 N->getOperand(0), RV);
6891 assert(TM.Options.UnsafeFPMath &&
6892 "Reciprocal estimates require UnsafeFPMath");
6894 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
6896 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
6897 if (RV.getNode() != 0) {
6898 DCI.AddToWorklist(RV.getNode());
6899 RV = DAGCombineFastRecip(RV, DCI);
6900 if (RV.getNode() != 0)
6906 case ISD::SINT_TO_FP:
6907 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6908 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6909 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6910 // We allow the src/dst to be either f32/f64, but the intermediate
6911 // type must be i64.
6912 if (N->getOperand(0).getValueType() == MVT::i64 &&
6913 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6914 SDValue Val = N->getOperand(0).getOperand(0);
6915 if (Val.getValueType() == MVT::f32) {
6916 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6917 DCI.AddToWorklist(Val.getNode());
6920 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
6921 DCI.AddToWorklist(Val.getNode());
6922 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
6923 DCI.AddToWorklist(Val.getNode());
6924 if (N->getValueType(0) == MVT::f32) {
6925 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
6926 DAG.getIntPtrConstant(0));
6927 DCI.AddToWorklist(Val.getNode());
6930 } else if (N->getOperand(0).getValueType() == MVT::i32) {
6931 // If the intermediate type is i32, we can avoid the load/store here
6938 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
6939 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
6940 !cast<StoreSDNode>(N)->isTruncatingStore() &&
6941 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
6942 N->getOperand(1).getValueType() == MVT::i32 &&
6943 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
6944 SDValue Val = N->getOperand(1).getOperand(0);
6945 if (Val.getValueType() == MVT::f32) {
6946 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6947 DCI.AddToWorklist(Val.getNode());
6949 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
6950 DCI.AddToWorklist(Val.getNode());
6953 N->getOperand(0), Val, N->getOperand(2),
6954 DAG.getValueType(N->getOperand(1).getValueType())
6957 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6958 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
6959 cast<StoreSDNode>(N)->getMemoryVT(),
6960 cast<StoreSDNode>(N)->getMemOperand());
6961 DCI.AddToWorklist(Val.getNode());
6965 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
6966 if (cast<StoreSDNode>(N)->isUnindexed() &&
6967 N->getOperand(1).getOpcode() == ISD::BSWAP &&
6968 N->getOperand(1).getNode()->hasOneUse() &&
6969 (N->getOperand(1).getValueType() == MVT::i32 ||
6970 N->getOperand(1).getValueType() == MVT::i16 ||
6971 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
6972 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
6973 N->getOperand(1).getValueType() == MVT::i64))) {
6974 SDValue BSwapOp = N->getOperand(1).getOperand(0);
6975 // Do an any-extend to 32-bits if this is a half-word input.
6976 if (BSwapOp.getValueType() == MVT::i16)
6977 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
6980 N->getOperand(0), BSwapOp, N->getOperand(2),
6981 DAG.getValueType(N->getOperand(1).getValueType())
6984 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
6985 Ops, array_lengthof(Ops),
6986 cast<StoreSDNode>(N)->getMemoryVT(),
6987 cast<StoreSDNode>(N)->getMemOperand());
6991 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
6992 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6993 N->getOperand(0).hasOneUse() &&
6994 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
6995 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
6996 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
6997 N->getValueType(0) == MVT::i64))) {
6998 SDValue Load = N->getOperand(0);
6999 LoadSDNode *LD = cast<LoadSDNode>(Load);
7000 // Create the byte-swapping load.
7002 LD->getChain(), // Chain
7003 LD->getBasePtr(), // Ptr
7004 DAG.getValueType(N->getValueType(0)) // VT
7007 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
7008 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
7009 MVT::i64 : MVT::i32, MVT::Other),
7010 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
7012 // If this is an i16 load, insert the truncate.
7013 SDValue ResVal = BSLoad;
7014 if (N->getValueType(0) == MVT::i16)
7015 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
7017 // First, combine the bswap away. This makes the value produced by the
7019 DCI.CombineTo(N, ResVal);
7021 // Next, combine the load away, we give it a bogus result value but a real
7022 // chain result. The result value is dead because the bswap is dead.
7023 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
7025 // Return N so it doesn't get rechecked!
7026 return SDValue(N, 0);
7030 case PPCISD::VCMP: {
7031 // If a VCMPo node already exists with exactly the same operands as this
7032 // node, use its result instead of this node (VCMPo computes both a CR6 and
7033 // a normal output).
7035 if (!N->getOperand(0).hasOneUse() &&
7036 !N->getOperand(1).hasOneUse() &&
7037 !N->getOperand(2).hasOneUse()) {
7039 // Scan all of the users of the LHS, looking for VCMPo's that match.
7040 SDNode *VCMPoNode = 0;
7042 SDNode *LHSN = N->getOperand(0).getNode();
7043 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
7045 if (UI->getOpcode() == PPCISD::VCMPo &&
7046 UI->getOperand(1) == N->getOperand(1) &&
7047 UI->getOperand(2) == N->getOperand(2) &&
7048 UI->getOperand(0) == N->getOperand(0)) {
7053 // If there is no VCMPo node, or if the flag value has a single use, don't
7055 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
7058 // Look at the (necessarily single) use of the flag value. If it has a
7059 // chain, this transformation is more complex. Note that multiple things
7060 // could use the value result, which we should ignore.
7061 SDNode *FlagUser = 0;
7062 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
7063 FlagUser == 0; ++UI) {
7064 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
7066 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
7067 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
7074 // If the user is a MFCR instruction, we know this is safe. Otherwise we
7075 // give up for right now.
7076 if (FlagUser->getOpcode() == PPCISD::MFCR)
7077 return SDValue(VCMPoNode, 0);
7082 // If this is a branch on an altivec predicate comparison, lower this so
7083 // that we don't have to do a MFCR: instead, branch directly on CR6. This
7084 // lowering is done pre-legalize, because the legalizer lowers the predicate
7085 // compare down to code that is difficult to reassemble.
7086 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
7087 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
7091 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
7092 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
7093 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
7094 assert(isDot && "Can't compare against a vector result!");
7096 // If this is a comparison against something other than 0/1, then we know
7097 // that the condition is never/always true.
7098 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
7099 if (Val != 0 && Val != 1) {
7100 if (CC == ISD::SETEQ) // Cond never true, remove branch.
7101 return N->getOperand(0);
7102 // Always !=, turn it into an unconditional branch.
7103 return DAG.getNode(ISD::BR, dl, MVT::Other,
7104 N->getOperand(0), N->getOperand(4));
7107 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
7109 // Create the PPCISD altivec 'dot' comparison node.
7111 LHS.getOperand(2), // LHS of compare
7112 LHS.getOperand(3), // RHS of compare
7113 DAG.getConstant(CompareOpc, MVT::i32)
7115 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
7116 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
7118 // Unpack the result based on how the target uses it.
7119 PPC::Predicate CompOpc;
7120 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
7121 default: // Can't happen, don't crash on invalid number though.
7122 case 0: // Branch on the value of the EQ bit of CR6.
7123 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
7125 case 1: // Branch on the inverted value of the EQ bit of CR6.
7126 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
7128 case 2: // Branch on the value of the LT bit of CR6.
7129 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
7131 case 3: // Branch on the inverted value of the LT bit of CR6.
7132 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
7136 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
7137 DAG.getConstant(CompOpc, MVT::i32),
7138 DAG.getRegister(PPC::CR6, MVT::i32),
7139 N->getOperand(4), CompNode.getValue(1));
7148 //===----------------------------------------------------------------------===//
7149 // Inline Assembly Support
7150 //===----------------------------------------------------------------------===//
7152 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7155 const SelectionDAG &DAG,
7156 unsigned Depth) const {
7157 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
7158 switch (Op.getOpcode()) {
7160 case PPCISD::LBRX: {
7161 // lhbrx is known to have the top bits cleared out.
7162 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
7163 KnownZero = 0xFFFF0000;
7166 case ISD::INTRINSIC_WO_CHAIN: {
7167 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
7169 case Intrinsic::ppc_altivec_vcmpbfp_p:
7170 case Intrinsic::ppc_altivec_vcmpeqfp_p:
7171 case Intrinsic::ppc_altivec_vcmpequb_p:
7172 case Intrinsic::ppc_altivec_vcmpequh_p:
7173 case Intrinsic::ppc_altivec_vcmpequw_p:
7174 case Intrinsic::ppc_altivec_vcmpgefp_p:
7175 case Intrinsic::ppc_altivec_vcmpgtfp_p:
7176 case Intrinsic::ppc_altivec_vcmpgtsb_p:
7177 case Intrinsic::ppc_altivec_vcmpgtsh_p:
7178 case Intrinsic::ppc_altivec_vcmpgtsw_p:
7179 case Intrinsic::ppc_altivec_vcmpgtub_p:
7180 case Intrinsic::ppc_altivec_vcmpgtuh_p:
7181 case Intrinsic::ppc_altivec_vcmpgtuw_p:
7182 KnownZero = ~1U; // All bits but the low one are known to be zero.
7190 /// getConstraintType - Given a constraint, return the type of
7191 /// constraint it is for this target.
7192 PPCTargetLowering::ConstraintType
7193 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
7194 if (Constraint.size() == 1) {
7195 switch (Constraint[0]) {
7202 return C_RegisterClass;
7204 // FIXME: While Z does indicate a memory constraint, it specifically
7205 // indicates an r+r address (used in conjunction with the 'y' modifier
7206 // in the replacement string). Currently, we're forcing the base
7207 // register to be r0 in the asm printer (which is interpreted as zero)
7208 // and forming the complete address in the second register. This is
7213 return TargetLowering::getConstraintType(Constraint);
7216 /// Examine constraint type and operand type and determine a weight value.
7217 /// This object must already have been set up with the operand type
7218 /// and the current alternative constraint selected.
7219 TargetLowering::ConstraintWeight
7220 PPCTargetLowering::getSingleConstraintMatchWeight(
7221 AsmOperandInfo &info, const char *constraint) const {
7222 ConstraintWeight weight = CW_Invalid;
7223 Value *CallOperandVal = info.CallOperandVal;
7224 // If we don't have a value, we can't do a match,
7225 // but allow it at the lowest weight.
7226 if (CallOperandVal == NULL)
7228 Type *type = CallOperandVal->getType();
7229 // Look at the constraint type.
7230 switch (*constraint) {
7232 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7235 if (type->isIntegerTy())
7236 weight = CW_Register;
7239 if (type->isFloatTy())
7240 weight = CW_Register;
7243 if (type->isDoubleTy())
7244 weight = CW_Register;
7247 if (type->isVectorTy())
7248 weight = CW_Register;
7251 weight = CW_Register;
7260 std::pair<unsigned, const TargetRegisterClass*>
7261 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7263 if (Constraint.size() == 1) {
7264 // GCC RS6000 Constraint Letters
7265 switch (Constraint[0]) {
7267 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
7268 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
7269 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
7271 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
7272 return std::make_pair(0U, &PPC::G8RCRegClass);
7273 return std::make_pair(0U, &PPC::GPRCRegClass);
7275 if (VT == MVT::f32 || VT == MVT::i32)
7276 return std::make_pair(0U, &PPC::F4RCRegClass);
7277 if (VT == MVT::f64 || VT == MVT::i64)
7278 return std::make_pair(0U, &PPC::F8RCRegClass);
7281 return std::make_pair(0U, &PPC::VRRCRegClass);
7283 return std::make_pair(0U, &PPC::CRRCRegClass);
7287 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7291 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7292 /// vector. If it is invalid, don't add anything to Ops.
7293 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7294 std::string &Constraint,
7295 std::vector<SDValue>&Ops,
7296 SelectionDAG &DAG) const {
7297 SDValue Result(0,0);
7299 // Only support length 1 constraints.
7300 if (Constraint.length() > 1) return;
7302 char Letter = Constraint[0];
7313 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
7314 if (!CST) return; // Must be an immediate to match.
7315 unsigned Value = CST->getZExtValue();
7317 default: llvm_unreachable("Unknown constraint letter!");
7318 case 'I': // "I" is a signed 16-bit constant.
7319 if ((short)Value == (int)Value)
7320 Result = DAG.getTargetConstant(Value, Op.getValueType());
7322 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
7323 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
7324 if ((short)Value == 0)
7325 Result = DAG.getTargetConstant(Value, Op.getValueType());
7327 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
7328 if ((Value >> 16) == 0)
7329 Result = DAG.getTargetConstant(Value, Op.getValueType());
7331 case 'M': // "M" is a constant that is greater than 31.
7333 Result = DAG.getTargetConstant(Value, Op.getValueType());
7335 case 'N': // "N" is a positive constant that is an exact power of two.
7336 if ((int)Value > 0 && isPowerOf2_32(Value))
7337 Result = DAG.getTargetConstant(Value, Op.getValueType());
7339 case 'O': // "O" is the constant zero.
7341 Result = DAG.getTargetConstant(Value, Op.getValueType());
7343 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
7344 if ((short)-Value == (int)-Value)
7345 Result = DAG.getTargetConstant(Value, Op.getValueType());
7352 if (Result.getNode()) {
7353 Ops.push_back(Result);
7357 // Handle standard constraint letters.
7358 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7361 // isLegalAddressingMode - Return true if the addressing mode represented
7362 // by AM is legal for this target, for a load/store of the specified type.
7363 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
7365 // FIXME: PPC does not allow r+i addressing modes for vectors!
7367 // PPC allows a sign-extended 16-bit immediate field.
7368 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
7371 // No global is ever allowed as a base.
7375 // PPC only support r+r,
7377 case 0: // "r+i" or just "i", depending on HasBaseReg.
7380 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
7382 // Otherwise we have r+r or r+i.
7385 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
7387 // Allow 2*r as r+r.
7390 // No other scales are supported.
7397 /// isLegalAddressImmediate - Return true if the integer value can be used
7398 /// as the offset of the target addressing mode for load / store of the
7400 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{
7401 // PPC allows a sign-extended 16-bit immediate field.
7402 return (V > -(1 << 16) && V < (1 << 16)-1);
7405 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
7409 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
7410 SelectionDAG &DAG) const {
7411 MachineFunction &MF = DAG.getMachineFunction();
7412 MachineFrameInfo *MFI = MF.getFrameInfo();
7413 MFI->setReturnAddressIsTaken(true);
7415 DebugLoc dl = Op.getDebugLoc();
7416 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7418 // Make sure the function does not optimize away the store of the RA to
7420 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7421 FuncInfo->setLRStoreRequired();
7422 bool isPPC64 = PPCSubTarget.isPPC64();
7423 bool isDarwinABI = PPCSubTarget.isDarwinABI();
7426 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7429 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
7430 isPPC64? MVT::i64 : MVT::i32);
7431 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7432 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7434 MachinePointerInfo(), false, false, false, 0);
7437 // Just load the return address off the stack.
7438 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
7439 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7440 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
7443 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
7444 SelectionDAG &DAG) const {
7445 DebugLoc dl = Op.getDebugLoc();
7446 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7448 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
7449 bool isPPC64 = PtrVT == MVT::i64;
7451 MachineFunction &MF = DAG.getMachineFunction();
7452 MachineFrameInfo *MFI = MF.getFrameInfo();
7453 MFI->setFrameAddressIsTaken(true);
7455 // Naked functions never have a frame pointer, and so we use r1. For all
7456 // other functions, this decision must be delayed until during PEI.
7458 if (MF.getFunction()->getAttributes().hasAttribute(
7459 AttributeSet::FunctionIndex, Attribute::Naked))
7460 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
7462 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
7464 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
7467 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
7468 FrameAddr, MachinePointerInfo(), false, false,
7474 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7475 // The PowerPC target isn't yet aware of offsets.
7479 /// getOptimalMemOpType - Returns the target specific optimal type for load
7480 /// and store operations as a result of memset, memcpy, and memmove
7481 /// lowering. If DstAlign is zero that means it's safe to destination
7482 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
7483 /// means there isn't a need to check it against alignment requirement,
7484 /// probably because the source does not need to be loaded. If 'IsMemset' is
7485 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
7486 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
7487 /// source is constant so it does not need to be loaded.
7488 /// It returns EVT::Other if the type should be determined using generic
7489 /// target-independent logic.
7490 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
7491 unsigned DstAlign, unsigned SrcAlign,
7492 bool IsMemset, bool ZeroMemset,
7494 MachineFunction &MF) const {
7495 if (this->PPCSubTarget.isPPC64()) {
7502 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
7504 if (DisablePPCUnaligned)
7507 // PowerPC supports unaligned memory access for simple non-vector types.
7508 // Although accessing unaligned addresses is not as efficient as accessing
7509 // aligned addresses, it is generally more efficient than manual expansion,
7510 // and generally only traps for software emulation when crossing page
7516 if (VT.getSimpleVT().isVector())
7519 if (VT == MVT::ppcf128)
7528 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
7529 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
7530 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
7531 /// is expanded to mul + add.
7532 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
7536 switch (VT.getSimpleVT().SimpleTy) {
7548 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
7550 return TargetLowering::getSchedulingPreference(N);