1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetOptions.h"
41 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
42 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
44 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
45 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
47 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
48 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
50 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
51 if (TM.getSubtargetImpl()->isDarwin())
52 return new TargetLoweringObjectFileMachO();
54 if (TM.getSubtargetImpl()->isSVR4ABI())
55 return new PPC64LinuxTargetObjectFile();
57 return new TargetLoweringObjectFileELF();
60 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
61 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
62 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
66 // Use _setjmp/_longjmp instead of setjmp/longjmp.
67 setUseUnderscoreSetJmp(true);
68 setUseUnderscoreLongJmp(true);
70 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
71 // arguments are at least 4/8 bytes aligned.
72 bool isPPC64 = Subtarget->isPPC64();
73 setMinStackArgumentAlignment(isPPC64 ? 8:4);
75 // Set up the register classes.
76 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
77 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
78 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
80 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
81 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
82 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
84 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
86 // PowerPC has pre-inc load and store's.
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
92 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
98 // This is used in the ppcf128->int sequence. Note it has different semantics
99 // from FP_ROUND: that rounds to nearest, this rounds to zero.
100 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
102 // We do not currently implement these libm ops for PowerPC.
103 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
104 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
105 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
106 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
107 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
108 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
110 // PowerPC has no SREM/UREM instructions
111 setOperationAction(ISD::SREM, MVT::i32, Expand);
112 setOperationAction(ISD::UREM, MVT::i32, Expand);
113 setOperationAction(ISD::SREM, MVT::i64, Expand);
114 setOperationAction(ISD::UREM, MVT::i64, Expand);
116 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
117 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
118 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
119 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
120 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
121 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
122 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
123 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
124 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
126 // We don't support sin/cos/sqrt/fmod/pow
127 setOperationAction(ISD::FSIN , MVT::f64, Expand);
128 setOperationAction(ISD::FCOS , MVT::f64, Expand);
129 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
130 setOperationAction(ISD::FREM , MVT::f64, Expand);
131 setOperationAction(ISD::FPOW , MVT::f64, Expand);
132 setOperationAction(ISD::FMA , MVT::f64, Legal);
133 setOperationAction(ISD::FSIN , MVT::f32, Expand);
134 setOperationAction(ISD::FCOS , MVT::f32, Expand);
135 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
136 setOperationAction(ISD::FREM , MVT::f32, Expand);
137 setOperationAction(ISD::FPOW , MVT::f32, Expand);
138 setOperationAction(ISD::FMA , MVT::f32, Legal);
140 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
142 // If we're enabling GP optimizations, use hardware square root
143 if (!Subtarget->hasFSQRT() &&
144 !(TM.Options.UnsafeFPMath &&
145 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
146 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
148 if (!Subtarget->hasFSQRT() &&
149 !(TM.Options.UnsafeFPMath &&
150 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
151 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
153 if (Subtarget->hasFCPSGN()) {
154 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
155 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
157 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
158 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
161 if (Subtarget->hasFPRND()) {
162 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
163 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
164 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
165 setOperationAction(ISD::FROUND, MVT::f64, Legal);
167 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
168 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
169 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
170 setOperationAction(ISD::FROUND, MVT::f32, Legal);
173 // PowerPC does not have BSWAP, CTPOP or CTTZ
174 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
175 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
176 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
177 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
178 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
179 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
180 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
181 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
183 if (Subtarget->hasPOPCNTD()) {
184 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
185 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
187 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
188 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
191 // PowerPC does not have ROTR
192 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
193 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
195 // PowerPC does not have Select
196 setOperationAction(ISD::SELECT, MVT::i32, Expand);
197 setOperationAction(ISD::SELECT, MVT::i64, Expand);
198 setOperationAction(ISD::SELECT, MVT::f32, Expand);
199 setOperationAction(ISD::SELECT, MVT::f64, Expand);
201 // PowerPC wants to turn select_cc of FP into fsel when possible.
202 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
203 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
205 // PowerPC wants to optimize integer setcc a bit
206 setOperationAction(ISD::SETCC, MVT::i32, Custom);
208 // PowerPC does not have BRCOND which requires SetCC
209 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
211 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
213 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
214 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
216 // PowerPC does not have [U|S]INT_TO_FP
217 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
218 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
220 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
221 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
222 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
223 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
225 // We cannot sextinreg(i1). Expand to shifts.
226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
228 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
229 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
230 // support continuation, user-level threading, and etc.. As a result, no
231 // other SjLj exception interfaces are implemented and please don't build
232 // your own exception handling based on them.
233 // LLVM/Clang supports zero-cost DWARF exception handling.
234 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
235 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
237 // We want to legalize GlobalAddress and ConstantPool nodes into the
238 // appropriate instructions to materialize the address.
239 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
240 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
241 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
242 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
243 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
244 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
245 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
246 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
247 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
248 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
251 setOperationAction(ISD::TRAP, MVT::Other, Legal);
253 // TRAMPOLINE is custom lowered.
254 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
255 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
257 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
258 setOperationAction(ISD::VASTART , MVT::Other, Custom);
260 if (Subtarget->isSVR4ABI()) {
262 // VAARG always uses double-word chunks, so promote anything smaller.
263 setOperationAction(ISD::VAARG, MVT::i1, Promote);
264 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
265 setOperationAction(ISD::VAARG, MVT::i8, Promote);
266 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
267 setOperationAction(ISD::VAARG, MVT::i16, Promote);
268 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
269 setOperationAction(ISD::VAARG, MVT::i32, Promote);
270 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
271 setOperationAction(ISD::VAARG, MVT::Other, Expand);
273 // VAARG is custom lowered with the 32-bit SVR4 ABI.
274 setOperationAction(ISD::VAARG, MVT::Other, Custom);
275 setOperationAction(ISD::VAARG, MVT::i64, Custom);
278 setOperationAction(ISD::VAARG, MVT::Other, Expand);
280 if (Subtarget->isSVR4ABI() && !isPPC64)
281 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
282 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
284 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
286 // Use the default implementation.
287 setOperationAction(ISD::VAEND , MVT::Other, Expand);
288 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
289 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
290 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
291 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
293 // We want to custom lower some of our intrinsics.
294 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
296 // To handle counter-based loop conditions.
297 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
299 // Comparisons that require checking two conditions.
300 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
301 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
302 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
303 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
304 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
305 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
306 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
311 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
313 if (Subtarget->has64BitSupport()) {
314 // They also have instructions for converting between i64 and fp.
315 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
316 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
317 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
318 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
319 // This is just the low 32 bits of a (signed) fp->i64 conversion.
320 // We cannot do this with Promote because i64 is not a legal type.
321 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
323 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
324 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
326 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
327 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
330 // With the instructions enabled under FPCVT, we can do everything.
331 if (PPCSubTarget.hasFPCVT()) {
332 if (Subtarget->has64BitSupport()) {
333 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
334 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
335 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
336 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
339 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
340 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
341 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
342 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
345 if (Subtarget->use64BitRegs()) {
346 // 64-bit PowerPC implementations can support i64 types directly
347 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
348 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
349 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
350 // 64-bit PowerPC wants to expand i128 shifts itself.
351 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
352 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
353 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
355 // 32-bit PowerPC wants to expand i64 shifts itself.
356 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
357 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
358 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
361 if (Subtarget->hasAltivec()) {
362 // First set operation action for all vector types to expand. Then we
363 // will selectively turn on ones that can be effectively codegen'd.
364 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
365 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
366 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
368 // add/sub are legal for all supported vector VT's.
369 setOperationAction(ISD::ADD , VT, Legal);
370 setOperationAction(ISD::SUB , VT, Legal);
372 // We promote all shuffles to v16i8.
373 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
374 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
376 // We promote all non-typed operations to v4i32.
377 setOperationAction(ISD::AND , VT, Promote);
378 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
379 setOperationAction(ISD::OR , VT, Promote);
380 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
381 setOperationAction(ISD::XOR , VT, Promote);
382 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
383 setOperationAction(ISD::LOAD , VT, Promote);
384 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
385 setOperationAction(ISD::SELECT, VT, Promote);
386 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
387 setOperationAction(ISD::STORE, VT, Promote);
388 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
390 // No other operations are legal.
391 setOperationAction(ISD::MUL , VT, Expand);
392 setOperationAction(ISD::SDIV, VT, Expand);
393 setOperationAction(ISD::SREM, VT, Expand);
394 setOperationAction(ISD::UDIV, VT, Expand);
395 setOperationAction(ISD::UREM, VT, Expand);
396 setOperationAction(ISD::FDIV, VT, Expand);
397 setOperationAction(ISD::FREM, VT, Expand);
398 setOperationAction(ISD::FNEG, VT, Expand);
399 setOperationAction(ISD::FSQRT, VT, Expand);
400 setOperationAction(ISD::FLOG, VT, Expand);
401 setOperationAction(ISD::FLOG10, VT, Expand);
402 setOperationAction(ISD::FLOG2, VT, Expand);
403 setOperationAction(ISD::FEXP, VT, Expand);
404 setOperationAction(ISD::FEXP2, VT, Expand);
405 setOperationAction(ISD::FSIN, VT, Expand);
406 setOperationAction(ISD::FCOS, VT, Expand);
407 setOperationAction(ISD::FABS, VT, Expand);
408 setOperationAction(ISD::FPOWI, VT, Expand);
409 setOperationAction(ISD::FFLOOR, VT, Expand);
410 setOperationAction(ISD::FCEIL, VT, Expand);
411 setOperationAction(ISD::FTRUNC, VT, Expand);
412 setOperationAction(ISD::FRINT, VT, Expand);
413 setOperationAction(ISD::FNEARBYINT, VT, Expand);
414 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
415 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
416 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
417 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
418 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419 setOperationAction(ISD::UDIVREM, VT, Expand);
420 setOperationAction(ISD::SDIVREM, VT, Expand);
421 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
422 setOperationAction(ISD::FPOW, VT, Expand);
423 setOperationAction(ISD::CTPOP, VT, Expand);
424 setOperationAction(ISD::CTLZ, VT, Expand);
425 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
426 setOperationAction(ISD::CTTZ, VT, Expand);
427 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
428 setOperationAction(ISD::VSELECT, VT, Expand);
429 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
431 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
432 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
433 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
434 setTruncStoreAction(VT, InnerVT, Expand);
436 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
437 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
438 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
441 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
442 // with merges, splats, etc.
443 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
445 setOperationAction(ISD::AND , MVT::v4i32, Legal);
446 setOperationAction(ISD::OR , MVT::v4i32, Legal);
447 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
448 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
449 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
450 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
451 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
452 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
453 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
454 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
455 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
456 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
457 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
458 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
460 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
461 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
462 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
463 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
465 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
466 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
468 if (TM.Options.UnsafeFPMath) {
469 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
470 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
473 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
474 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
475 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
477 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
478 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
480 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
481 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
482 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
483 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
485 // Altivec does not contain unordered floating-point compare instructions
486 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
487 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
488 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
489 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
490 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
491 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
493 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
494 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
497 if (Subtarget->has64BitSupport()) {
498 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
499 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
502 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
503 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
504 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
505 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
507 setBooleanContents(ZeroOrOneBooleanContent);
508 // Altivec instructions set fields to all zeros or all ones.
509 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
512 setStackPointerRegisterToSaveRestore(PPC::X1);
513 setExceptionPointerRegister(PPC::X3);
514 setExceptionSelectorRegister(PPC::X4);
516 setStackPointerRegisterToSaveRestore(PPC::R1);
517 setExceptionPointerRegister(PPC::R3);
518 setExceptionSelectorRegister(PPC::R4);
521 // We have target-specific dag combine patterns for the following nodes:
522 setTargetDAGCombine(ISD::SINT_TO_FP);
523 setTargetDAGCombine(ISD::LOAD);
524 setTargetDAGCombine(ISD::STORE);
525 setTargetDAGCombine(ISD::BR_CC);
526 setTargetDAGCombine(ISD::BSWAP);
527 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
529 // Use reciprocal estimates.
530 if (TM.Options.UnsafeFPMath) {
531 setTargetDAGCombine(ISD::FDIV);
532 setTargetDAGCombine(ISD::FSQRT);
535 // Darwin long double math library functions have $LDBL128 appended.
536 if (Subtarget->isDarwin()) {
537 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
538 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
539 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
540 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
541 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
542 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
543 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
544 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
545 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
546 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
549 setMinFunctionAlignment(2);
550 if (PPCSubTarget.isDarwin())
551 setPrefFunctionAlignment(4);
553 if (isPPC64 && Subtarget->isJITCodeModel())
554 // Temporary workaround for the inability of PPC64 JIT to handle jump
556 setSupportJumpTables(false);
558 setInsertFencesForAtomic(true);
560 if (Subtarget->enableMachineScheduler())
561 setSchedulingPreference(Sched::Source);
563 setSchedulingPreference(Sched::Hybrid);
565 computeRegisterProperties();
567 // The Freescale cores does better with aggressive inlining of memcpy and
568 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
569 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
570 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
571 MaxStoresPerMemset = 32;
572 MaxStoresPerMemsetOptSize = 16;
573 MaxStoresPerMemcpy = 32;
574 MaxStoresPerMemcpyOptSize = 8;
575 MaxStoresPerMemmove = 32;
576 MaxStoresPerMemmoveOptSize = 8;
578 setPrefFunctionAlignment(4);
582 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
583 /// the desired ByVal argument alignment.
584 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
585 unsigned MaxMaxAlign) {
586 if (MaxAlign == MaxMaxAlign)
588 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
589 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
591 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
593 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
594 unsigned EltAlign = 0;
595 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
596 if (EltAlign > MaxAlign)
598 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
599 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
600 unsigned EltAlign = 0;
601 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
602 if (EltAlign > MaxAlign)
604 if (MaxAlign == MaxMaxAlign)
610 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
611 /// function arguments in the caller parameter area.
612 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
613 // Darwin passes everything on 4 byte boundary.
614 if (PPCSubTarget.isDarwin())
617 // 16byte and wider vectors are passed on 16byte boundary.
618 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
619 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
620 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
621 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
625 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
628 case PPCISD::FSEL: return "PPCISD::FSEL";
629 case PPCISD::FCFID: return "PPCISD::FCFID";
630 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
631 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
632 case PPCISD::FRE: return "PPCISD::FRE";
633 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
634 case PPCISD::STFIWX: return "PPCISD::STFIWX";
635 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
636 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
637 case PPCISD::VPERM: return "PPCISD::VPERM";
638 case PPCISD::Hi: return "PPCISD::Hi";
639 case PPCISD::Lo: return "PPCISD::Lo";
640 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
641 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
642 case PPCISD::LOAD: return "PPCISD::LOAD";
643 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
644 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
645 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
646 case PPCISD::SRL: return "PPCISD::SRL";
647 case PPCISD::SRA: return "PPCISD::SRA";
648 case PPCISD::SHL: return "PPCISD::SHL";
649 case PPCISD::CALL: return "PPCISD::CALL";
650 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
651 case PPCISD::MTCTR: return "PPCISD::MTCTR";
652 case PPCISD::BCTRL: return "PPCISD::BCTRL";
653 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
654 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
655 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
656 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
657 case PPCISD::VCMP: return "PPCISD::VCMP";
658 case PPCISD::VCMPo: return "PPCISD::VCMPo";
659 case PPCISD::LBRX: return "PPCISD::LBRX";
660 case PPCISD::STBRX: return "PPCISD::STBRX";
661 case PPCISD::LARX: return "PPCISD::LARX";
662 case PPCISD::STCX: return "PPCISD::STCX";
663 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
664 case PPCISD::BDNZ: return "PPCISD::BDNZ";
665 case PPCISD::BDZ: return "PPCISD::BDZ";
666 case PPCISD::MFFS: return "PPCISD::MFFS";
667 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
668 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
669 case PPCISD::CR6SET: return "PPCISD::CR6SET";
670 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
671 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
672 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
673 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
674 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
675 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
676 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
677 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
678 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
679 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
680 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
681 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
682 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
683 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
684 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
685 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
686 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
687 case PPCISD::SC: return "PPCISD::SC";
691 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
694 return VT.changeVectorElementTypeToInteger();
697 //===----------------------------------------------------------------------===//
698 // Node matching predicates, for use by the tblgen matching code.
699 //===----------------------------------------------------------------------===//
701 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
702 static bool isFloatingPointZero(SDValue Op) {
703 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
704 return CFP->getValueAPF().isZero();
705 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
706 // Maybe this has already been legalized into the constant pool?
707 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
708 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
709 return CFP->getValueAPF().isZero();
714 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
715 /// true if Op is undef or if it matches the specified value.
716 static bool isConstantOrUndef(int Op, int Val) {
717 return Op < 0 || Op == Val;
720 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
721 /// VPKUHUM instruction.
722 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
724 for (unsigned i = 0; i != 16; ++i)
725 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
728 for (unsigned i = 0; i != 8; ++i)
729 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
730 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
736 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
737 /// VPKUWUM instruction.
738 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
740 for (unsigned i = 0; i != 16; i += 2)
741 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
742 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
745 for (unsigned i = 0; i != 8; i += 2)
746 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
747 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
748 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
749 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
755 /// isVMerge - Common function, used to match vmrg* shuffles.
757 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
758 unsigned LHSStart, unsigned RHSStart) {
759 assert(N->getValueType(0) == MVT::v16i8 &&
760 "PPC only supports shuffles by bytes!");
761 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
762 "Unsupported merge size!");
764 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
765 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
766 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
767 LHSStart+j+i*UnitSize) ||
768 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
769 RHSStart+j+i*UnitSize))
775 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
776 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
777 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
780 return isVMerge(N, UnitSize, 8, 24);
781 return isVMerge(N, UnitSize, 8, 8);
784 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
785 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
786 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
789 return isVMerge(N, UnitSize, 0, 16);
790 return isVMerge(N, UnitSize, 0, 0);
794 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
795 /// amount, otherwise return -1.
796 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
797 assert(N->getValueType(0) == MVT::v16i8 &&
798 "PPC only supports shuffles by bytes!");
800 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
802 // Find the first non-undef value in the shuffle mask.
804 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
807 if (i == 16) return -1; // all undef.
809 // Otherwise, check to see if the rest of the elements are consecutively
810 // numbered from this value.
811 unsigned ShiftAmt = SVOp->getMaskElt(i);
812 if (ShiftAmt < i) return -1;
816 // Check the rest of the elements to see if they are consecutive.
817 for (++i; i != 16; ++i)
818 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
821 // Check the rest of the elements to see if they are consecutive.
822 for (++i; i != 16; ++i)
823 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
829 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
830 /// specifies a splat of a single element that is suitable for input to
831 /// VSPLTB/VSPLTH/VSPLTW.
832 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
833 assert(N->getValueType(0) == MVT::v16i8 &&
834 (EltSize == 1 || EltSize == 2 || EltSize == 4));
836 // This is a splat operation if each element of the permute is the same, and
837 // if the value doesn't reference the second vector.
838 unsigned ElementBase = N->getMaskElt(0);
840 // FIXME: Handle UNDEF elements too!
841 if (ElementBase >= 16)
844 // Check that the indices are consecutive, in the case of a multi-byte element
845 // splatted with a v16i8 mask.
846 for (unsigned i = 1; i != EltSize; ++i)
847 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
850 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
851 if (N->getMaskElt(i) < 0) continue;
852 for (unsigned j = 0; j != EltSize; ++j)
853 if (N->getMaskElt(i+j) != N->getMaskElt(j))
859 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
861 bool PPC::isAllNegativeZeroVector(SDNode *N) {
862 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
864 APInt APVal, APUndef;
868 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
869 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
870 return CFP->getValueAPF().isNegZero();
875 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
876 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
877 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
878 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
879 assert(isSplatShuffleMask(SVOp, EltSize));
880 return SVOp->getMaskElt(0) / EltSize;
883 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
884 /// by using a vspltis[bhw] instruction of the specified element size, return
885 /// the constant being splatted. The ByteSize field indicates the number of
886 /// bytes of each element [124] -> [bhw].
887 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
890 // If ByteSize of the splat is bigger than the element size of the
891 // build_vector, then we have a case where we are checking for a splat where
892 // multiple elements of the buildvector are folded together into a single
893 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
894 unsigned EltSize = 16/N->getNumOperands();
895 if (EltSize < ByteSize) {
896 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
897 SDValue UniquedVals[4];
898 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
900 // See if all of the elements in the buildvector agree across.
901 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
902 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
903 // If the element isn't a constant, bail fully out.
904 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
907 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
908 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
909 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
910 return SDValue(); // no match.
913 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
914 // either constant or undef values that are identical for each chunk. See
915 // if these chunks can form into a larger vspltis*.
917 // Check to see if all of the leading entries are either 0 or -1. If
918 // neither, then this won't fit into the immediate field.
919 bool LeadingZero = true;
920 bool LeadingOnes = true;
921 for (unsigned i = 0; i != Multiple-1; ++i) {
922 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
924 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
925 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
927 // Finally, check the least significant entry.
929 if (UniquedVals[Multiple-1].getNode() == 0)
930 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
931 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
933 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
936 if (UniquedVals[Multiple-1].getNode() == 0)
937 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
938 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
939 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
940 return DAG.getTargetConstant(Val, MVT::i32);
946 // Check to see if this buildvec has a single non-undef value in its elements.
947 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
948 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
949 if (OpVal.getNode() == 0)
950 OpVal = N->getOperand(i);
951 else if (OpVal != N->getOperand(i))
955 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
957 unsigned ValSizeInBytes = EltSize;
959 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
960 Value = CN->getZExtValue();
961 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
962 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
963 Value = FloatToBits(CN->getValueAPF().convertToFloat());
966 // If the splat value is larger than the element value, then we can never do
967 // this splat. The only case that we could fit the replicated bits into our
968 // immediate field for would be zero, and we prefer to use vxor for it.
969 if (ValSizeInBytes < ByteSize) return SDValue();
971 // If the element value is larger than the splat value, cut it in half and
972 // check to see if the two halves are equal. Continue doing this until we
973 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
974 while (ValSizeInBytes > ByteSize) {
975 ValSizeInBytes >>= 1;
977 // If the top half equals the bottom half, we're still ok.
978 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
979 (Value & ((1 << (8*ValSizeInBytes))-1)))
983 // Properly sign extend the value.
984 int MaskVal = SignExtend32(Value, ByteSize * 8);
986 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
987 if (MaskVal == 0) return SDValue();
989 // Finally, if this value fits in a 5 bit sext field, return it
990 if (SignExtend32<5>(MaskVal) == MaskVal)
991 return DAG.getTargetConstant(MaskVal, MVT::i32);
995 //===----------------------------------------------------------------------===//
996 // Addressing Mode Selection
997 //===----------------------------------------------------------------------===//
999 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1000 /// or 64-bit immediate, and if the value can be accurately represented as a
1001 /// sign extension from a 16-bit value. If so, this returns true and the
1003 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1004 if (N->getOpcode() != ISD::Constant)
1007 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1008 if (N->getValueType(0) == MVT::i32)
1009 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1011 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1013 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1014 return isIntS16Immediate(Op.getNode(), Imm);
1018 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1019 /// can be represented as an indexed [r+r] operation. Returns false if it
1020 /// can be more efficiently represented with [r+imm].
1021 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1023 SelectionDAG &DAG) const {
1025 if (N.getOpcode() == ISD::ADD) {
1026 if (isIntS16Immediate(N.getOperand(1), imm))
1027 return false; // r+i
1028 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1029 return false; // r+i
1031 Base = N.getOperand(0);
1032 Index = N.getOperand(1);
1034 } else if (N.getOpcode() == ISD::OR) {
1035 if (isIntS16Immediate(N.getOperand(1), imm))
1036 return false; // r+i can fold it if we can.
1038 // If this is an or of disjoint bitfields, we can codegen this as an add
1039 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1041 APInt LHSKnownZero, LHSKnownOne;
1042 APInt RHSKnownZero, RHSKnownOne;
1043 DAG.ComputeMaskedBits(N.getOperand(0),
1044 LHSKnownZero, LHSKnownOne);
1046 if (LHSKnownZero.getBoolValue()) {
1047 DAG.ComputeMaskedBits(N.getOperand(1),
1048 RHSKnownZero, RHSKnownOne);
1049 // If all of the bits are known zero on the LHS or RHS, the add won't
1051 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1052 Base = N.getOperand(0);
1053 Index = N.getOperand(1);
1062 // If we happen to be doing an i64 load or store into a stack slot that has
1063 // less than a 4-byte alignment, then the frame-index elimination may need to
1064 // use an indexed load or store instruction (because the offset may not be a
1065 // multiple of 4). The extra register needed to hold the offset comes from the
1066 // register scavenger, and it is possible that the scavenger will need to use
1067 // an emergency spill slot. As a result, we need to make sure that a spill slot
1068 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1070 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1071 // FIXME: This does not handle the LWA case.
1075 // NOTE: We'll exclude negative FIs here, which come from argument
1076 // lowering, because there are no known test cases triggering this problem
1077 // using packed structures (or similar). We can remove this exclusion if
1078 // we find such a test case. The reason why this is so test-case driven is
1079 // because this entire 'fixup' is only to prevent crashes (from the
1080 // register scavenger) on not-really-valid inputs. For example, if we have:
1082 // %b = bitcast i1* %a to i64*
1083 // store i64* a, i64 b
1084 // then the store should really be marked as 'align 1', but is not. If it
1085 // were marked as 'align 1' then the indexed form would have been
1086 // instruction-selected initially, and the problem this 'fixup' is preventing
1087 // won't happen regardless.
1091 MachineFunction &MF = DAG.getMachineFunction();
1092 MachineFrameInfo *MFI = MF.getFrameInfo();
1094 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1098 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1099 FuncInfo->setHasNonRISpills();
1102 /// Returns true if the address N can be represented by a base register plus
1103 /// a signed 16-bit displacement [r+imm], and if it is not better
1104 /// represented as reg+reg. If Aligned is true, only accept displacements
1105 /// suitable for STD and friends, i.e. multiples of 4.
1106 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1109 bool Aligned) const {
1110 // FIXME dl should come from parent load or store, not from address
1112 // If this can be more profitably realized as r+r, fail.
1113 if (SelectAddressRegReg(N, Disp, Base, DAG))
1116 if (N.getOpcode() == ISD::ADD) {
1118 if (isIntS16Immediate(N.getOperand(1), imm) &&
1119 (!Aligned || (imm & 3) == 0)) {
1120 Disp = DAG.getTargetConstant(imm, N.getValueType());
1121 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1122 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1123 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1125 Base = N.getOperand(0);
1127 return true; // [r+i]
1128 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1129 // Match LOAD (ADD (X, Lo(G))).
1130 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1131 && "Cannot handle constant offsets yet!");
1132 Disp = N.getOperand(1).getOperand(0); // The global address.
1133 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1134 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1135 Disp.getOpcode() == ISD::TargetConstantPool ||
1136 Disp.getOpcode() == ISD::TargetJumpTable);
1137 Base = N.getOperand(0);
1138 return true; // [&g+r]
1140 } else if (N.getOpcode() == ISD::OR) {
1142 if (isIntS16Immediate(N.getOperand(1), imm) &&
1143 (!Aligned || (imm & 3) == 0)) {
1144 // If this is an or of disjoint bitfields, we can codegen this as an add
1145 // (for better address arithmetic) if the LHS and RHS of the OR are
1146 // provably disjoint.
1147 APInt LHSKnownZero, LHSKnownOne;
1148 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1150 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1151 // If all of the bits are known zero on the LHS or RHS, the add won't
1153 Base = N.getOperand(0);
1154 Disp = DAG.getTargetConstant(imm, N.getValueType());
1158 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1159 // Loading from a constant address.
1161 // If this address fits entirely in a 16-bit sext immediate field, codegen
1164 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1165 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1166 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1167 CN->getValueType(0));
1171 // Handle 32-bit sext immediates with LIS + addr mode.
1172 if ((CN->getValueType(0) == MVT::i32 ||
1173 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1174 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1175 int Addr = (int)CN->getZExtValue();
1177 // Otherwise, break this down into an LIS + disp.
1178 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1180 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1181 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1182 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1187 Disp = DAG.getTargetConstant(0, getPointerTy());
1188 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1189 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1190 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1193 return true; // [r+0]
1196 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1197 /// represented as an indexed [r+r] operation.
1198 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1200 SelectionDAG &DAG) const {
1201 // Check to see if we can easily represent this as an [r+r] address. This
1202 // will fail if it thinks that the address is more profitably represented as
1203 // reg+imm, e.g. where imm = 0.
1204 if (SelectAddressRegReg(N, Base, Index, DAG))
1207 // If the operand is an addition, always emit this as [r+r], since this is
1208 // better (for code size, and execution, as the memop does the add for free)
1209 // than emitting an explicit add.
1210 if (N.getOpcode() == ISD::ADD) {
1211 Base = N.getOperand(0);
1212 Index = N.getOperand(1);
1216 // Otherwise, do it the hard way, using R0 as the base register.
1217 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1223 /// getPreIndexedAddressParts - returns true by value, base pointer and
1224 /// offset pointer and addressing mode by reference if the node's address
1225 /// can be legally represented as pre-indexed load / store address.
1226 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1228 ISD::MemIndexedMode &AM,
1229 SelectionDAG &DAG) const {
1230 if (DisablePPCPreinc) return false;
1236 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1237 Ptr = LD->getBasePtr();
1238 VT = LD->getMemoryVT();
1239 Alignment = LD->getAlignment();
1240 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1241 Ptr = ST->getBasePtr();
1242 VT = ST->getMemoryVT();
1243 Alignment = ST->getAlignment();
1248 // PowerPC doesn't have preinc load/store instructions for vectors.
1252 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1254 // Common code will reject creating a pre-inc form if the base pointer
1255 // is a frame index, or if N is a store and the base pointer is either
1256 // the same as or a predecessor of the value being stored. Check for
1257 // those situations here, and try with swapped Base/Offset instead.
1260 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1263 SDValue Val = cast<StoreSDNode>(N)->getValue();
1264 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1269 std::swap(Base, Offset);
1275 // LDU/STU can only handle immediates that are a multiple of 4.
1276 if (VT != MVT::i64) {
1277 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1280 // LDU/STU need an address with at least 4-byte alignment.
1284 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1288 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1289 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1290 // sext i32 to i64 when addr mode is r+i.
1291 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1292 LD->getExtensionType() == ISD::SEXTLOAD &&
1293 isa<ConstantSDNode>(Offset))
1301 //===----------------------------------------------------------------------===//
1302 // LowerOperation implementation
1303 //===----------------------------------------------------------------------===//
1305 /// GetLabelAccessInfo - Return true if we should reference labels using a
1306 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1307 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1308 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1309 HiOpFlags = PPCII::MO_HA;
1310 LoOpFlags = PPCII::MO_LO;
1312 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1313 // non-darwin platform. We don't support PIC on other platforms yet.
1314 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1315 TM.getSubtarget<PPCSubtarget>().isDarwin();
1317 HiOpFlags |= PPCII::MO_PIC_FLAG;
1318 LoOpFlags |= PPCII::MO_PIC_FLAG;
1321 // If this is a reference to a global value that requires a non-lazy-ptr, make
1322 // sure that instruction lowering adds it.
1323 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1324 HiOpFlags |= PPCII::MO_NLP_FLAG;
1325 LoOpFlags |= PPCII::MO_NLP_FLAG;
1327 if (GV->hasHiddenVisibility()) {
1328 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1329 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1336 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1337 SelectionDAG &DAG) {
1338 EVT PtrVT = HiPart.getValueType();
1339 SDValue Zero = DAG.getConstant(0, PtrVT);
1342 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1343 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1345 // With PIC, the first instruction is actually "GR+hi(&G)".
1347 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1348 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1350 // Generate non-pic code that has direct accesses to the constant pool.
1351 // The address of the global is just (hi(&g)+lo(&g)).
1352 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1355 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1356 SelectionDAG &DAG) const {
1357 EVT PtrVT = Op.getValueType();
1358 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1359 const Constant *C = CP->getConstVal();
1361 // 64-bit SVR4 ABI code is always position-independent.
1362 // The actual address of the GlobalValue is stored in the TOC.
1363 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1364 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1365 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1366 DAG.getRegister(PPC::X2, MVT::i64));
1369 unsigned MOHiFlag, MOLoFlag;
1370 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1372 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1374 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1375 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1378 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1379 EVT PtrVT = Op.getValueType();
1380 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1382 // 64-bit SVR4 ABI code is always position-independent.
1383 // The actual address of the GlobalValue is stored in the TOC.
1384 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1385 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1386 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1387 DAG.getRegister(PPC::X2, MVT::i64));
1390 unsigned MOHiFlag, MOLoFlag;
1391 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1392 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1393 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1394 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1397 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1398 SelectionDAG &DAG) const {
1399 EVT PtrVT = Op.getValueType();
1401 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1403 unsigned MOHiFlag, MOLoFlag;
1404 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1405 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1406 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1407 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1410 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1411 SelectionDAG &DAG) const {
1413 // FIXME: TLS addresses currently use medium model code sequences,
1414 // which is the most useful form. Eventually support for small and
1415 // large models could be added if users need it, at the cost of
1416 // additional complexity.
1417 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1419 const GlobalValue *GV = GA->getGlobal();
1420 EVT PtrVT = getPointerTy();
1421 bool is64bit = PPCSubTarget.isPPC64();
1423 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1425 if (Model == TLSModel::LocalExec) {
1426 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1427 PPCII::MO_TPREL_HA);
1428 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1429 PPCII::MO_TPREL_LO);
1430 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1431 is64bit ? MVT::i64 : MVT::i32);
1432 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1433 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1436 if (Model == TLSModel::InitialExec) {
1437 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1438 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1442 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1443 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1444 PtrVT, GOTReg, TGA);
1446 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1447 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1448 PtrVT, TGA, GOTPtr);
1449 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1452 if (Model == TLSModel::GeneralDynamic) {
1453 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1454 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1455 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1457 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1460 // We need a chain node, and don't have one handy. The underlying
1461 // call has no side effects, so using the function entry node
1463 SDValue Chain = DAG.getEntryNode();
1464 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1465 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1466 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1467 PtrVT, ParmReg, TGA);
1468 // The return value from GET_TLS_ADDR really is in X3 already, but
1469 // some hacks are needed here to tie everything together. The extra
1470 // copies dissolve during subsequent transforms.
1471 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1472 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1475 if (Model == TLSModel::LocalDynamic) {
1476 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1477 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1478 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1480 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1483 // We need a chain node, and don't have one handy. The underlying
1484 // call has no side effects, so using the function entry node
1486 SDValue Chain = DAG.getEntryNode();
1487 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1488 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1489 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1490 PtrVT, ParmReg, TGA);
1491 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1492 // some hacks are needed here to tie everything together. The extra
1493 // copies dissolve during subsequent transforms.
1494 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1495 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1496 Chain, ParmReg, TGA);
1497 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1500 llvm_unreachable("Unknown TLS model!");
1503 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1504 SelectionDAG &DAG) const {
1505 EVT PtrVT = Op.getValueType();
1506 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1508 const GlobalValue *GV = GSDN->getGlobal();
1510 // 64-bit SVR4 ABI code is always position-independent.
1511 // The actual address of the GlobalValue is stored in the TOC.
1512 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1513 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1514 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1515 DAG.getRegister(PPC::X2, MVT::i64));
1518 unsigned MOHiFlag, MOLoFlag;
1519 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1522 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1524 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1526 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1528 // If the global reference is actually to a non-lazy-pointer, we have to do an
1529 // extra load to get the address of the global.
1530 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1531 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1532 false, false, false, 0);
1536 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1537 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1540 // If we're comparing for equality to zero, expose the fact that this is
1541 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1542 // fold the new nodes.
1543 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1544 if (C->isNullValue() && CC == ISD::SETEQ) {
1545 EVT VT = Op.getOperand(0).getValueType();
1546 SDValue Zext = Op.getOperand(0);
1547 if (VT.bitsLT(MVT::i32)) {
1549 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1551 unsigned Log2b = Log2_32(VT.getSizeInBits());
1552 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1553 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1554 DAG.getConstant(Log2b, MVT::i32));
1555 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1557 // Leave comparisons against 0 and -1 alone for now, since they're usually
1558 // optimized. FIXME: revisit this when we can custom lower all setcc
1560 if (C->isAllOnesValue() || C->isNullValue())
1564 // If we have an integer seteq/setne, turn it into a compare against zero
1565 // by xor'ing the rhs with the lhs, which is faster than setting a
1566 // condition register, reading it back out, and masking the correct bit. The
1567 // normal approach here uses sub to do this instead of xor. Using xor exposes
1568 // the result to other bit-twiddling opportunities.
1569 EVT LHSVT = Op.getOperand(0).getValueType();
1570 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1571 EVT VT = Op.getValueType();
1572 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1574 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1579 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1580 const PPCSubtarget &Subtarget) const {
1581 SDNode *Node = Op.getNode();
1582 EVT VT = Node->getValueType(0);
1583 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1584 SDValue InChain = Node->getOperand(0);
1585 SDValue VAListPtr = Node->getOperand(1);
1586 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1589 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1592 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1593 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1595 InChain = GprIndex.getValue(1);
1597 if (VT == MVT::i64) {
1598 // Check if GprIndex is even
1599 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1600 DAG.getConstant(1, MVT::i32));
1601 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1602 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1603 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1604 DAG.getConstant(1, MVT::i32));
1605 // Align GprIndex to be even if it isn't
1606 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1610 // fpr index is 1 byte after gpr
1611 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1612 DAG.getConstant(1, MVT::i32));
1615 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1616 FprPtr, MachinePointerInfo(SV), MVT::i8,
1618 InChain = FprIndex.getValue(1);
1620 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1621 DAG.getConstant(8, MVT::i32));
1623 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1624 DAG.getConstant(4, MVT::i32));
1627 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1628 MachinePointerInfo(), false, false,
1630 InChain = OverflowArea.getValue(1);
1632 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1633 MachinePointerInfo(), false, false,
1635 InChain = RegSaveArea.getValue(1);
1637 // select overflow_area if index > 8
1638 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1639 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1641 // adjustment constant gpr_index * 4/8
1642 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1643 VT.isInteger() ? GprIndex : FprIndex,
1644 DAG.getConstant(VT.isInteger() ? 4 : 8,
1647 // OurReg = RegSaveArea + RegConstant
1648 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1651 // Floating types are 32 bytes into RegSaveArea
1652 if (VT.isFloatingPoint())
1653 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1654 DAG.getConstant(32, MVT::i32));
1656 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1657 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1658 VT.isInteger() ? GprIndex : FprIndex,
1659 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1662 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1663 VT.isInteger() ? VAListPtr : FprPtr,
1664 MachinePointerInfo(SV),
1665 MVT::i8, false, false, 0);
1667 // determine if we should load from reg_save_area or overflow_area
1668 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1670 // increase overflow_area by 4/8 if gpr/fpr > 8
1671 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1672 DAG.getConstant(VT.isInteger() ? 4 : 8,
1675 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1678 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1680 MachinePointerInfo(),
1681 MVT::i32, false, false, 0);
1683 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1684 false, false, false, 0);
1687 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1688 const PPCSubtarget &Subtarget) const {
1689 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1691 // We have to copy the entire va_list struct:
1692 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1693 return DAG.getMemcpy(Op.getOperand(0), Op,
1694 Op.getOperand(1), Op.getOperand(2),
1695 DAG.getConstant(12, MVT::i32), 8, false, true,
1696 MachinePointerInfo(), MachinePointerInfo());
1699 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1700 SelectionDAG &DAG) const {
1701 return Op.getOperand(0);
1704 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1705 SelectionDAG &DAG) const {
1706 SDValue Chain = Op.getOperand(0);
1707 SDValue Trmp = Op.getOperand(1); // trampoline
1708 SDValue FPtr = Op.getOperand(2); // nested function
1709 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1712 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1713 bool isPPC64 = (PtrVT == MVT::i64);
1715 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1718 TargetLowering::ArgListTy Args;
1719 TargetLowering::ArgListEntry Entry;
1721 Entry.Ty = IntPtrTy;
1722 Entry.Node = Trmp; Args.push_back(Entry);
1724 // TrampSize == (isPPC64 ? 48 : 40);
1725 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1726 isPPC64 ? MVT::i64 : MVT::i32);
1727 Args.push_back(Entry);
1729 Entry.Node = FPtr; Args.push_back(Entry);
1730 Entry.Node = Nest; Args.push_back(Entry);
1732 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1733 TargetLowering::CallLoweringInfo CLI(Chain,
1734 Type::getVoidTy(*DAG.getContext()),
1735 false, false, false, false, 0,
1737 /*isTailCall=*/false,
1738 /*doesNotRet=*/false,
1739 /*isReturnValueUsed=*/true,
1740 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1742 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1744 return CallResult.second;
1747 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1748 const PPCSubtarget &Subtarget) const {
1749 MachineFunction &MF = DAG.getMachineFunction();
1750 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1754 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1755 // vastart just stores the address of the VarArgsFrameIndex slot into the
1756 // memory location argument.
1757 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1758 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1759 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1760 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1761 MachinePointerInfo(SV),
1765 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1766 // We suppose the given va_list is already allocated.
1769 // char gpr; /* index into the array of 8 GPRs
1770 // * stored in the register save area
1771 // * gpr=0 corresponds to r3,
1772 // * gpr=1 to r4, etc.
1774 // char fpr; /* index into the array of 8 FPRs
1775 // * stored in the register save area
1776 // * fpr=0 corresponds to f1,
1777 // * fpr=1 to f2, etc.
1779 // char *overflow_arg_area;
1780 // /* location on stack that holds
1781 // * the next overflow argument
1783 // char *reg_save_area;
1784 // /* where r3:r10 and f1:f8 (if saved)
1790 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1791 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1794 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1796 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1798 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1801 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1802 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1804 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1805 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1807 uint64_t FPROffset = 1;
1808 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1810 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1812 // Store first byte : number of int regs
1813 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1815 MachinePointerInfo(SV),
1816 MVT::i8, false, false, 0);
1817 uint64_t nextOffset = FPROffset;
1818 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1821 // Store second byte : number of float regs
1822 SDValue secondStore =
1823 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1824 MachinePointerInfo(SV, nextOffset), MVT::i8,
1826 nextOffset += StackOffset;
1827 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1829 // Store second word : arguments given on stack
1830 SDValue thirdStore =
1831 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1832 MachinePointerInfo(SV, nextOffset),
1834 nextOffset += FrameOffset;
1835 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1837 // Store third word : arguments given in registers
1838 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1839 MachinePointerInfo(SV, nextOffset),
1844 #include "PPCGenCallingConv.inc"
1846 // Function whose sole purpose is to kill compiler warnings
1847 // stemming from unused functions included from PPCGenCallingConv.inc.
1848 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
1849 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
1852 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1853 CCValAssign::LocInfo &LocInfo,
1854 ISD::ArgFlagsTy &ArgFlags,
1859 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1861 CCValAssign::LocInfo &LocInfo,
1862 ISD::ArgFlagsTy &ArgFlags,
1864 static const uint16_t ArgRegs[] = {
1865 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1866 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1868 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1870 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1872 // Skip one register if the first unallocated register has an even register
1873 // number and there are still argument registers available which have not been
1874 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1875 // need to skip a register if RegNum is odd.
1876 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1877 State.AllocateReg(ArgRegs[RegNum]);
1880 // Always return false here, as this function only makes sure that the first
1881 // unallocated register has an odd register number and does not actually
1882 // allocate a register for the current argument.
1886 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1888 CCValAssign::LocInfo &LocInfo,
1889 ISD::ArgFlagsTy &ArgFlags,
1891 static const uint16_t ArgRegs[] = {
1892 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1896 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1898 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1900 // If there is only one Floating-point register left we need to put both f64
1901 // values of a split ppc_fp128 value on the stack.
1902 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1903 State.AllocateReg(ArgRegs[RegNum]);
1906 // Always return false here, as this function only makes sure that the two f64
1907 // values a ppc_fp128 value is split into are both passed in registers or both
1908 // passed on the stack and does not actually allocate a register for the
1909 // current argument.
1913 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1915 static const uint16_t *GetFPR() {
1916 static const uint16_t FPR[] = {
1917 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1918 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1924 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1926 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1927 unsigned PtrByteSize) {
1928 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1929 if (Flags.isByVal())
1930 ArgSize = Flags.getByValSize();
1931 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1937 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1938 CallingConv::ID CallConv, bool isVarArg,
1939 const SmallVectorImpl<ISD::InputArg>
1941 SDLoc dl, SelectionDAG &DAG,
1942 SmallVectorImpl<SDValue> &InVals)
1944 if (PPCSubTarget.isSVR4ABI()) {
1945 if (PPCSubTarget.isPPC64())
1946 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1949 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1952 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1958 PPCTargetLowering::LowerFormalArguments_32SVR4(
1960 CallingConv::ID CallConv, bool isVarArg,
1961 const SmallVectorImpl<ISD::InputArg>
1963 SDLoc dl, SelectionDAG &DAG,
1964 SmallVectorImpl<SDValue> &InVals) const {
1966 // 32-bit SVR4 ABI Stack Frame Layout:
1967 // +-----------------------------------+
1968 // +--> | Back chain |
1969 // | +-----------------------------------+
1970 // | | Floating-point register save area |
1971 // | +-----------------------------------+
1972 // | | General register save area |
1973 // | +-----------------------------------+
1974 // | | CR save word |
1975 // | +-----------------------------------+
1976 // | | VRSAVE save word |
1977 // | +-----------------------------------+
1978 // | | Alignment padding |
1979 // | +-----------------------------------+
1980 // | | Vector register save area |
1981 // | +-----------------------------------+
1982 // | | Local variable space |
1983 // | +-----------------------------------+
1984 // | | Parameter list area |
1985 // | +-----------------------------------+
1986 // | | LR save word |
1987 // | +-----------------------------------+
1988 // SP--> +--- | Back chain |
1989 // +-----------------------------------+
1992 // System V Application Binary Interface PowerPC Processor Supplement
1993 // AltiVec Technology Programming Interface Manual
1995 MachineFunction &MF = DAG.getMachineFunction();
1996 MachineFrameInfo *MFI = MF.getFrameInfo();
1997 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1999 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2000 // Potential tail calls could cause overwriting of argument stack slots.
2001 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2002 (CallConv == CallingConv::Fast));
2003 unsigned PtrByteSize = 4;
2005 // Assign locations to all of the incoming arguments.
2006 SmallVector<CCValAssign, 16> ArgLocs;
2007 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2008 getTargetMachine(), ArgLocs, *DAG.getContext());
2010 // Reserve space for the linkage area on the stack.
2011 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2013 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2015 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2016 CCValAssign &VA = ArgLocs[i];
2018 // Arguments stored in registers.
2019 if (VA.isRegLoc()) {
2020 const TargetRegisterClass *RC;
2021 EVT ValVT = VA.getValVT();
2023 switch (ValVT.getSimpleVT().SimpleTy) {
2025 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2027 RC = &PPC::GPRCRegClass;
2030 RC = &PPC::F4RCRegClass;
2033 RC = &PPC::F8RCRegClass;
2039 RC = &PPC::VRRCRegClass;
2043 // Transform the arguments stored in physical registers into virtual ones.
2044 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2045 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
2047 InVals.push_back(ArgValue);
2049 // Argument stored in memory.
2050 assert(VA.isMemLoc());
2052 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
2053 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2056 // Create load nodes to retrieve arguments from the stack.
2057 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2058 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2059 MachinePointerInfo(),
2060 false, false, false, 0));
2064 // Assign locations to all of the incoming aggregate by value arguments.
2065 // Aggregates passed by value are stored in the local variable space of the
2066 // caller's stack frame, right above the parameter list area.
2067 SmallVector<CCValAssign, 16> ByValArgLocs;
2068 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2069 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2071 // Reserve stack space for the allocations in CCInfo.
2072 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2074 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2076 // Area that is at least reserved in the caller of this function.
2077 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2079 // Set the size that is at least reserved in caller of this function. Tail
2080 // call optimized function's reserved stack space needs to be aligned so that
2081 // taking the difference between two stack areas will result in an aligned
2083 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2086 std::max(MinReservedArea,
2087 PPCFrameLowering::getMinCallFrameSize(false, false));
2089 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2090 getStackAlignment();
2091 unsigned AlignMask = TargetAlign-1;
2092 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2094 FI->setMinReservedArea(MinReservedArea);
2096 SmallVector<SDValue, 8> MemOps;
2098 // If the function takes variable number of arguments, make a frame index for
2099 // the start of the first vararg value... for expansion of llvm.va_start.
2101 static const uint16_t GPArgRegs[] = {
2102 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2103 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2105 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2107 static const uint16_t FPArgRegs[] = {
2108 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2111 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2113 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2115 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2118 // Make room for NumGPArgRegs and NumFPArgRegs.
2119 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2120 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2122 FuncInfo->setVarArgsStackOffset(
2123 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2124 CCInfo.getNextStackOffset(), true));
2126 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2127 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2129 // The fixed integer arguments of a variadic function are stored to the
2130 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2131 // the result of va_next.
2132 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2133 // Get an existing live-in vreg, or add a new one.
2134 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2136 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2138 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2139 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2140 MachinePointerInfo(), false, false, 0);
2141 MemOps.push_back(Store);
2142 // Increment the address by four for the next argument to store
2143 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2144 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2147 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2149 // The double arguments are stored to the VarArgsFrameIndex
2151 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2152 // Get an existing live-in vreg, or add a new one.
2153 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2155 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2157 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2158 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2159 MachinePointerInfo(), false, false, 0);
2160 MemOps.push_back(Store);
2161 // Increment the address by eight for the next argument to store
2162 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2164 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2168 if (!MemOps.empty())
2169 Chain = DAG.getNode(ISD::TokenFactor, dl,
2170 MVT::Other, &MemOps[0], MemOps.size());
2175 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2176 // value to MVT::i64 and then truncate to the correct register size.
2178 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2179 SelectionDAG &DAG, SDValue ArgVal,
2182 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2183 DAG.getValueType(ObjectVT));
2184 else if (Flags.isZExt())
2185 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2186 DAG.getValueType(ObjectVT));
2188 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2191 // Set the size that is at least reserved in caller of this function. Tail
2192 // call optimized functions' reserved stack space needs to be aligned so that
2193 // taking the difference between two stack areas will result in an aligned
2196 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2197 unsigned nAltivecParamsAtEnd,
2198 unsigned MinReservedArea,
2199 bool isPPC64) const {
2200 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2201 // Add the Altivec parameters at the end, if needed.
2202 if (nAltivecParamsAtEnd) {
2203 MinReservedArea = ((MinReservedArea+15)/16)*16;
2204 MinReservedArea += 16*nAltivecParamsAtEnd;
2207 std::max(MinReservedArea,
2208 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2209 unsigned TargetAlign
2210 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2211 getStackAlignment();
2212 unsigned AlignMask = TargetAlign-1;
2213 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2214 FI->setMinReservedArea(MinReservedArea);
2218 PPCTargetLowering::LowerFormalArguments_64SVR4(
2220 CallingConv::ID CallConv, bool isVarArg,
2221 const SmallVectorImpl<ISD::InputArg>
2223 SDLoc dl, SelectionDAG &DAG,
2224 SmallVectorImpl<SDValue> &InVals) const {
2225 // TODO: add description of PPC stack frame format, or at least some docs.
2227 MachineFunction &MF = DAG.getMachineFunction();
2228 MachineFrameInfo *MFI = MF.getFrameInfo();
2229 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2231 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2232 // Potential tail calls could cause overwriting of argument stack slots.
2233 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2234 (CallConv == CallingConv::Fast));
2235 unsigned PtrByteSize = 8;
2237 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2238 // Area that is at least reserved in caller of this function.
2239 unsigned MinReservedArea = ArgOffset;
2241 static const uint16_t GPR[] = {
2242 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2243 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2246 static const uint16_t *FPR = GetFPR();
2248 static const uint16_t VR[] = {
2249 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2250 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2253 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2254 const unsigned Num_FPR_Regs = 13;
2255 const unsigned Num_VR_Regs = array_lengthof(VR);
2257 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2259 // Add DAG nodes to load the arguments or copy them out of registers. On
2260 // entry to a function on PPC, the arguments start after the linkage area,
2261 // although the first ones are often in registers.
2263 SmallVector<SDValue, 8> MemOps;
2264 unsigned nAltivecParamsAtEnd = 0;
2265 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2266 unsigned CurArgIdx = 0;
2267 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2269 bool needsLoad = false;
2270 EVT ObjectVT = Ins[ArgNo].VT;
2271 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2272 unsigned ArgSize = ObjSize;
2273 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2274 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2275 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2277 unsigned CurArgOffset = ArgOffset;
2279 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2280 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2281 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2283 MinReservedArea = ((MinReservedArea+15)/16)*16;
2284 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2288 nAltivecParamsAtEnd++;
2290 // Calculate min reserved area.
2291 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2295 // FIXME the codegen can be much improved in some cases.
2296 // We do not have to keep everything in memory.
2297 if (Flags.isByVal()) {
2298 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2299 ObjSize = Flags.getByValSize();
2300 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2301 // Empty aggregate parameters do not take up registers. Examples:
2305 // etc. However, we have to provide a place-holder in InVals, so
2306 // pretend we have an 8-byte item at the current address for that
2309 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2310 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2311 InVals.push_back(FIN);
2315 unsigned BVAlign = Flags.getByValAlign();
2317 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2318 CurArgOffset = ArgOffset;
2321 // All aggregates smaller than 8 bytes must be passed right-justified.
2322 if (ObjSize < PtrByteSize)
2323 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2324 // The value of the object is its address.
2325 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2326 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2327 InVals.push_back(FIN);
2330 if (GPR_idx != Num_GPR_Regs) {
2331 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2332 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2335 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2336 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2337 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2338 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2339 MachinePointerInfo(FuncArg, CurArgOffset),
2340 ObjType, false, false, 0);
2342 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2343 // store the whole register as-is to the parameter save area
2344 // slot. The address of the parameter was already calculated
2345 // above (InVals.push_back(FIN)) to be the right-justified
2346 // offset within the slot. For this store, we need a new
2347 // frame index that points at the beginning of the slot.
2348 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2349 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2350 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2351 MachinePointerInfo(FuncArg, ArgOffset),
2355 MemOps.push_back(Store);
2358 // Whether we copied from a register or not, advance the offset
2359 // into the parameter save area by a full doubleword.
2360 ArgOffset += PtrByteSize;
2364 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2365 // Store whatever pieces of the object are in registers
2366 // to memory. ArgOffset will be the address of the beginning
2368 if (GPR_idx != Num_GPR_Regs) {
2370 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2371 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2372 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2373 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2374 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2375 MachinePointerInfo(FuncArg, ArgOffset),
2377 MemOps.push_back(Store);
2379 ArgOffset += PtrByteSize;
2381 ArgOffset += ArgSize - j;
2388 switch (ObjectVT.getSimpleVT().SimpleTy) {
2389 default: llvm_unreachable("Unhandled argument type!");
2392 if (GPR_idx != Num_GPR_Regs) {
2393 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2394 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2396 if (ObjectVT == MVT::i32)
2397 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2398 // value to MVT::i64 and then truncate to the correct register size.
2399 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2404 ArgSize = PtrByteSize;
2411 // Every 8 bytes of argument space consumes one of the GPRs available for
2412 // argument passing.
2413 if (GPR_idx != Num_GPR_Regs) {
2416 if (FPR_idx != Num_FPR_Regs) {
2419 if (ObjectVT == MVT::f32)
2420 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2422 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2424 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2428 ArgSize = PtrByteSize;
2437 // Note that vector arguments in registers don't reserve stack space,
2438 // except in varargs functions.
2439 if (VR_idx != Num_VR_Regs) {
2440 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2441 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2443 while ((ArgOffset % 16) != 0) {
2444 ArgOffset += PtrByteSize;
2445 if (GPR_idx != Num_GPR_Regs)
2449 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2453 // Vectors are aligned.
2454 ArgOffset = ((ArgOffset+15)/16)*16;
2455 CurArgOffset = ArgOffset;
2462 // We need to load the argument to a virtual register if we determined
2463 // above that we ran out of physical registers of the appropriate type.
2465 int FI = MFI->CreateFixedObject(ObjSize,
2466 CurArgOffset + (ArgSize - ObjSize),
2468 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2469 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2470 false, false, false, 0);
2473 InVals.push_back(ArgVal);
2476 // Set the size that is at least reserved in caller of this function. Tail
2477 // call optimized functions' reserved stack space needs to be aligned so that
2478 // taking the difference between two stack areas will result in an aligned
2480 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2482 // If the function takes variable number of arguments, make a frame index for
2483 // the start of the first vararg value... for expansion of llvm.va_start.
2485 int Depth = ArgOffset;
2487 FuncInfo->setVarArgsFrameIndex(
2488 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2489 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2491 // If this function is vararg, store any remaining integer argument regs
2492 // to their spots on the stack so that they may be loaded by deferencing the
2493 // result of va_next.
2494 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2495 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2496 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2497 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2498 MachinePointerInfo(), false, false, 0);
2499 MemOps.push_back(Store);
2500 // Increment the address by four for the next argument to store
2501 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2502 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2506 if (!MemOps.empty())
2507 Chain = DAG.getNode(ISD::TokenFactor, dl,
2508 MVT::Other, &MemOps[0], MemOps.size());
2514 PPCTargetLowering::LowerFormalArguments_Darwin(
2516 CallingConv::ID CallConv, bool isVarArg,
2517 const SmallVectorImpl<ISD::InputArg>
2519 SDLoc dl, SelectionDAG &DAG,
2520 SmallVectorImpl<SDValue> &InVals) const {
2521 // TODO: add description of PPC stack frame format, or at least some docs.
2523 MachineFunction &MF = DAG.getMachineFunction();
2524 MachineFrameInfo *MFI = MF.getFrameInfo();
2525 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2527 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2528 bool isPPC64 = PtrVT == MVT::i64;
2529 // Potential tail calls could cause overwriting of argument stack slots.
2530 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2531 (CallConv == CallingConv::Fast));
2532 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2534 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2535 // Area that is at least reserved in caller of this function.
2536 unsigned MinReservedArea = ArgOffset;
2538 static const uint16_t GPR_32[] = { // 32-bit registers.
2539 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2540 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2542 static const uint16_t GPR_64[] = { // 64-bit registers.
2543 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2544 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2547 static const uint16_t *FPR = GetFPR();
2549 static const uint16_t VR[] = {
2550 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2551 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2554 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2555 const unsigned Num_FPR_Regs = 13;
2556 const unsigned Num_VR_Regs = array_lengthof( VR);
2558 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2560 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2562 // In 32-bit non-varargs functions, the stack space for vectors is after the
2563 // stack space for non-vectors. We do not use this space unless we have
2564 // too many vectors to fit in registers, something that only occurs in
2565 // constructed examples:), but we have to walk the arglist to figure
2566 // that out...for the pathological case, compute VecArgOffset as the
2567 // start of the vector parameter area. Computing VecArgOffset is the
2568 // entire point of the following loop.
2569 unsigned VecArgOffset = ArgOffset;
2570 if (!isVarArg && !isPPC64) {
2571 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2573 EVT ObjectVT = Ins[ArgNo].VT;
2574 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2576 if (Flags.isByVal()) {
2577 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2578 unsigned ObjSize = Flags.getByValSize();
2580 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2581 VecArgOffset += ArgSize;
2585 switch(ObjectVT.getSimpleVT().SimpleTy) {
2586 default: llvm_unreachable("Unhandled argument type!");
2591 case MVT::i64: // PPC64
2593 // FIXME: We are guaranteed to be !isPPC64 at this point.
2594 // Does MVT::i64 apply?
2601 // Nothing to do, we're only looking at Nonvector args here.
2606 // We've found where the vector parameter area in memory is. Skip the
2607 // first 12 parameters; these don't use that memory.
2608 VecArgOffset = ((VecArgOffset+15)/16)*16;
2609 VecArgOffset += 12*16;
2611 // Add DAG nodes to load the arguments or copy them out of registers. On
2612 // entry to a function on PPC, the arguments start after the linkage area,
2613 // although the first ones are often in registers.
2615 SmallVector<SDValue, 8> MemOps;
2616 unsigned nAltivecParamsAtEnd = 0;
2617 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2618 unsigned CurArgIdx = 0;
2619 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2621 bool needsLoad = false;
2622 EVT ObjectVT = Ins[ArgNo].VT;
2623 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2624 unsigned ArgSize = ObjSize;
2625 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2626 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2627 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2629 unsigned CurArgOffset = ArgOffset;
2631 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2632 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2633 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2634 if (isVarArg || isPPC64) {
2635 MinReservedArea = ((MinReservedArea+15)/16)*16;
2636 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2639 } else nAltivecParamsAtEnd++;
2641 // Calculate min reserved area.
2642 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2646 // FIXME the codegen can be much improved in some cases.
2647 // We do not have to keep everything in memory.
2648 if (Flags.isByVal()) {
2649 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2650 ObjSize = Flags.getByValSize();
2651 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2652 // Objects of size 1 and 2 are right justified, everything else is
2653 // left justified. This means the memory address is adjusted forwards.
2654 if (ObjSize==1 || ObjSize==2) {
2655 CurArgOffset = CurArgOffset + (4 - ObjSize);
2657 // The value of the object is its address.
2658 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2659 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2660 InVals.push_back(FIN);
2661 if (ObjSize==1 || ObjSize==2) {
2662 if (GPR_idx != Num_GPR_Regs) {
2665 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2667 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2668 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2669 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2670 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2671 MachinePointerInfo(FuncArg,
2673 ObjType, false, false, 0);
2674 MemOps.push_back(Store);
2678 ArgOffset += PtrByteSize;
2682 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2683 // Store whatever pieces of the object are in registers
2684 // to memory. ArgOffset will be the address of the beginning
2686 if (GPR_idx != Num_GPR_Regs) {
2689 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2691 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2692 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2693 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2694 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2695 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2696 MachinePointerInfo(FuncArg, ArgOffset),
2698 MemOps.push_back(Store);
2700 ArgOffset += PtrByteSize;
2702 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2709 switch (ObjectVT.getSimpleVT().SimpleTy) {
2710 default: llvm_unreachable("Unhandled argument type!");
2713 if (GPR_idx != Num_GPR_Regs) {
2714 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2715 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2719 ArgSize = PtrByteSize;
2721 // All int arguments reserve stack space in the Darwin ABI.
2722 ArgOffset += PtrByteSize;
2726 case MVT::i64: // PPC64
2727 if (GPR_idx != Num_GPR_Regs) {
2728 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2729 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2731 if (ObjectVT == MVT::i32)
2732 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2733 // value to MVT::i64 and then truncate to the correct register size.
2734 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2739 ArgSize = PtrByteSize;
2741 // All int arguments reserve stack space in the Darwin ABI.
2747 // Every 4 bytes of argument space consumes one of the GPRs available for
2748 // argument passing.
2749 if (GPR_idx != Num_GPR_Regs) {
2751 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2754 if (FPR_idx != Num_FPR_Regs) {
2757 if (ObjectVT == MVT::f32)
2758 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2760 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2762 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2768 // All FP arguments reserve stack space in the Darwin ABI.
2769 ArgOffset += isPPC64 ? 8 : ObjSize;
2775 // Note that vector arguments in registers don't reserve stack space,
2776 // except in varargs functions.
2777 if (VR_idx != Num_VR_Regs) {
2778 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2779 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2781 while ((ArgOffset % 16) != 0) {
2782 ArgOffset += PtrByteSize;
2783 if (GPR_idx != Num_GPR_Regs)
2787 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2791 if (!isVarArg && !isPPC64) {
2792 // Vectors go after all the nonvectors.
2793 CurArgOffset = VecArgOffset;
2796 // Vectors are aligned.
2797 ArgOffset = ((ArgOffset+15)/16)*16;
2798 CurArgOffset = ArgOffset;
2806 // We need to load the argument to a virtual register if we determined above
2807 // that we ran out of physical registers of the appropriate type.
2809 int FI = MFI->CreateFixedObject(ObjSize,
2810 CurArgOffset + (ArgSize - ObjSize),
2812 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2813 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2814 false, false, false, 0);
2817 InVals.push_back(ArgVal);
2820 // Set the size that is at least reserved in caller of this function. Tail
2821 // call optimized functions' reserved stack space needs to be aligned so that
2822 // taking the difference between two stack areas will result in an aligned
2824 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2826 // If the function takes variable number of arguments, make a frame index for
2827 // the start of the first vararg value... for expansion of llvm.va_start.
2829 int Depth = ArgOffset;
2831 FuncInfo->setVarArgsFrameIndex(
2832 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2834 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2836 // If this function is vararg, store any remaining integer argument regs
2837 // to their spots on the stack so that they may be loaded by deferencing the
2838 // result of va_next.
2839 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2843 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2845 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2847 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2848 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2849 MachinePointerInfo(), false, false, 0);
2850 MemOps.push_back(Store);
2851 // Increment the address by four for the next argument to store
2852 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2853 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2857 if (!MemOps.empty())
2858 Chain = DAG.getNode(ISD::TokenFactor, dl,
2859 MVT::Other, &MemOps[0], MemOps.size());
2864 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2865 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2867 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2871 const SmallVectorImpl<ISD::OutputArg>
2873 const SmallVectorImpl<SDValue> &OutVals,
2874 unsigned &nAltivecParamsAtEnd) {
2875 // Count how many bytes are to be pushed on the stack, including the linkage
2876 // area, and parameter passing area. We start with 24/48 bytes, which is
2877 // prereserved space for [SP][CR][LR][3 x unused].
2878 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2879 unsigned NumOps = Outs.size();
2880 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2882 // Add up all the space actually used.
2883 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2884 // they all go in registers, but we must reserve stack space for them for
2885 // possible use by the caller. In varargs or 64-bit calls, parameters are
2886 // assigned stack space in order, with padding so Altivec parameters are
2888 nAltivecParamsAtEnd = 0;
2889 for (unsigned i = 0; i != NumOps; ++i) {
2890 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2891 EVT ArgVT = Outs[i].VT;
2892 // Varargs Altivec parameters are padded to a 16 byte boundary.
2893 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2894 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2895 if (!isVarArg && !isPPC64) {
2896 // Non-varargs Altivec parameters go after all the non-Altivec
2897 // parameters; handle those later so we know how much padding we need.
2898 nAltivecParamsAtEnd++;
2901 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2902 NumBytes = ((NumBytes+15)/16)*16;
2904 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2907 // Allow for Altivec parameters at the end, if needed.
2908 if (nAltivecParamsAtEnd) {
2909 NumBytes = ((NumBytes+15)/16)*16;
2910 NumBytes += 16*nAltivecParamsAtEnd;
2913 // The prolog code of the callee may store up to 8 GPR argument registers to
2914 // the stack, allowing va_start to index over them in memory if its varargs.
2915 // Because we cannot tell if this is needed on the caller side, we have to
2916 // conservatively assume that it is needed. As such, make sure we have at
2917 // least enough stack space for the caller to store the 8 GPRs.
2918 NumBytes = std::max(NumBytes,
2919 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2921 // Tail call needs the stack to be aligned.
2922 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2923 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2924 getFrameLowering()->getStackAlignment();
2925 unsigned AlignMask = TargetAlign-1;
2926 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2932 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2933 /// adjusted to accommodate the arguments for the tailcall.
2934 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2935 unsigned ParamSize) {
2937 if (!isTailCall) return 0;
2939 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2940 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2941 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2942 // Remember only if the new adjustement is bigger.
2943 if (SPDiff < FI->getTailCallSPDelta())
2944 FI->setTailCallSPDelta(SPDiff);
2949 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2950 /// for tail call optimization. Targets which want to do tail call
2951 /// optimization should implement this function.
2953 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2954 CallingConv::ID CalleeCC,
2956 const SmallVectorImpl<ISD::InputArg> &Ins,
2957 SelectionDAG& DAG) const {
2958 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2961 // Variable argument functions are not supported.
2965 MachineFunction &MF = DAG.getMachineFunction();
2966 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2967 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2968 // Functions containing by val parameters are not supported.
2969 for (unsigned i = 0; i != Ins.size(); i++) {
2970 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2971 if (Flags.isByVal()) return false;
2974 // Non-PIC/GOT tail calls are supported.
2975 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2978 // At the moment we can only do local tail calls (in same module, hidden
2979 // or protected) if we are generating PIC.
2980 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2981 return G->getGlobal()->hasHiddenVisibility()
2982 || G->getGlobal()->hasProtectedVisibility();
2988 /// isCallCompatibleAddress - Return the immediate to use if the specified
2989 /// 32-bit value is representable in the immediate field of a BxA instruction.
2990 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2991 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2994 int Addr = C->getZExtValue();
2995 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2996 SignExtend32<26>(Addr) != Addr)
2997 return 0; // Top 6 bits have to be sext of immediate.
2999 return DAG.getConstant((int)C->getZExtValue() >> 2,
3000 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3005 struct TailCallArgumentInfo {
3010 TailCallArgumentInfo() : FrameIdx(0) {}
3015 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3017 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3019 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3020 SmallVectorImpl<SDValue> &MemOpChains,
3022 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3023 SDValue Arg = TailCallArgs[i].Arg;
3024 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3025 int FI = TailCallArgs[i].FrameIdx;
3026 // Store relative to framepointer.
3027 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3028 MachinePointerInfo::getFixedStack(FI),
3033 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3034 /// the appropriate stack slot for the tail call optimized function call.
3035 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3036 MachineFunction &MF,
3045 // Calculate the new stack slot for the return address.
3046 int SlotSize = isPPC64 ? 8 : 4;
3047 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3049 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3050 NewRetAddrLoc, true);
3051 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3052 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3053 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3054 MachinePointerInfo::getFixedStack(NewRetAddr),
3057 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3058 // slot as the FP is never overwritten.
3061 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3062 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3064 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3065 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3066 MachinePointerInfo::getFixedStack(NewFPIdx),
3073 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3074 /// the position of the argument.
3076 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3077 SDValue Arg, int SPDiff, unsigned ArgOffset,
3078 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3079 int Offset = ArgOffset + SPDiff;
3080 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3081 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3082 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3083 SDValue FIN = DAG.getFrameIndex(FI, VT);
3084 TailCallArgumentInfo Info;
3086 Info.FrameIdxOp = FIN;
3088 TailCallArguments.push_back(Info);
3091 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3092 /// stack slot. Returns the chain as result and the loaded frame pointers in
3093 /// LROpOut/FPOpout. Used when tail calling.
3094 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3102 // Load the LR and FP stack slot for later adjusting.
3103 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3104 LROpOut = getReturnAddrFrameIndex(DAG);
3105 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3106 false, false, false, 0);
3107 Chain = SDValue(LROpOut.getNode(), 1);
3109 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3110 // slot as the FP is never overwritten.
3112 FPOpOut = getFramePointerFrameIndex(DAG);
3113 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3114 false, false, false, 0);
3115 Chain = SDValue(FPOpOut.getNode(), 1);
3121 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3122 /// by "Src" to address "Dst" of size "Size". Alignment information is
3123 /// specified by the specific parameter attribute. The copy will be passed as
3124 /// a byval function parameter.
3125 /// Sometimes what we are copying is the end of a larger object, the part that
3126 /// does not fit in registers.
3128 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3129 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3131 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3132 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3133 false, false, MachinePointerInfo(0),
3134 MachinePointerInfo(0));
3137 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3140 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3141 SDValue Arg, SDValue PtrOff, int SPDiff,
3142 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3143 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3144 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3146 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3151 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3153 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3154 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3155 DAG.getConstant(ArgOffset, PtrVT));
3157 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3158 MachinePointerInfo(), false, false, 0));
3159 // Calculate and remember argument location.
3160 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3165 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3166 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3167 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3168 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3169 MachineFunction &MF = DAG.getMachineFunction();
3171 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3172 // might overwrite each other in case of tail call optimization.
3173 SmallVector<SDValue, 8> MemOpChains2;
3174 // Do not flag preceding copytoreg stuff together with the following stuff.
3176 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3178 if (!MemOpChains2.empty())
3179 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3180 &MemOpChains2[0], MemOpChains2.size());
3182 // Store the return address to the appropriate stack slot.
3183 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3184 isPPC64, isDarwinABI, dl);
3186 // Emit callseq_end just before tailcall node.
3187 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3188 DAG.getIntPtrConstant(0, true), InFlag, dl);
3189 InFlag = Chain.getValue(1);
3193 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3194 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3195 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3196 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3197 const PPCSubtarget &PPCSubTarget) {
3199 bool isPPC64 = PPCSubTarget.isPPC64();
3200 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3202 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3203 NodeTys.push_back(MVT::Other); // Returns a chain
3204 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3206 unsigned CallOpc = PPCISD::CALL;
3208 bool needIndirectCall = true;
3209 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3210 // If this is an absolute destination address, use the munged value.
3211 Callee = SDValue(Dest, 0);
3212 needIndirectCall = false;
3215 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3216 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3217 // Use indirect calls for ALL functions calls in JIT mode, since the
3218 // far-call stubs may be outside relocation limits for a BL instruction.
3219 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3220 unsigned OpFlags = 0;
3221 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3222 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3223 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3224 (G->getGlobal()->isDeclaration() ||
3225 G->getGlobal()->isWeakForLinker())) {
3226 // PC-relative references to external symbols should go through $stub,
3227 // unless we're building with the leopard linker or later, which
3228 // automatically synthesizes these stubs.
3229 OpFlags = PPCII::MO_DARWIN_STUB;
3232 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3233 // every direct call is) turn it into a TargetGlobalAddress /
3234 // TargetExternalSymbol node so that legalize doesn't hack it.
3235 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3236 Callee.getValueType(),
3238 needIndirectCall = false;
3242 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3243 unsigned char OpFlags = 0;
3245 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3246 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3247 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3248 // PC-relative references to external symbols should go through $stub,
3249 // unless we're building with the leopard linker or later, which
3250 // automatically synthesizes these stubs.
3251 OpFlags = PPCII::MO_DARWIN_STUB;
3254 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3256 needIndirectCall = false;
3259 if (needIndirectCall) {
3260 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3261 // to do the call, we can't use PPCISD::CALL.
3262 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3264 if (isSVR4ABI && isPPC64) {
3265 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3266 // entry point, but to the function descriptor (the function entry point
3267 // address is part of the function descriptor though).
3268 // The function descriptor is a three doubleword structure with the
3269 // following fields: function entry point, TOC base address and
3270 // environment pointer.
3271 // Thus for a call through a function pointer, the following actions need
3273 // 1. Save the TOC of the caller in the TOC save area of its stack
3274 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3275 // 2. Load the address of the function entry point from the function
3277 // 3. Load the TOC of the callee from the function descriptor into r2.
3278 // 4. Load the environment pointer from the function descriptor into
3280 // 5. Branch to the function entry point address.
3281 // 6. On return of the callee, the TOC of the caller needs to be
3282 // restored (this is done in FinishCall()).
3284 // All those operations are flagged together to ensure that no other
3285 // operations can be scheduled in between. E.g. without flagging the
3286 // operations together, a TOC access in the caller could be scheduled
3287 // between the load of the callee TOC and the branch to the callee, which
3288 // results in the TOC access going through the TOC of the callee instead
3289 // of going through the TOC of the caller, which leads to incorrect code.
3291 // Load the address of the function entry point from the function
3293 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3294 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3295 InFlag.getNode() ? 3 : 2);
3296 Chain = LoadFuncPtr.getValue(1);
3297 InFlag = LoadFuncPtr.getValue(2);
3299 // Load environment pointer into r11.
3300 // Offset of the environment pointer within the function descriptor.
3301 SDValue PtrOff = DAG.getIntPtrConstant(16);
3303 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3304 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3306 Chain = LoadEnvPtr.getValue(1);
3307 InFlag = LoadEnvPtr.getValue(2);
3309 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3311 Chain = EnvVal.getValue(0);
3312 InFlag = EnvVal.getValue(1);
3314 // Load TOC of the callee into r2. We are using a target-specific load
3315 // with r2 hard coded, because the result of a target-independent load
3316 // would never go directly into r2, since r2 is a reserved register (which
3317 // prevents the register allocator from allocating it), resulting in an
3318 // additional register being allocated and an unnecessary move instruction
3320 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3321 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3323 Chain = LoadTOCPtr.getValue(0);
3324 InFlag = LoadTOCPtr.getValue(1);
3326 MTCTROps[0] = Chain;
3327 MTCTROps[1] = LoadFuncPtr;
3328 MTCTROps[2] = InFlag;
3331 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3332 2 + (InFlag.getNode() != 0));
3333 InFlag = Chain.getValue(1);
3336 NodeTys.push_back(MVT::Other);
3337 NodeTys.push_back(MVT::Glue);
3338 Ops.push_back(Chain);
3339 CallOpc = PPCISD::BCTRL;
3341 // Add use of X11 (holding environment pointer)
3342 if (isSVR4ABI && isPPC64)
3343 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3344 // Add CTR register as callee so a bctr can be emitted later.
3346 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3349 // If this is a direct call, pass the chain and the callee.
3350 if (Callee.getNode()) {
3351 Ops.push_back(Chain);
3352 Ops.push_back(Callee);
3354 // If this is a tail call add stack pointer delta.
3356 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3358 // Add argument registers to the end of the list so that they are known live
3360 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3361 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3362 RegsToPass[i].second.getValueType()));
3368 bool isLocalCall(const SDValue &Callee)
3370 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3371 return !G->getGlobal()->isDeclaration() &&
3372 !G->getGlobal()->isWeakForLinker();
3377 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3378 CallingConv::ID CallConv, bool isVarArg,
3379 const SmallVectorImpl<ISD::InputArg> &Ins,
3380 SDLoc dl, SelectionDAG &DAG,
3381 SmallVectorImpl<SDValue> &InVals) const {
3383 SmallVector<CCValAssign, 16> RVLocs;
3384 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3385 getTargetMachine(), RVLocs, *DAG.getContext());
3386 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3388 // Copy all of the result registers out of their specified physreg.
3389 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3390 CCValAssign &VA = RVLocs[i];
3391 assert(VA.isRegLoc() && "Can only return in registers!");
3393 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3394 VA.getLocReg(), VA.getLocVT(), InFlag);
3395 Chain = Val.getValue(1);
3396 InFlag = Val.getValue(2);
3398 switch (VA.getLocInfo()) {
3399 default: llvm_unreachable("Unknown loc info!");
3400 case CCValAssign::Full: break;
3401 case CCValAssign::AExt:
3402 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3404 case CCValAssign::ZExt:
3405 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3406 DAG.getValueType(VA.getValVT()));
3407 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3409 case CCValAssign::SExt:
3410 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3411 DAG.getValueType(VA.getValVT()));
3412 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3416 InVals.push_back(Val);
3423 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3424 bool isTailCall, bool isVarArg,
3426 SmallVector<std::pair<unsigned, SDValue>, 8>
3428 SDValue InFlag, SDValue Chain,
3430 int SPDiff, unsigned NumBytes,
3431 const SmallVectorImpl<ISD::InputArg> &Ins,
3432 SmallVectorImpl<SDValue> &InVals) const {
3433 std::vector<EVT> NodeTys;
3434 SmallVector<SDValue, 8> Ops;
3435 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3436 isTailCall, RegsToPass, Ops, NodeTys,
3439 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3440 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3441 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3443 // When performing tail call optimization the callee pops its arguments off
3444 // the stack. Account for this here so these bytes can be pushed back on in
3445 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3446 int BytesCalleePops =
3447 (CallConv == CallingConv::Fast &&
3448 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3450 // Add a register mask operand representing the call-preserved registers.
3451 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3452 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3453 assert(Mask && "Missing call preserved mask for calling convention");
3454 Ops.push_back(DAG.getRegisterMask(Mask));
3456 if (InFlag.getNode())
3457 Ops.push_back(InFlag);
3461 assert(((Callee.getOpcode() == ISD::Register &&
3462 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3463 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3464 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3465 isa<ConstantSDNode>(Callee)) &&
3466 "Expecting an global address, external symbol, absolute value or register");
3468 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3471 // Add a NOP immediately after the branch instruction when using the 64-bit
3472 // SVR4 ABI. At link time, if caller and callee are in a different module and
3473 // thus have a different TOC, the call will be replaced with a call to a stub
3474 // function which saves the current TOC, loads the TOC of the callee and
3475 // branches to the callee. The NOP will be replaced with a load instruction
3476 // which restores the TOC of the caller from the TOC save slot of the current
3477 // stack frame. If caller and callee belong to the same module (and have the
3478 // same TOC), the NOP will remain unchanged.
3480 bool needsTOCRestore = false;
3481 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3482 if (CallOpc == PPCISD::BCTRL) {
3483 // This is a call through a function pointer.
3484 // Restore the caller TOC from the save area into R2.
3485 // See PrepareCall() for more information about calls through function
3486 // pointers in the 64-bit SVR4 ABI.
3487 // We are using a target-specific load with r2 hard coded, because the
3488 // result of a target-independent load would never go directly into r2,
3489 // since r2 is a reserved register (which prevents the register allocator
3490 // from allocating it), resulting in an additional register being
3491 // allocated and an unnecessary move instruction being generated.
3492 needsTOCRestore = true;
3493 } else if ((CallOpc == PPCISD::CALL) &&
3494 (!isLocalCall(Callee) ||
3495 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3496 // Otherwise insert NOP for non-local calls.
3497 CallOpc = PPCISD::CALL_NOP;
3501 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3502 InFlag = Chain.getValue(1);
3504 if (needsTOCRestore) {
3505 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3506 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3507 InFlag = Chain.getValue(1);
3510 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3511 DAG.getIntPtrConstant(BytesCalleePops, true),
3514 InFlag = Chain.getValue(1);
3516 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3517 Ins, dl, DAG, InVals);
3521 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3522 SmallVectorImpl<SDValue> &InVals) const {
3523 SelectionDAG &DAG = CLI.DAG;
3525 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3526 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3527 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3528 SDValue Chain = CLI.Chain;
3529 SDValue Callee = CLI.Callee;
3530 bool &isTailCall = CLI.IsTailCall;
3531 CallingConv::ID CallConv = CLI.CallConv;
3532 bool isVarArg = CLI.IsVarArg;
3535 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3538 if (PPCSubTarget.isSVR4ABI()) {
3539 if (PPCSubTarget.isPPC64())
3540 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3541 isTailCall, Outs, OutVals, Ins,
3544 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3545 isTailCall, Outs, OutVals, Ins,
3549 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3550 isTailCall, Outs, OutVals, Ins,
3555 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3556 CallingConv::ID CallConv, bool isVarArg,
3558 const SmallVectorImpl<ISD::OutputArg> &Outs,
3559 const SmallVectorImpl<SDValue> &OutVals,
3560 const SmallVectorImpl<ISD::InputArg> &Ins,
3561 SDLoc dl, SelectionDAG &DAG,
3562 SmallVectorImpl<SDValue> &InVals) const {
3563 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3564 // of the 32-bit SVR4 ABI stack frame layout.
3566 assert((CallConv == CallingConv::C ||
3567 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3569 unsigned PtrByteSize = 4;
3571 MachineFunction &MF = DAG.getMachineFunction();
3573 // Mark this function as potentially containing a function that contains a
3574 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3575 // and restoring the callers stack pointer in this functions epilog. This is
3576 // done because by tail calling the called function might overwrite the value
3577 // in this function's (MF) stack pointer stack slot 0(SP).
3578 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3579 CallConv == CallingConv::Fast)
3580 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3582 // Count how many bytes are to be pushed on the stack, including the linkage
3583 // area, parameter list area and the part of the local variable space which
3584 // contains copies of aggregates which are passed by value.
3586 // Assign locations to all of the outgoing arguments.
3587 SmallVector<CCValAssign, 16> ArgLocs;
3588 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3589 getTargetMachine(), ArgLocs, *DAG.getContext());
3591 // Reserve space for the linkage area on the stack.
3592 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3595 // Handle fixed and variable vector arguments differently.
3596 // Fixed vector arguments go into registers as long as registers are
3597 // available. Variable vector arguments always go into memory.
3598 unsigned NumArgs = Outs.size();
3600 for (unsigned i = 0; i != NumArgs; ++i) {
3601 MVT ArgVT = Outs[i].VT;
3602 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3605 if (Outs[i].IsFixed) {
3606 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3609 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3615 errs() << "Call operand #" << i << " has unhandled type "
3616 << EVT(ArgVT).getEVTString() << "\n";
3618 llvm_unreachable(0);
3622 // All arguments are treated the same.
3623 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3626 // Assign locations to all of the outgoing aggregate by value arguments.
3627 SmallVector<CCValAssign, 16> ByValArgLocs;
3628 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3629 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3631 // Reserve stack space for the allocations in CCInfo.
3632 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3634 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3636 // Size of the linkage area, parameter list area and the part of the local
3637 // space variable where copies of aggregates which are passed by value are
3639 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3641 // Calculate by how many bytes the stack has to be adjusted in case of tail
3642 // call optimization.
3643 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3645 // Adjust the stack pointer for the new arguments...
3646 // These operations are automatically eliminated by the prolog/epilog pass
3647 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3649 SDValue CallSeqStart = Chain;
3651 // Load the return address and frame pointer so it can be moved somewhere else
3654 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3657 // Set up a copy of the stack pointer for use loading and storing any
3658 // arguments that may not fit in the registers available for argument
3660 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3662 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3663 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3664 SmallVector<SDValue, 8> MemOpChains;
3666 bool seenFloatArg = false;
3667 // Walk the register/memloc assignments, inserting copies/loads.
3668 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3671 CCValAssign &VA = ArgLocs[i];
3672 SDValue Arg = OutVals[i];
3673 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3675 if (Flags.isByVal()) {
3676 // Argument is an aggregate which is passed by value, thus we need to
3677 // create a copy of it in the local variable space of the current stack
3678 // frame (which is the stack frame of the caller) and pass the address of
3679 // this copy to the callee.
3680 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3681 CCValAssign &ByValVA = ByValArgLocs[j++];
3682 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3684 // Memory reserved in the local variable space of the callers stack frame.
3685 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3687 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3688 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3690 // Create a copy of the argument in the local area of the current
3692 SDValue MemcpyCall =
3693 CreateCopyOfByValArgument(Arg, PtrOff,
3694 CallSeqStart.getNode()->getOperand(0),
3697 // This must go outside the CALLSEQ_START..END.
3698 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3699 CallSeqStart.getNode()->getOperand(1),
3701 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3702 NewCallSeqStart.getNode());
3703 Chain = CallSeqStart = NewCallSeqStart;
3705 // Pass the address of the aggregate copy on the stack either in a
3706 // physical register or in the parameter list area of the current stack
3707 // frame to the callee.
3711 if (VA.isRegLoc()) {
3712 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3713 // Put argument in a physical register.
3714 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3716 // Put argument in the parameter list area of the current stack frame.
3717 assert(VA.isMemLoc());
3718 unsigned LocMemOffset = VA.getLocMemOffset();
3721 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3722 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3724 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3725 MachinePointerInfo(),
3728 // Calculate and remember argument location.
3729 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3735 if (!MemOpChains.empty())
3736 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3737 &MemOpChains[0], MemOpChains.size());
3739 // Build a sequence of copy-to-reg nodes chained together with token chain
3740 // and flag operands which copy the outgoing args into the appropriate regs.
3742 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3743 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3744 RegsToPass[i].second, InFlag);
3745 InFlag = Chain.getValue(1);
3748 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3751 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3752 SDValue Ops[] = { Chain, InFlag };
3754 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3755 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3757 InFlag = Chain.getValue(1);
3761 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3762 false, TailCallArguments);
3764 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3765 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3769 // Copy an argument into memory, being careful to do this outside the
3770 // call sequence for the call to which the argument belongs.
3772 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3773 SDValue CallSeqStart,
3774 ISD::ArgFlagsTy Flags,
3777 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3778 CallSeqStart.getNode()->getOperand(0),
3780 // The MEMCPY must go outside the CALLSEQ_START..END.
3781 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3782 CallSeqStart.getNode()->getOperand(1),
3784 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3785 NewCallSeqStart.getNode());
3786 return NewCallSeqStart;
3790 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3791 CallingConv::ID CallConv, bool isVarArg,
3793 const SmallVectorImpl<ISD::OutputArg> &Outs,
3794 const SmallVectorImpl<SDValue> &OutVals,
3795 const SmallVectorImpl<ISD::InputArg> &Ins,
3796 SDLoc dl, SelectionDAG &DAG,
3797 SmallVectorImpl<SDValue> &InVals) const {
3799 unsigned NumOps = Outs.size();
3801 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3802 unsigned PtrByteSize = 8;
3804 MachineFunction &MF = DAG.getMachineFunction();
3806 // Mark this function as potentially containing a function that contains a
3807 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3808 // and restoring the callers stack pointer in this functions epilog. This is
3809 // done because by tail calling the called function might overwrite the value
3810 // in this function's (MF) stack pointer stack slot 0(SP).
3811 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3812 CallConv == CallingConv::Fast)
3813 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3815 unsigned nAltivecParamsAtEnd = 0;
3817 // Count how many bytes are to be pushed on the stack, including the linkage
3818 // area, and parameter passing area. We start with at least 48 bytes, which
3819 // is reserved space for [SP][CR][LR][3 x unused].
3820 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3823 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3824 Outs, OutVals, nAltivecParamsAtEnd);
3826 // Calculate by how many bytes the stack has to be adjusted in case of tail
3827 // call optimization.
3828 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3830 // To protect arguments on the stack from being clobbered in a tail call,
3831 // force all the loads to happen before doing any other lowering.
3833 Chain = DAG.getStackArgumentTokenFactor(Chain);
3835 // Adjust the stack pointer for the new arguments...
3836 // These operations are automatically eliminated by the prolog/epilog pass
3837 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3839 SDValue CallSeqStart = Chain;
3841 // Load the return address and frame pointer so it can be move somewhere else
3844 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3847 // Set up a copy of the stack pointer for use loading and storing any
3848 // arguments that may not fit in the registers available for argument
3850 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3852 // Figure out which arguments are going to go in registers, and which in
3853 // memory. Also, if this is a vararg function, floating point operations
3854 // must be stored to our stack, and loaded into integer regs as well, if
3855 // any integer regs are available for argument passing.
3856 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3857 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3859 static const uint16_t GPR[] = {
3860 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3861 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3863 static const uint16_t *FPR = GetFPR();
3865 static const uint16_t VR[] = {
3866 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3867 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3869 const unsigned NumGPRs = array_lengthof(GPR);
3870 const unsigned NumFPRs = 13;
3871 const unsigned NumVRs = array_lengthof(VR);
3873 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3874 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3876 SmallVector<SDValue, 8> MemOpChains;
3877 for (unsigned i = 0; i != NumOps; ++i) {
3878 SDValue Arg = OutVals[i];
3879 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3881 // PtrOff will be used to store the current argument to the stack if a
3882 // register cannot be found for it.
3885 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3887 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3889 // Promote integers to 64-bit values.
3890 if (Arg.getValueType() == MVT::i32) {
3891 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3892 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3893 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3896 // FIXME memcpy is used way more than necessary. Correctness first.
3897 // Note: "by value" is code for passing a structure by value, not
3899 if (Flags.isByVal()) {
3900 // Note: Size includes alignment padding, so
3901 // struct x { short a; char b; }
3902 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3903 // These are the proper values we need for right-justifying the
3904 // aggregate in a parameter register.
3905 unsigned Size = Flags.getByValSize();
3907 // An empty aggregate parameter takes up no storage and no
3912 unsigned BVAlign = Flags.getByValAlign();
3914 if (BVAlign % PtrByteSize != 0)
3916 "ByVal alignment is not a multiple of the pointer size");
3918 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
3921 // All aggregates smaller than 8 bytes must be passed right-justified.
3922 if (Size==1 || Size==2 || Size==4) {
3923 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3924 if (GPR_idx != NumGPRs) {
3925 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3926 MachinePointerInfo(), VT,
3928 MemOpChains.push_back(Load.getValue(1));
3929 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3931 ArgOffset += PtrByteSize;
3936 if (GPR_idx == NumGPRs && Size < 8) {
3937 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3938 PtrOff.getValueType());
3939 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3940 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3943 ArgOffset += PtrByteSize;
3946 // Copy entire object into memory. There are cases where gcc-generated
3947 // code assumes it is there, even if it could be put entirely into
3948 // registers. (This is not what the doc says.)
3950 // FIXME: The above statement is likely due to a misunderstanding of the
3951 // documents. All arguments must be copied into the parameter area BY
3952 // THE CALLEE in the event that the callee takes the address of any
3953 // formal argument. That has not yet been implemented. However, it is
3954 // reasonable to use the stack area as a staging area for the register
3957 // Skip this for small aggregates, as we will use the same slot for a
3958 // right-justified copy, below.
3960 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3964 // When a register is available, pass a small aggregate right-justified.
3965 if (Size < 8 && GPR_idx != NumGPRs) {
3966 // The easiest way to get this right-justified in a register
3967 // is to copy the structure into the rightmost portion of a
3968 // local variable slot, then load the whole slot into the
3970 // FIXME: The memcpy seems to produce pretty awful code for
3971 // small aggregates, particularly for packed ones.
3972 // FIXME: It would be preferable to use the slot in the
3973 // parameter save area instead of a new local variable.
3974 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3975 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3976 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3980 // Load the slot into the register.
3981 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3982 MachinePointerInfo(),
3983 false, false, false, 0);
3984 MemOpChains.push_back(Load.getValue(1));
3985 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3987 // Done with this argument.
3988 ArgOffset += PtrByteSize;
3992 // For aggregates larger than PtrByteSize, copy the pieces of the
3993 // object that fit into registers from the parameter save area.
3994 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3995 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3996 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3997 if (GPR_idx != NumGPRs) {
3998 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3999 MachinePointerInfo(),
4000 false, false, false, 0);
4001 MemOpChains.push_back(Load.getValue(1));
4002 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4003 ArgOffset += PtrByteSize;
4005 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4012 switch (Arg.getSimpleValueType().SimpleTy) {
4013 default: llvm_unreachable("Unexpected ValueType for argument!");
4016 if (GPR_idx != NumGPRs) {
4017 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4019 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4020 true, isTailCall, false, MemOpChains,
4021 TailCallArguments, dl);
4023 ArgOffset += PtrByteSize;
4027 if (FPR_idx != NumFPRs) {
4028 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4031 // A single float or an aggregate containing only a single float
4032 // must be passed right-justified in the stack doubleword, and
4033 // in the GPR, if one is available.
4035 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4036 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4037 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4041 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4042 MachinePointerInfo(), false, false, 0);
4043 MemOpChains.push_back(Store);
4045 // Float varargs are always shadowed in available integer registers
4046 if (GPR_idx != NumGPRs) {
4047 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4048 MachinePointerInfo(), false, false,
4050 MemOpChains.push_back(Load.getValue(1));
4051 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4053 } else if (GPR_idx != NumGPRs)
4054 // If we have any FPRs remaining, we may also have GPRs remaining.
4057 // Single-precision floating-point values are mapped to the
4058 // second (rightmost) word of the stack doubleword.
4059 if (Arg.getValueType() == MVT::f32) {
4060 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4061 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4064 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4065 true, isTailCall, false, MemOpChains,
4066 TailCallArguments, dl);
4075 // These go aligned on the stack, or in the corresponding R registers
4076 // when within range. The Darwin PPC ABI doc claims they also go in
4077 // V registers; in fact gcc does this only for arguments that are
4078 // prototyped, not for those that match the ... We do it for all
4079 // arguments, seems to work.
4080 while (ArgOffset % 16 !=0) {
4081 ArgOffset += PtrByteSize;
4082 if (GPR_idx != NumGPRs)
4085 // We could elide this store in the case where the object fits
4086 // entirely in R registers. Maybe later.
4087 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4088 DAG.getConstant(ArgOffset, PtrVT));
4089 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4090 MachinePointerInfo(), false, false, 0);
4091 MemOpChains.push_back(Store);
4092 if (VR_idx != NumVRs) {
4093 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4094 MachinePointerInfo(),
4095 false, false, false, 0);
4096 MemOpChains.push_back(Load.getValue(1));
4097 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4100 for (unsigned i=0; i<16; i+=PtrByteSize) {
4101 if (GPR_idx == NumGPRs)
4103 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4104 DAG.getConstant(i, PtrVT));
4105 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4106 false, false, false, 0);
4107 MemOpChains.push_back(Load.getValue(1));
4108 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4113 // Non-varargs Altivec params generally go in registers, but have
4114 // stack space allocated at the end.
4115 if (VR_idx != NumVRs) {
4116 // Doesn't have GPR space allocated.
4117 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4119 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4120 true, isTailCall, true, MemOpChains,
4121 TailCallArguments, dl);
4128 if (!MemOpChains.empty())
4129 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4130 &MemOpChains[0], MemOpChains.size());
4132 // Check if this is an indirect call (MTCTR/BCTRL).
4133 // See PrepareCall() for more information about calls through function
4134 // pointers in the 64-bit SVR4 ABI.
4136 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4137 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4138 !isBLACompatibleAddress(Callee, DAG)) {
4139 // Load r2 into a virtual register and store it to the TOC save area.
4140 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4141 // TOC save area offset.
4142 SDValue PtrOff = DAG.getIntPtrConstant(40);
4143 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4144 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4146 // R12 must contain the address of an indirect callee. This does not
4147 // mean the MTCTR instruction must use R12; it's easier to model this
4148 // as an extra parameter, so do that.
4149 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4152 // Build a sequence of copy-to-reg nodes chained together with token chain
4153 // and flag operands which copy the outgoing args into the appropriate regs.
4155 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4156 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4157 RegsToPass[i].second, InFlag);
4158 InFlag = Chain.getValue(1);
4162 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4163 FPOp, true, TailCallArguments);
4165 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4166 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4171 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4172 CallingConv::ID CallConv, bool isVarArg,
4174 const SmallVectorImpl<ISD::OutputArg> &Outs,
4175 const SmallVectorImpl<SDValue> &OutVals,
4176 const SmallVectorImpl<ISD::InputArg> &Ins,
4177 SDLoc dl, SelectionDAG &DAG,
4178 SmallVectorImpl<SDValue> &InVals) const {
4180 unsigned NumOps = Outs.size();
4182 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4183 bool isPPC64 = PtrVT == MVT::i64;
4184 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4186 MachineFunction &MF = DAG.getMachineFunction();
4188 // Mark this function as potentially containing a function that contains a
4189 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4190 // and restoring the callers stack pointer in this functions epilog. This is
4191 // done because by tail calling the called function might overwrite the value
4192 // in this function's (MF) stack pointer stack slot 0(SP).
4193 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4194 CallConv == CallingConv::Fast)
4195 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4197 unsigned nAltivecParamsAtEnd = 0;
4199 // Count how many bytes are to be pushed on the stack, including the linkage
4200 // area, and parameter passing area. We start with 24/48 bytes, which is
4201 // prereserved space for [SP][CR][LR][3 x unused].
4203 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4205 nAltivecParamsAtEnd);
4207 // Calculate by how many bytes the stack has to be adjusted in case of tail
4208 // call optimization.
4209 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4211 // To protect arguments on the stack from being clobbered in a tail call,
4212 // force all the loads to happen before doing any other lowering.
4214 Chain = DAG.getStackArgumentTokenFactor(Chain);
4216 // Adjust the stack pointer for the new arguments...
4217 // These operations are automatically eliminated by the prolog/epilog pass
4218 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4220 SDValue CallSeqStart = Chain;
4222 // Load the return address and frame pointer so it can be move somewhere else
4225 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4228 // Set up a copy of the stack pointer for use loading and storing any
4229 // arguments that may not fit in the registers available for argument
4233 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4235 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4237 // Figure out which arguments are going to go in registers, and which in
4238 // memory. Also, if this is a vararg function, floating point operations
4239 // must be stored to our stack, and loaded into integer regs as well, if
4240 // any integer regs are available for argument passing.
4241 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4242 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4244 static const uint16_t GPR_32[] = { // 32-bit registers.
4245 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4246 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4248 static const uint16_t GPR_64[] = { // 64-bit registers.
4249 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4250 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4252 static const uint16_t *FPR = GetFPR();
4254 static const uint16_t VR[] = {
4255 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4256 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4258 const unsigned NumGPRs = array_lengthof(GPR_32);
4259 const unsigned NumFPRs = 13;
4260 const unsigned NumVRs = array_lengthof(VR);
4262 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4264 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4265 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4267 SmallVector<SDValue, 8> MemOpChains;
4268 for (unsigned i = 0; i != NumOps; ++i) {
4269 SDValue Arg = OutVals[i];
4270 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4272 // PtrOff will be used to store the current argument to the stack if a
4273 // register cannot be found for it.
4276 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4278 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4280 // On PPC64, promote integers to 64-bit values.
4281 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4282 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4283 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4284 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4287 // FIXME memcpy is used way more than necessary. Correctness first.
4288 // Note: "by value" is code for passing a structure by value, not
4290 if (Flags.isByVal()) {
4291 unsigned Size = Flags.getByValSize();
4292 // Very small objects are passed right-justified. Everything else is
4293 // passed left-justified.
4294 if (Size==1 || Size==2) {
4295 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4296 if (GPR_idx != NumGPRs) {
4297 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4298 MachinePointerInfo(), VT,
4300 MemOpChains.push_back(Load.getValue(1));
4301 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4303 ArgOffset += PtrByteSize;
4305 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4306 PtrOff.getValueType());
4307 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4308 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4311 ArgOffset += PtrByteSize;
4315 // Copy entire object into memory. There are cases where gcc-generated
4316 // code assumes it is there, even if it could be put entirely into
4317 // registers. (This is not what the doc says.)
4318 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4322 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4323 // copy the pieces of the object that fit into registers from the
4324 // parameter save area.
4325 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4326 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4327 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4328 if (GPR_idx != NumGPRs) {
4329 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4330 MachinePointerInfo(),
4331 false, false, false, 0);
4332 MemOpChains.push_back(Load.getValue(1));
4333 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4334 ArgOffset += PtrByteSize;
4336 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4343 switch (Arg.getSimpleValueType().SimpleTy) {
4344 default: llvm_unreachable("Unexpected ValueType for argument!");
4347 if (GPR_idx != NumGPRs) {
4348 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4350 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4351 isPPC64, isTailCall, false, MemOpChains,
4352 TailCallArguments, dl);
4354 ArgOffset += PtrByteSize;
4358 if (FPR_idx != NumFPRs) {
4359 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4362 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4363 MachinePointerInfo(), false, false, 0);
4364 MemOpChains.push_back(Store);
4366 // Float varargs are always shadowed in available integer registers
4367 if (GPR_idx != NumGPRs) {
4368 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4369 MachinePointerInfo(), false, false,
4371 MemOpChains.push_back(Load.getValue(1));
4372 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4374 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4375 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4376 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4377 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4378 MachinePointerInfo(),
4379 false, false, false, 0);
4380 MemOpChains.push_back(Load.getValue(1));
4381 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4384 // If we have any FPRs remaining, we may also have GPRs remaining.
4385 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4387 if (GPR_idx != NumGPRs)
4389 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4390 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4394 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4395 isPPC64, isTailCall, false, MemOpChains,
4396 TailCallArguments, dl);
4400 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4407 // These go aligned on the stack, or in the corresponding R registers
4408 // when within range. The Darwin PPC ABI doc claims they also go in
4409 // V registers; in fact gcc does this only for arguments that are
4410 // prototyped, not for those that match the ... We do it for all
4411 // arguments, seems to work.
4412 while (ArgOffset % 16 !=0) {
4413 ArgOffset += PtrByteSize;
4414 if (GPR_idx != NumGPRs)
4417 // We could elide this store in the case where the object fits
4418 // entirely in R registers. Maybe later.
4419 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4420 DAG.getConstant(ArgOffset, PtrVT));
4421 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4422 MachinePointerInfo(), false, false, 0);
4423 MemOpChains.push_back(Store);
4424 if (VR_idx != NumVRs) {
4425 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4426 MachinePointerInfo(),
4427 false, false, false, 0);
4428 MemOpChains.push_back(Load.getValue(1));
4429 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4432 for (unsigned i=0; i<16; i+=PtrByteSize) {
4433 if (GPR_idx == NumGPRs)
4435 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4436 DAG.getConstant(i, PtrVT));
4437 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4438 false, false, false, 0);
4439 MemOpChains.push_back(Load.getValue(1));
4440 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4445 // Non-varargs Altivec params generally go in registers, but have
4446 // stack space allocated at the end.
4447 if (VR_idx != NumVRs) {
4448 // Doesn't have GPR space allocated.
4449 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4450 } else if (nAltivecParamsAtEnd==0) {
4451 // We are emitting Altivec params in order.
4452 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4453 isPPC64, isTailCall, true, MemOpChains,
4454 TailCallArguments, dl);
4460 // If all Altivec parameters fit in registers, as they usually do,
4461 // they get stack space following the non-Altivec parameters. We
4462 // don't track this here because nobody below needs it.
4463 // If there are more Altivec parameters than fit in registers emit
4465 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4467 // Offset is aligned; skip 1st 12 params which go in V registers.
4468 ArgOffset = ((ArgOffset+15)/16)*16;
4470 for (unsigned i = 0; i != NumOps; ++i) {
4471 SDValue Arg = OutVals[i];
4472 EVT ArgType = Outs[i].VT;
4473 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4474 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4477 // We are emitting Altivec params in order.
4478 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4479 isPPC64, isTailCall, true, MemOpChains,
4480 TailCallArguments, dl);
4487 if (!MemOpChains.empty())
4488 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4489 &MemOpChains[0], MemOpChains.size());
4491 // On Darwin, R12 must contain the address of an indirect callee. This does
4492 // not mean the MTCTR instruction must use R12; it's easier to model this as
4493 // an extra parameter, so do that.
4495 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4496 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4497 !isBLACompatibleAddress(Callee, DAG))
4498 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4499 PPC::R12), Callee));
4501 // Build a sequence of copy-to-reg nodes chained together with token chain
4502 // and flag operands which copy the outgoing args into the appropriate regs.
4504 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4505 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4506 RegsToPass[i].second, InFlag);
4507 InFlag = Chain.getValue(1);
4511 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4512 FPOp, true, TailCallArguments);
4514 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4515 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4520 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4521 MachineFunction &MF, bool isVarArg,
4522 const SmallVectorImpl<ISD::OutputArg> &Outs,
4523 LLVMContext &Context) const {
4524 SmallVector<CCValAssign, 16> RVLocs;
4525 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4527 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4531 PPCTargetLowering::LowerReturn(SDValue Chain,
4532 CallingConv::ID CallConv, bool isVarArg,
4533 const SmallVectorImpl<ISD::OutputArg> &Outs,
4534 const SmallVectorImpl<SDValue> &OutVals,
4535 SDLoc dl, SelectionDAG &DAG) const {
4537 SmallVector<CCValAssign, 16> RVLocs;
4538 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4539 getTargetMachine(), RVLocs, *DAG.getContext());
4540 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4543 SmallVector<SDValue, 4> RetOps(1, Chain);
4545 // Copy the result values into the output registers.
4546 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4547 CCValAssign &VA = RVLocs[i];
4548 assert(VA.isRegLoc() && "Can only return in registers!");
4550 SDValue Arg = OutVals[i];
4552 switch (VA.getLocInfo()) {
4553 default: llvm_unreachable("Unknown loc info!");
4554 case CCValAssign::Full: break;
4555 case CCValAssign::AExt:
4556 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4558 case CCValAssign::ZExt:
4559 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4561 case CCValAssign::SExt:
4562 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4566 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4567 Flag = Chain.getValue(1);
4568 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4571 RetOps[0] = Chain; // Update chain.
4573 // Add the flag if we have it.
4575 RetOps.push_back(Flag);
4577 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4578 &RetOps[0], RetOps.size());
4581 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4582 const PPCSubtarget &Subtarget) const {
4583 // When we pop the dynamic allocation we need to restore the SP link.
4586 // Get the corect type for pointers.
4587 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4589 // Construct the stack pointer operand.
4590 bool isPPC64 = Subtarget.isPPC64();
4591 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4592 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4594 // Get the operands for the STACKRESTORE.
4595 SDValue Chain = Op.getOperand(0);
4596 SDValue SaveSP = Op.getOperand(1);
4598 // Load the old link SP.
4599 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4600 MachinePointerInfo(),
4601 false, false, false, 0);
4603 // Restore the stack pointer.
4604 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4606 // Store the old link SP.
4607 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4614 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4615 MachineFunction &MF = DAG.getMachineFunction();
4616 bool isPPC64 = PPCSubTarget.isPPC64();
4617 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4618 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4620 // Get current frame pointer save index. The users of this index will be
4621 // primarily DYNALLOC instructions.
4622 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4623 int RASI = FI->getReturnAddrSaveIndex();
4625 // If the frame pointer save index hasn't been defined yet.
4627 // Find out what the fix offset of the frame pointer save area.
4628 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4629 // Allocate the frame index for frame pointer save area.
4630 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4632 FI->setReturnAddrSaveIndex(RASI);
4634 return DAG.getFrameIndex(RASI, PtrVT);
4638 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4639 MachineFunction &MF = DAG.getMachineFunction();
4640 bool isPPC64 = PPCSubTarget.isPPC64();
4641 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4642 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4644 // Get current frame pointer save index. The users of this index will be
4645 // primarily DYNALLOC instructions.
4646 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4647 int FPSI = FI->getFramePointerSaveIndex();
4649 // If the frame pointer save index hasn't been defined yet.
4651 // Find out what the fix offset of the frame pointer save area.
4652 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4655 // Allocate the frame index for frame pointer save area.
4656 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4658 FI->setFramePointerSaveIndex(FPSI);
4660 return DAG.getFrameIndex(FPSI, PtrVT);
4663 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4665 const PPCSubtarget &Subtarget) const {
4667 SDValue Chain = Op.getOperand(0);
4668 SDValue Size = Op.getOperand(1);
4671 // Get the corect type for pointers.
4672 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4674 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4675 DAG.getConstant(0, PtrVT), Size);
4676 // Construct a node for the frame pointer save index.
4677 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4678 // Build a DYNALLOC node.
4679 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4680 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4681 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4684 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4685 SelectionDAG &DAG) const {
4687 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4688 DAG.getVTList(MVT::i32, MVT::Other),
4689 Op.getOperand(0), Op.getOperand(1));
4692 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4693 SelectionDAG &DAG) const {
4695 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4696 Op.getOperand(0), Op.getOperand(1));
4699 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4701 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4702 // Not FP? Not a fsel.
4703 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4704 !Op.getOperand(2).getValueType().isFloatingPoint())
4707 // We might be able to do better than this under some circumstances, but in
4708 // general, fsel-based lowering of select is a finite-math-only optimization.
4709 // For more information, see section F.3 of the 2.06 ISA specification.
4710 if (!DAG.getTarget().Options.NoInfsFPMath ||
4711 !DAG.getTarget().Options.NoNaNsFPMath)
4714 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4716 EVT ResVT = Op.getValueType();
4717 EVT CmpVT = Op.getOperand(0).getValueType();
4718 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4719 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4722 // If the RHS of the comparison is a 0.0, we don't need to do the
4723 // subtraction at all.
4725 if (isFloatingPointZero(RHS))
4727 default: break; // SETUO etc aren't handled by fsel.
4731 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4732 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4733 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4734 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4735 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4736 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4737 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4740 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4743 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4744 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4745 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4748 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4751 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4752 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4753 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4754 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4759 default: break; // SETUO etc aren't handled by fsel.
4763 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4764 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4765 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4766 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4767 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4768 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4769 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4770 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
4773 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4774 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4775 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4776 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4779 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4780 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4781 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4782 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4785 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4786 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4787 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4788 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4791 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4792 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4793 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4794 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4799 // FIXME: Split this code up when LegalizeDAGTypes lands.
4800 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4802 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4803 SDValue Src = Op.getOperand(0);
4804 if (Src.getValueType() == MVT::f32)
4805 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4808 switch (Op.getSimpleValueType().SimpleTy) {
4809 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4811 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4812 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
4817 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
4818 "i64 FP_TO_UINT is supported only with FPCVT");
4819 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
4825 // Convert the FP value to an int value through memory.
4826 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
4827 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
4828 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
4829 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
4830 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
4832 // Emit a store to the stack slot.
4835 MachineFunction &MF = DAG.getMachineFunction();
4836 MachineMemOperand *MMO =
4837 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
4838 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
4839 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
4840 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
4843 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4844 MPI, false, false, 0);
4846 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4848 if (Op.getValueType() == MVT::i32 && !i32Stack) {
4849 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4850 DAG.getConstant(4, FIPtr.getValueType()));
4851 MPI = MachinePointerInfo();
4854 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
4855 false, false, false, 0);
4858 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
4859 SelectionDAG &DAG) const {
4861 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4862 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4865 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
4866 "UINT_TO_FP is supported only with FPCVT");
4868 // If we have FCFIDS, then use it when converting to single-precision.
4869 // Otherwise, convert to double-precision and then round.
4870 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4871 (Op.getOpcode() == ISD::UINT_TO_FP ?
4872 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
4873 (Op.getOpcode() == ISD::UINT_TO_FP ?
4874 PPCISD::FCFIDU : PPCISD::FCFID);
4875 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4876 MVT::f32 : MVT::f64;
4878 if (Op.getOperand(0).getValueType() == MVT::i64) {
4879 SDValue SINT = Op.getOperand(0);
4880 // When converting to single-precision, we actually need to convert
4881 // to double-precision first and then round to single-precision.
4882 // To avoid double-rounding effects during that operation, we have
4883 // to prepare the input operand. Bits that might be truncated when
4884 // converting to double-precision are replaced by a bit that won't
4885 // be lost at this stage, but is below the single-precision rounding
4888 // However, if -enable-unsafe-fp-math is in effect, accept double
4889 // rounding to avoid the extra overhead.
4890 if (Op.getValueType() == MVT::f32 &&
4891 !PPCSubTarget.hasFPCVT() &&
4892 !DAG.getTarget().Options.UnsafeFPMath) {
4894 // Twiddle input to make sure the low 11 bits are zero. (If this
4895 // is the case, we are guaranteed the value will fit into the 53 bit
4896 // mantissa of an IEEE double-precision value without rounding.)
4897 // If any of those low 11 bits were not zero originally, make sure
4898 // bit 12 (value 2048) is set instead, so that the final rounding
4899 // to single-precision gets the correct result.
4900 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4901 SINT, DAG.getConstant(2047, MVT::i64));
4902 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4903 Round, DAG.getConstant(2047, MVT::i64));
4904 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4905 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4906 Round, DAG.getConstant(-2048, MVT::i64));
4908 // However, we cannot use that value unconditionally: if the magnitude
4909 // of the input value is small, the bit-twiddling we did above might
4910 // end up visibly changing the output. Fortunately, in that case, we
4911 // don't need to twiddle bits since the original input will convert
4912 // exactly to double-precision floating-point already. Therefore,
4913 // construct a conditional to use the original value if the top 11
4914 // bits are all sign-bit copies, and use the rounded value computed
4916 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4917 SINT, DAG.getConstant(53, MVT::i32));
4918 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4919 Cond, DAG.getConstant(1, MVT::i64));
4920 Cond = DAG.getSetCC(dl, MVT::i32,
4921 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4923 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4926 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4927 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
4929 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
4930 FP = DAG.getNode(ISD::FP_ROUND, dl,
4931 MVT::f32, FP, DAG.getIntPtrConstant(0));
4935 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4936 "Unhandled INT_TO_FP type in custom expander!");
4937 // Since we only generate this in 64-bit mode, we can take advantage of
4938 // 64-bit registers. In particular, sign extend the input value into the
4939 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4940 // then lfd it and fcfid it.
4941 MachineFunction &MF = DAG.getMachineFunction();
4942 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4943 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4946 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
4947 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
4948 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4950 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
4951 MachinePointerInfo::getFixedStack(FrameIdx),
4954 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
4955 "Expected an i32 store");
4956 MachineMemOperand *MMO =
4957 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4958 MachineMemOperand::MOLoad, 4, 4);
4959 SDValue Ops[] = { Store, FIdx };
4960 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
4961 PPCISD::LFIWZX : PPCISD::LFIWAX,
4962 dl, DAG.getVTList(MVT::f64, MVT::Other),
4963 Ops, 2, MVT::i32, MMO);
4965 assert(PPCSubTarget.isPPC64() &&
4966 "i32->FP without LFIWAX supported only on PPC64");
4968 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4969 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4971 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
4974 // STD the extended value into the stack slot.
4975 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
4976 MachinePointerInfo::getFixedStack(FrameIdx),
4979 // Load the value as a double.
4980 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
4981 MachinePointerInfo::getFixedStack(FrameIdx),
4982 false, false, false, 0);
4985 // FCFID it and return it.
4986 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
4987 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
4988 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4992 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4993 SelectionDAG &DAG) const {
4996 The rounding mode is in bits 30:31 of FPSR, and has the following
5003 FLT_ROUNDS, on the other hand, expects the following:
5010 To perform the conversion, we do:
5011 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5014 MachineFunction &MF = DAG.getMachineFunction();
5015 EVT VT = Op.getValueType();
5016 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5017 SDValue MFFSreg, InFlag;
5019 // Save FP Control Word to register
5021 MVT::f64, // return register
5022 MVT::Glue // unused in this context
5024 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5026 // Save FP register to stack slot
5027 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5028 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5029 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5030 StackSlot, MachinePointerInfo(), false, false,0);
5032 // Load FP Control Word from low 32 bits of stack slot.
5033 SDValue Four = DAG.getConstant(4, PtrVT);
5034 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5035 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5036 false, false, false, 0);
5038 // Transform as necessary
5040 DAG.getNode(ISD::AND, dl, MVT::i32,
5041 CWD, DAG.getConstant(3, MVT::i32));
5043 DAG.getNode(ISD::SRL, dl, MVT::i32,
5044 DAG.getNode(ISD::AND, dl, MVT::i32,
5045 DAG.getNode(ISD::XOR, dl, MVT::i32,
5046 CWD, DAG.getConstant(3, MVT::i32)),
5047 DAG.getConstant(3, MVT::i32)),
5048 DAG.getConstant(1, MVT::i32));
5051 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5053 return DAG.getNode((VT.getSizeInBits() < 16 ?
5054 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5057 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5058 EVT VT = Op.getValueType();
5059 unsigned BitWidth = VT.getSizeInBits();
5061 assert(Op.getNumOperands() == 3 &&
5062 VT == Op.getOperand(1).getValueType() &&
5065 // Expand into a bunch of logical ops. Note that these ops
5066 // depend on the PPC behavior for oversized shift amounts.
5067 SDValue Lo = Op.getOperand(0);
5068 SDValue Hi = Op.getOperand(1);
5069 SDValue Amt = Op.getOperand(2);
5070 EVT AmtVT = Amt.getValueType();
5072 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5073 DAG.getConstant(BitWidth, AmtVT), Amt);
5074 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5075 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5076 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5077 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5078 DAG.getConstant(-BitWidth, AmtVT));
5079 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5080 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5081 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5082 SDValue OutOps[] = { OutLo, OutHi };
5083 return DAG.getMergeValues(OutOps, 2, dl);
5086 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5087 EVT VT = Op.getValueType();
5089 unsigned BitWidth = VT.getSizeInBits();
5090 assert(Op.getNumOperands() == 3 &&
5091 VT == Op.getOperand(1).getValueType() &&
5094 // Expand into a bunch of logical ops. Note that these ops
5095 // depend on the PPC behavior for oversized shift amounts.
5096 SDValue Lo = Op.getOperand(0);
5097 SDValue Hi = Op.getOperand(1);
5098 SDValue Amt = Op.getOperand(2);
5099 EVT AmtVT = Amt.getValueType();
5101 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5102 DAG.getConstant(BitWidth, AmtVT), Amt);
5103 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5104 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5105 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5106 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5107 DAG.getConstant(-BitWidth, AmtVT));
5108 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5109 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5110 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5111 SDValue OutOps[] = { OutLo, OutHi };
5112 return DAG.getMergeValues(OutOps, 2, dl);
5115 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5117 EVT VT = Op.getValueType();
5118 unsigned BitWidth = VT.getSizeInBits();
5119 assert(Op.getNumOperands() == 3 &&
5120 VT == Op.getOperand(1).getValueType() &&
5123 // Expand into a bunch of logical ops, followed by a select_cc.
5124 SDValue Lo = Op.getOperand(0);
5125 SDValue Hi = Op.getOperand(1);
5126 SDValue Amt = Op.getOperand(2);
5127 EVT AmtVT = Amt.getValueType();
5129 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5130 DAG.getConstant(BitWidth, AmtVT), Amt);
5131 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5132 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5133 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5134 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5135 DAG.getConstant(-BitWidth, AmtVT));
5136 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5137 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5138 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5139 Tmp4, Tmp6, ISD::SETLE);
5140 SDValue OutOps[] = { OutLo, OutHi };
5141 return DAG.getMergeValues(OutOps, 2, dl);
5144 //===----------------------------------------------------------------------===//
5145 // Vector related lowering.
5148 /// BuildSplatI - Build a canonical splati of Val with an element size of
5149 /// SplatSize. Cast the result to VT.
5150 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5151 SelectionDAG &DAG, SDLoc dl) {
5152 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5154 static const EVT VTys[] = { // canonical VT to use for each size.
5155 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5158 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5160 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5164 EVT CanonicalVT = VTys[SplatSize-1];
5166 // Build a canonical splat for this value.
5167 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5168 SmallVector<SDValue, 8> Ops;
5169 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5170 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5171 &Ops[0], Ops.size());
5172 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5175 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5176 /// specified intrinsic ID.
5177 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5178 SelectionDAG &DAG, SDLoc dl,
5179 EVT DestVT = MVT::Other) {
5180 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5181 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5182 DAG.getConstant(IID, MVT::i32), Op);
5185 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5186 /// specified intrinsic ID.
5187 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5188 SelectionDAG &DAG, SDLoc dl,
5189 EVT DestVT = MVT::Other) {
5190 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5191 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5192 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5195 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5196 /// specified intrinsic ID.
5197 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5198 SDValue Op2, SelectionDAG &DAG,
5199 SDLoc dl, EVT DestVT = MVT::Other) {
5200 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5201 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5202 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5206 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5207 /// amount. The result has the specified value type.
5208 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5209 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5210 // Force LHS/RHS to be the right type.
5211 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5212 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5215 for (unsigned i = 0; i != 16; ++i)
5217 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5218 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5221 // If this is a case we can't handle, return null and let the default
5222 // expansion code take care of it. If we CAN select this case, and if it
5223 // selects to a single instruction, return Op. Otherwise, if we can codegen
5224 // this case more efficiently than a constant pool load, lower it to the
5225 // sequence of ops that should be used.
5226 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5227 SelectionDAG &DAG) const {
5229 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5230 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5232 // Check if this is a splat of a constant value.
5233 APInt APSplatBits, APSplatUndef;
5234 unsigned SplatBitSize;
5236 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5237 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5240 unsigned SplatBits = APSplatBits.getZExtValue();
5241 unsigned SplatUndef = APSplatUndef.getZExtValue();
5242 unsigned SplatSize = SplatBitSize / 8;
5244 // First, handle single instruction cases.
5247 if (SplatBits == 0) {
5248 // Canonicalize all zero vectors to be v4i32.
5249 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5250 SDValue Z = DAG.getConstant(0, MVT::i32);
5251 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5252 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5257 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5258 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5260 if (SextVal >= -16 && SextVal <= 15)
5261 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5264 // Two instruction sequences.
5266 // If this value is in the range [-32,30] and is even, use:
5267 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5268 // If this value is in the range [17,31] and is odd, use:
5269 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5270 // If this value is in the range [-31,-17] and is odd, use:
5271 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5272 // Note the last two are three-instruction sequences.
5273 if (SextVal >= -32 && SextVal <= 31) {
5274 // To avoid having these optimizations undone by constant folding,
5275 // we convert to a pseudo that will be expanded later into one of
5277 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5278 EVT VT = Op.getValueType();
5279 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5280 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5281 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5284 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5285 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5287 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5288 // Make -1 and vspltisw -1:
5289 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5291 // Make the VSLW intrinsic, computing 0x8000_0000.
5292 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5295 // xor by OnesV to invert it.
5296 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5297 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5300 // Check to see if this is a wide variety of vsplti*, binop self cases.
5301 static const signed char SplatCsts[] = {
5302 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5303 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5306 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5307 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5308 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5309 int i = SplatCsts[idx];
5311 // Figure out what shift amount will be used by altivec if shifted by i in
5313 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5315 // vsplti + shl self.
5316 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5317 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5318 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5319 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5320 Intrinsic::ppc_altivec_vslw
5322 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5323 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5326 // vsplti + srl self.
5327 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5328 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5329 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5330 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5331 Intrinsic::ppc_altivec_vsrw
5333 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5334 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5337 // vsplti + sra self.
5338 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5339 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5340 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5341 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5342 Intrinsic::ppc_altivec_vsraw
5344 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5345 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5348 // vsplti + rol self.
5349 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5350 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5351 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5352 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5353 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5354 Intrinsic::ppc_altivec_vrlw
5356 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5357 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5360 // t = vsplti c, result = vsldoi t, t, 1
5361 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5362 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5363 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5365 // t = vsplti c, result = vsldoi t, t, 2
5366 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5367 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5368 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5370 // t = vsplti c, result = vsldoi t, t, 3
5371 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5372 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5373 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5380 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5381 /// the specified operations to build the shuffle.
5382 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5383 SDValue RHS, SelectionDAG &DAG,
5385 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5386 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5387 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5390 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5402 if (OpNum == OP_COPY) {
5403 if (LHSID == (1*9+2)*9+3) return LHS;
5404 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5408 SDValue OpLHS, OpRHS;
5409 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5410 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5414 default: llvm_unreachable("Unknown i32 permute!");
5416 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5417 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5418 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5419 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5422 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5423 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5424 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5425 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5428 for (unsigned i = 0; i != 16; ++i)
5429 ShufIdxs[i] = (i&3)+0;
5432 for (unsigned i = 0; i != 16; ++i)
5433 ShufIdxs[i] = (i&3)+4;
5436 for (unsigned i = 0; i != 16; ++i)
5437 ShufIdxs[i] = (i&3)+8;
5440 for (unsigned i = 0; i != 16; ++i)
5441 ShufIdxs[i] = (i&3)+12;
5444 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5446 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5448 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5450 EVT VT = OpLHS.getValueType();
5451 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5452 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5453 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5454 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5457 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5458 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5459 /// return the code it can be lowered into. Worst case, it can always be
5460 /// lowered into a vperm.
5461 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5462 SelectionDAG &DAG) const {
5464 SDValue V1 = Op.getOperand(0);
5465 SDValue V2 = Op.getOperand(1);
5466 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5467 EVT VT = Op.getValueType();
5469 // Cases that are handled by instructions that take permute immediates
5470 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5471 // selected by the instruction selector.
5472 if (V2.getOpcode() == ISD::UNDEF) {
5473 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5474 PPC::isSplatShuffleMask(SVOp, 2) ||
5475 PPC::isSplatShuffleMask(SVOp, 4) ||
5476 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5477 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5478 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5479 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5480 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5481 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5482 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5483 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5484 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5489 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5490 // and produce a fixed permutation. If any of these match, do not lower to
5492 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5493 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5494 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5495 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5496 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5497 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5498 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5499 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5500 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5503 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5504 // perfect shuffle table to emit an optimal matching sequence.
5505 ArrayRef<int> PermMask = SVOp->getMask();
5507 unsigned PFIndexes[4];
5508 bool isFourElementShuffle = true;
5509 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5510 unsigned EltNo = 8; // Start out undef.
5511 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5512 if (PermMask[i*4+j] < 0)
5513 continue; // Undef, ignore it.
5515 unsigned ByteSource = PermMask[i*4+j];
5516 if ((ByteSource & 3) != j) {
5517 isFourElementShuffle = false;
5522 EltNo = ByteSource/4;
5523 } else if (EltNo != ByteSource/4) {
5524 isFourElementShuffle = false;
5528 PFIndexes[i] = EltNo;
5531 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5532 // perfect shuffle vector to determine if it is cost effective to do this as
5533 // discrete instructions, or whether we should use a vperm.
5534 if (isFourElementShuffle) {
5535 // Compute the index in the perfect shuffle table.
5536 unsigned PFTableIndex =
5537 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5539 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5540 unsigned Cost = (PFEntry >> 30);
5542 // Determining when to avoid vperm is tricky. Many things affect the cost
5543 // of vperm, particularly how many times the perm mask needs to be computed.
5544 // For example, if the perm mask can be hoisted out of a loop or is already
5545 // used (perhaps because there are multiple permutes with the same shuffle
5546 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5547 // the loop requires an extra register.
5549 // As a compromise, we only emit discrete instructions if the shuffle can be
5550 // generated in 3 or fewer operations. When we have loop information
5551 // available, if this block is within a loop, we should avoid using vperm
5552 // for 3-operation perms and use a constant pool load instead.
5554 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5557 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5558 // vector that will get spilled to the constant pool.
5559 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5561 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5562 // that it is in input element units, not in bytes. Convert now.
5563 EVT EltVT = V1.getValueType().getVectorElementType();
5564 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5566 SmallVector<SDValue, 16> ResultMask;
5567 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5568 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5570 for (unsigned j = 0; j != BytesPerElement; ++j)
5571 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5575 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5576 &ResultMask[0], ResultMask.size());
5577 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5580 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5581 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5582 /// information about the intrinsic.
5583 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5585 unsigned IntrinsicID =
5586 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5589 switch (IntrinsicID) {
5590 default: return false;
5591 // Comparison predicates.
5592 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5593 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5594 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5595 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5596 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5597 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5598 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5599 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5600 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5601 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5602 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5603 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5604 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5606 // Normal Comparisons.
5607 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5608 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5609 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5610 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5611 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5612 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5613 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5614 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5615 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5616 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5617 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5618 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5619 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5624 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5625 /// lower, do it, otherwise return null.
5626 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5627 SelectionDAG &DAG) const {
5628 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5629 // opcode number of the comparison.
5633 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5634 return SDValue(); // Don't custom lower most intrinsics.
5636 // If this is a non-dot comparison, make the VCMP node and we are done.
5638 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5639 Op.getOperand(1), Op.getOperand(2),
5640 DAG.getConstant(CompareOpc, MVT::i32));
5641 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5644 // Create the PPCISD altivec 'dot' comparison node.
5646 Op.getOperand(2), // LHS
5647 Op.getOperand(3), // RHS
5648 DAG.getConstant(CompareOpc, MVT::i32)
5650 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5651 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5653 // Now that we have the comparison, emit a copy from the CR to a GPR.
5654 // This is flagged to the above dot comparison.
5655 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5656 DAG.getRegister(PPC::CR6, MVT::i32),
5657 CompNode.getValue(1));
5659 // Unpack the result based on how the target uses it.
5660 unsigned BitNo; // Bit # of CR6.
5661 bool InvertBit; // Invert result?
5662 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5663 default: // Can't happen, don't crash on invalid number though.
5664 case 0: // Return the value of the EQ bit of CR6.
5665 BitNo = 0; InvertBit = false;
5667 case 1: // Return the inverted value of the EQ bit of CR6.
5668 BitNo = 0; InvertBit = true;
5670 case 2: // Return the value of the LT bit of CR6.
5671 BitNo = 2; InvertBit = false;
5673 case 3: // Return the inverted value of the LT bit of CR6.
5674 BitNo = 2; InvertBit = true;
5678 // Shift the bit into the low position.
5679 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5680 DAG.getConstant(8-(3-BitNo), MVT::i32));
5682 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5683 DAG.getConstant(1, MVT::i32));
5685 // If we are supposed to, toggle the bit.
5687 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5688 DAG.getConstant(1, MVT::i32));
5692 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5693 SelectionDAG &DAG) const {
5695 // Create a stack slot that is 16-byte aligned.
5696 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5697 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5698 EVT PtrVT = getPointerTy();
5699 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5701 // Store the input value into Value#0 of the stack slot.
5702 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5703 Op.getOperand(0), FIdx, MachinePointerInfo(),
5706 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5707 false, false, false, 0);
5710 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5712 if (Op.getValueType() == MVT::v4i32) {
5713 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5715 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5716 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5718 SDValue RHSSwap = // = vrlw RHS, 16
5719 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5721 // Shrinkify inputs to v8i16.
5722 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5723 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5724 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5726 // Low parts multiplied together, generating 32-bit results (we ignore the
5728 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5729 LHS, RHS, DAG, dl, MVT::v4i32);
5731 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5732 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5733 // Shift the high parts up 16 bits.
5734 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5736 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5737 } else if (Op.getValueType() == MVT::v8i16) {
5738 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5740 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5742 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5743 LHS, RHS, Zero, DAG, dl);
5744 } else if (Op.getValueType() == MVT::v16i8) {
5745 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5747 // Multiply the even 8-bit parts, producing 16-bit sums.
5748 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5749 LHS, RHS, DAG, dl, MVT::v8i16);
5750 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5752 // Multiply the odd 8-bit parts, producing 16-bit sums.
5753 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5754 LHS, RHS, DAG, dl, MVT::v8i16);
5755 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5757 // Merge the results together.
5759 for (unsigned i = 0; i != 8; ++i) {
5761 Ops[i*2+1] = 2*i+1+16;
5763 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5765 llvm_unreachable("Unknown mul to lower!");
5769 /// LowerOperation - Provide custom lowering hooks for some operations.
5771 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5772 switch (Op.getOpcode()) {
5773 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5774 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5775 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5776 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5777 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5778 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5779 case ISD::SETCC: return LowerSETCC(Op, DAG);
5780 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5781 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5783 return LowerVASTART(Op, DAG, PPCSubTarget);
5786 return LowerVAARG(Op, DAG, PPCSubTarget);
5789 return LowerVACOPY(Op, DAG, PPCSubTarget);
5791 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5792 case ISD::DYNAMIC_STACKALLOC:
5793 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5795 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5796 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5798 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5799 case ISD::FP_TO_UINT:
5800 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5802 case ISD::UINT_TO_FP:
5803 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5804 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5806 // Lower 64-bit shifts.
5807 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5808 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5809 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5811 // Vector-related lowering.
5812 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5813 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5814 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5815 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5816 case ISD::MUL: return LowerMUL(Op, DAG);
5818 // For counter-based loop handling.
5819 case ISD::INTRINSIC_W_CHAIN: return SDValue();
5821 // Frame & Return address.
5822 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5823 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5827 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5828 SmallVectorImpl<SDValue>&Results,
5829 SelectionDAG &DAG) const {
5830 const TargetMachine &TM = getTargetMachine();
5832 switch (N->getOpcode()) {
5834 llvm_unreachable("Do not know how to custom type legalize this operation!");
5835 case ISD::INTRINSIC_W_CHAIN: {
5836 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
5837 Intrinsic::ppc_is_decremented_ctr_nonzero)
5840 assert(N->getValueType(0) == MVT::i1 &&
5841 "Unexpected result type for CTR decrement intrinsic");
5842 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
5843 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
5844 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
5847 Results.push_back(NewInt);
5848 Results.push_back(NewInt.getValue(1));
5852 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5853 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5856 EVT VT = N->getValueType(0);
5858 if (VT == MVT::i64) {
5859 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5861 Results.push_back(NewNode);
5862 Results.push_back(NewNode.getValue(1));
5866 case ISD::FP_ROUND_INREG: {
5867 assert(N->getValueType(0) == MVT::ppcf128);
5868 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5869 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5870 MVT::f64, N->getOperand(0),
5871 DAG.getIntPtrConstant(0));
5872 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5873 MVT::f64, N->getOperand(0),
5874 DAG.getIntPtrConstant(1));
5876 // Add the two halves of the long double in round-to-zero mode.
5877 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
5879 // We know the low half is about to be thrown away, so just use something
5881 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5885 case ISD::FP_TO_SINT:
5886 // LowerFP_TO_INT() can only handle f32 and f64.
5887 if (N->getOperand(0).getValueType() == MVT::ppcf128)
5889 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5895 //===----------------------------------------------------------------------===//
5896 // Other Lowering Code
5897 //===----------------------------------------------------------------------===//
5900 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5901 bool is64bit, unsigned BinOpcode) const {
5902 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5903 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5905 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5906 MachineFunction *F = BB->getParent();
5907 MachineFunction::iterator It = BB;
5910 unsigned dest = MI->getOperand(0).getReg();
5911 unsigned ptrA = MI->getOperand(1).getReg();
5912 unsigned ptrB = MI->getOperand(2).getReg();
5913 unsigned incr = MI->getOperand(3).getReg();
5914 DebugLoc dl = MI->getDebugLoc();
5916 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5917 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5918 F->insert(It, loopMBB);
5919 F->insert(It, exitMBB);
5920 exitMBB->splice(exitMBB->begin(), BB,
5921 llvm::next(MachineBasicBlock::iterator(MI)),
5923 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5925 MachineRegisterInfo &RegInfo = F->getRegInfo();
5926 unsigned TmpReg = (!BinOpcode) ? incr :
5927 RegInfo.createVirtualRegister(
5928 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5929 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5933 // fallthrough --> loopMBB
5934 BB->addSuccessor(loopMBB);
5937 // l[wd]arx dest, ptr
5938 // add r0, dest, incr
5939 // st[wd]cx. r0, ptr
5941 // fallthrough --> exitMBB
5943 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5944 .addReg(ptrA).addReg(ptrB);
5946 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5947 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5948 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5949 BuildMI(BB, dl, TII->get(PPC::BCC))
5950 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5951 BB->addSuccessor(loopMBB);
5952 BB->addSuccessor(exitMBB);
5961 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5962 MachineBasicBlock *BB,
5963 bool is8bit, // operation
5964 unsigned BinOpcode) const {
5965 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5966 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5967 // In 64 bit mode we have to use 64 bits for addresses, even though the
5968 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5969 // registers without caring whether they're 32 or 64, but here we're
5970 // doing actual arithmetic on the addresses.
5971 bool is64bit = PPCSubTarget.isPPC64();
5972 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
5974 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5975 MachineFunction *F = BB->getParent();
5976 MachineFunction::iterator It = BB;
5979 unsigned dest = MI->getOperand(0).getReg();
5980 unsigned ptrA = MI->getOperand(1).getReg();
5981 unsigned ptrB = MI->getOperand(2).getReg();
5982 unsigned incr = MI->getOperand(3).getReg();
5983 DebugLoc dl = MI->getDebugLoc();
5985 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5986 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5987 F->insert(It, loopMBB);
5988 F->insert(It, exitMBB);
5989 exitMBB->splice(exitMBB->begin(), BB,
5990 llvm::next(MachineBasicBlock::iterator(MI)),
5992 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5994 MachineRegisterInfo &RegInfo = F->getRegInfo();
5995 const TargetRegisterClass *RC =
5996 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5997 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5998 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5999 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6000 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6001 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6002 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6003 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6004 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6005 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6006 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6007 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6008 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6010 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6014 // fallthrough --> loopMBB
6015 BB->addSuccessor(loopMBB);
6017 // The 4-byte load must be aligned, while a char or short may be
6018 // anywhere in the word. Hence all this nasty bookkeeping code.
6019 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6020 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6021 // xori shift, shift1, 24 [16]
6022 // rlwinm ptr, ptr1, 0, 0, 29
6023 // slw incr2, incr, shift
6024 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6025 // slw mask, mask2, shift
6027 // lwarx tmpDest, ptr
6028 // add tmp, tmpDest, incr2
6029 // andc tmp2, tmpDest, mask
6030 // and tmp3, tmp, mask
6031 // or tmp4, tmp3, tmp2
6034 // fallthrough --> exitMBB
6035 // srw dest, tmpDest, shift
6036 if (ptrA != ZeroReg) {
6037 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6038 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6039 .addReg(ptrA).addReg(ptrB);
6043 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6044 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6045 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6046 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6048 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6049 .addReg(Ptr1Reg).addImm(0).addImm(61);
6051 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6052 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6053 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6054 .addReg(incr).addReg(ShiftReg);
6056 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6058 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6059 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6061 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6062 .addReg(Mask2Reg).addReg(ShiftReg);
6065 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6066 .addReg(ZeroReg).addReg(PtrReg);
6068 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6069 .addReg(Incr2Reg).addReg(TmpDestReg);
6070 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6071 .addReg(TmpDestReg).addReg(MaskReg);
6072 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6073 .addReg(TmpReg).addReg(MaskReg);
6074 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6075 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6076 BuildMI(BB, dl, TII->get(PPC::STWCX))
6077 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6078 BuildMI(BB, dl, TII->get(PPC::BCC))
6079 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6080 BB->addSuccessor(loopMBB);
6081 BB->addSuccessor(exitMBB);
6086 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6091 llvm::MachineBasicBlock*
6092 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6093 MachineBasicBlock *MBB) const {
6094 DebugLoc DL = MI->getDebugLoc();
6095 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6097 MachineFunction *MF = MBB->getParent();
6098 MachineRegisterInfo &MRI = MF->getRegInfo();
6100 const BasicBlock *BB = MBB->getBasicBlock();
6101 MachineFunction::iterator I = MBB;
6105 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6106 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6108 unsigned DstReg = MI->getOperand(0).getReg();
6109 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6110 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6111 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6112 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6114 MVT PVT = getPointerTy();
6115 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6116 "Invalid Pointer Size!");
6117 // For v = setjmp(buf), we generate
6120 // SjLjSetup mainMBB
6126 // buf[LabelOffset] = LR
6130 // v = phi(main, restore)
6133 MachineBasicBlock *thisMBB = MBB;
6134 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6135 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6136 MF->insert(I, mainMBB);
6137 MF->insert(I, sinkMBB);
6139 MachineInstrBuilder MIB;
6141 // Transfer the remainder of BB and its successor edges to sinkMBB.
6142 sinkMBB->splice(sinkMBB->begin(), MBB,
6143 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
6144 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6146 // Note that the structure of the jmp_buf used here is not compatible
6147 // with that used by libc, and is not designed to be. Specifically, it
6148 // stores only those 'reserved' registers that LLVM does not otherwise
6149 // understand how to spill. Also, by convention, by the time this
6150 // intrinsic is called, Clang has already stored the frame address in the
6151 // first slot of the buffer and stack address in the third. Following the
6152 // X86 target code, we'll store the jump address in the second slot. We also
6153 // need to save the TOC pointer (R2) to handle jumps between shared
6154 // libraries, and that will be stored in the fourth slot. The thread
6155 // identifier (R13) is not affected.
6158 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6159 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6160 const int64_t BPOffset = 4 * PVT.getStoreSize();
6162 // Prepare IP either in reg.
6163 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6164 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6165 unsigned BufReg = MI->getOperand(1).getReg();
6167 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6168 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6172 MIB.setMemRefs(MMOBegin, MMOEnd);
6175 // Naked functions never have a base pointer, and so we use r1. For all
6176 // other functions, this decision must be delayed until during PEI.
6178 if (MF->getFunction()->getAttributes().hasAttribute(
6179 AttributeSet::FunctionIndex, Attribute::Naked))
6180 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6182 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6184 MIB = BuildMI(*thisMBB, MI, DL,
6185 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6189 MIB.setMemRefs(MMOBegin, MMOEnd);
6192 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6193 const PPCRegisterInfo *TRI =
6194 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6195 MIB.addRegMask(TRI->getNoPreservedMask());
6197 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6199 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6201 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6203 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6204 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6208 MIB = BuildMI(mainMBB, DL,
6209 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6212 if (PPCSubTarget.isPPC64()) {
6213 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6215 .addImm(LabelOffset)
6218 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6220 .addImm(LabelOffset)
6224 MIB.setMemRefs(MMOBegin, MMOEnd);
6226 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6227 mainMBB->addSuccessor(sinkMBB);
6230 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6231 TII->get(PPC::PHI), DstReg)
6232 .addReg(mainDstReg).addMBB(mainMBB)
6233 .addReg(restoreDstReg).addMBB(thisMBB);
6235 MI->eraseFromParent();
6240 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6241 MachineBasicBlock *MBB) const {
6242 DebugLoc DL = MI->getDebugLoc();
6243 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6245 MachineFunction *MF = MBB->getParent();
6246 MachineRegisterInfo &MRI = MF->getRegInfo();
6249 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6250 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6252 MVT PVT = getPointerTy();
6253 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6254 "Invalid Pointer Size!");
6256 const TargetRegisterClass *RC =
6257 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6258 unsigned Tmp = MRI.createVirtualRegister(RC);
6259 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6260 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6261 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6262 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6264 MachineInstrBuilder MIB;
6266 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6267 const int64_t SPOffset = 2 * PVT.getStoreSize();
6268 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6269 const int64_t BPOffset = 4 * PVT.getStoreSize();
6271 unsigned BufReg = MI->getOperand(0).getReg();
6273 // Reload FP (the jumped-to function may not have had a
6274 // frame pointer, and if so, then its r31 will be restored
6276 if (PVT == MVT::i64) {
6277 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6281 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6285 MIB.setMemRefs(MMOBegin, MMOEnd);
6288 if (PVT == MVT::i64) {
6289 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6290 .addImm(LabelOffset)
6293 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6294 .addImm(LabelOffset)
6297 MIB.setMemRefs(MMOBegin, MMOEnd);
6300 if (PVT == MVT::i64) {
6301 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6305 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6309 MIB.setMemRefs(MMOBegin, MMOEnd);
6312 if (PVT == MVT::i64) {
6313 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6317 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6321 MIB.setMemRefs(MMOBegin, MMOEnd);
6324 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6325 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6329 MIB.setMemRefs(MMOBegin, MMOEnd);
6333 BuildMI(*MBB, MI, DL,
6334 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6335 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6337 MI->eraseFromParent();
6342 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6343 MachineBasicBlock *BB) const {
6344 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6345 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6346 return emitEHSjLjSetJmp(MI, BB);
6347 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6348 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6349 return emitEHSjLjLongJmp(MI, BB);
6352 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6354 // To "insert" these instructions we actually have to insert their
6355 // control-flow patterns.
6356 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6357 MachineFunction::iterator It = BB;
6360 MachineFunction *F = BB->getParent();
6362 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6363 MI->getOpcode() == PPC::SELECT_CC_I8)) {
6364 SmallVector<MachineOperand, 2> Cond;
6365 Cond.push_back(MI->getOperand(4));
6366 Cond.push_back(MI->getOperand(1));
6368 DebugLoc dl = MI->getDebugLoc();
6369 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6370 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6371 Cond, MI->getOperand(2).getReg(),
6372 MI->getOperand(3).getReg());
6373 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6374 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6375 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6376 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6377 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
6380 // The incoming instruction knows the destination vreg to set, the
6381 // condition code register to branch on, the true/false values to
6382 // select between, and a branch opcode to use.
6387 // cmpTY ccX, r1, r2
6389 // fallthrough --> copy0MBB
6390 MachineBasicBlock *thisMBB = BB;
6391 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6392 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6393 unsigned SelectPred = MI->getOperand(4).getImm();
6394 DebugLoc dl = MI->getDebugLoc();
6395 F->insert(It, copy0MBB);
6396 F->insert(It, sinkMBB);
6398 // Transfer the remainder of BB and its successor edges to sinkMBB.
6399 sinkMBB->splice(sinkMBB->begin(), BB,
6400 llvm::next(MachineBasicBlock::iterator(MI)),
6402 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6404 // Next, add the true and fallthrough blocks as its successors.
6405 BB->addSuccessor(copy0MBB);
6406 BB->addSuccessor(sinkMBB);
6408 BuildMI(BB, dl, TII->get(PPC::BCC))
6409 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6412 // %FalseValue = ...
6413 // # fallthrough to sinkMBB
6416 // Update machine-CFG edges
6417 BB->addSuccessor(sinkMBB);
6420 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6423 BuildMI(*BB, BB->begin(), dl,
6424 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6425 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6426 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6428 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6429 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6430 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6431 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6432 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6433 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6434 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6435 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6437 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6438 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6439 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6440 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6441 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6442 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6443 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6444 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6446 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6447 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6448 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6449 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6450 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6451 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6452 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6453 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6455 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6456 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6457 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6458 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6459 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6460 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6461 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6462 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6464 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6465 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6466 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6467 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6468 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6469 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6470 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6471 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6473 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6474 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6475 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6476 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6477 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6478 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6479 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6480 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6482 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6483 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6484 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6485 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6486 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6487 BB = EmitAtomicBinary(MI, BB, false, 0);
6488 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6489 BB = EmitAtomicBinary(MI, BB, true, 0);
6491 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6492 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6493 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6495 unsigned dest = MI->getOperand(0).getReg();
6496 unsigned ptrA = MI->getOperand(1).getReg();
6497 unsigned ptrB = MI->getOperand(2).getReg();
6498 unsigned oldval = MI->getOperand(3).getReg();
6499 unsigned newval = MI->getOperand(4).getReg();
6500 DebugLoc dl = MI->getDebugLoc();
6502 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6503 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6504 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6505 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6506 F->insert(It, loop1MBB);
6507 F->insert(It, loop2MBB);
6508 F->insert(It, midMBB);
6509 F->insert(It, exitMBB);
6510 exitMBB->splice(exitMBB->begin(), BB,
6511 llvm::next(MachineBasicBlock::iterator(MI)),
6513 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6517 // fallthrough --> loopMBB
6518 BB->addSuccessor(loop1MBB);
6521 // l[wd]arx dest, ptr
6522 // cmp[wd] dest, oldval
6525 // st[wd]cx. newval, ptr
6529 // st[wd]cx. dest, ptr
6532 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6533 .addReg(ptrA).addReg(ptrB);
6534 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6535 .addReg(oldval).addReg(dest);
6536 BuildMI(BB, dl, TII->get(PPC::BCC))
6537 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6538 BB->addSuccessor(loop2MBB);
6539 BB->addSuccessor(midMBB);
6542 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6543 .addReg(newval).addReg(ptrA).addReg(ptrB);
6544 BuildMI(BB, dl, TII->get(PPC::BCC))
6545 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6546 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6547 BB->addSuccessor(loop1MBB);
6548 BB->addSuccessor(exitMBB);
6551 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6552 .addReg(dest).addReg(ptrA).addReg(ptrB);
6553 BB->addSuccessor(exitMBB);
6558 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6559 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6560 // We must use 64-bit registers for addresses when targeting 64-bit,
6561 // since we're actually doing arithmetic on them. Other registers
6563 bool is64bit = PPCSubTarget.isPPC64();
6564 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6566 unsigned dest = MI->getOperand(0).getReg();
6567 unsigned ptrA = MI->getOperand(1).getReg();
6568 unsigned ptrB = MI->getOperand(2).getReg();
6569 unsigned oldval = MI->getOperand(3).getReg();
6570 unsigned newval = MI->getOperand(4).getReg();
6571 DebugLoc dl = MI->getDebugLoc();
6573 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6574 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6575 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6576 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6577 F->insert(It, loop1MBB);
6578 F->insert(It, loop2MBB);
6579 F->insert(It, midMBB);
6580 F->insert(It, exitMBB);
6581 exitMBB->splice(exitMBB->begin(), BB,
6582 llvm::next(MachineBasicBlock::iterator(MI)),
6584 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6586 MachineRegisterInfo &RegInfo = F->getRegInfo();
6587 const TargetRegisterClass *RC =
6588 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6589 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6590 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6591 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6592 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6593 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6594 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6595 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6596 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6597 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6598 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6599 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6600 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6601 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6602 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6604 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6605 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6608 // fallthrough --> loopMBB
6609 BB->addSuccessor(loop1MBB);
6611 // The 4-byte load must be aligned, while a char or short may be
6612 // anywhere in the word. Hence all this nasty bookkeeping code.
6613 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6614 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6615 // xori shift, shift1, 24 [16]
6616 // rlwinm ptr, ptr1, 0, 0, 29
6617 // slw newval2, newval, shift
6618 // slw oldval2, oldval,shift
6619 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6620 // slw mask, mask2, shift
6621 // and newval3, newval2, mask
6622 // and oldval3, oldval2, mask
6624 // lwarx tmpDest, ptr
6625 // and tmp, tmpDest, mask
6626 // cmpw tmp, oldval3
6629 // andc tmp2, tmpDest, mask
6630 // or tmp4, tmp2, newval3
6635 // stwcx. tmpDest, ptr
6637 // srw dest, tmpDest, shift
6638 if (ptrA != ZeroReg) {
6639 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6640 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6641 .addReg(ptrA).addReg(ptrB);
6645 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6646 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6647 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6648 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6650 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6651 .addReg(Ptr1Reg).addImm(0).addImm(61);
6653 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6654 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6655 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6656 .addReg(newval).addReg(ShiftReg);
6657 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6658 .addReg(oldval).addReg(ShiftReg);
6660 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6662 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6663 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6664 .addReg(Mask3Reg).addImm(65535);
6666 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6667 .addReg(Mask2Reg).addReg(ShiftReg);
6668 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6669 .addReg(NewVal2Reg).addReg(MaskReg);
6670 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6671 .addReg(OldVal2Reg).addReg(MaskReg);
6674 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6675 .addReg(ZeroReg).addReg(PtrReg);
6676 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6677 .addReg(TmpDestReg).addReg(MaskReg);
6678 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6679 .addReg(TmpReg).addReg(OldVal3Reg);
6680 BuildMI(BB, dl, TII->get(PPC::BCC))
6681 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6682 BB->addSuccessor(loop2MBB);
6683 BB->addSuccessor(midMBB);
6686 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6687 .addReg(TmpDestReg).addReg(MaskReg);
6688 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6689 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6690 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6691 .addReg(ZeroReg).addReg(PtrReg);
6692 BuildMI(BB, dl, TII->get(PPC::BCC))
6693 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6694 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6695 BB->addSuccessor(loop1MBB);
6696 BB->addSuccessor(exitMBB);
6699 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6700 .addReg(ZeroReg).addReg(PtrReg);
6701 BB->addSuccessor(exitMBB);
6706 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6708 } else if (MI->getOpcode() == PPC::FADDrtz) {
6709 // This pseudo performs an FADD with rounding mode temporarily forced
6710 // to round-to-zero. We emit this via custom inserter since the FPSCR
6711 // is not modeled at the SelectionDAG level.
6712 unsigned Dest = MI->getOperand(0).getReg();
6713 unsigned Src1 = MI->getOperand(1).getReg();
6714 unsigned Src2 = MI->getOperand(2).getReg();
6715 DebugLoc dl = MI->getDebugLoc();
6717 MachineRegisterInfo &RegInfo = F->getRegInfo();
6718 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6720 // Save FPSCR value.
6721 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6723 // Set rounding mode to round-to-zero.
6724 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6725 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6727 // Perform addition.
6728 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6730 // Restore FPSCR value.
6731 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6733 llvm_unreachable("Unexpected instr type to insert");
6736 MI->eraseFromParent(); // The pseudo instruction is gone now.
6740 //===----------------------------------------------------------------------===//
6741 // Target Optimization Hooks
6742 //===----------------------------------------------------------------------===//
6744 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6745 DAGCombinerInfo &DCI) const {
6746 if (DCI.isAfterLegalizeVectorOps())
6749 EVT VT = Op.getValueType();
6751 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6752 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6753 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6755 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6756 // For the reciprocal, we need to find the zero of the function:
6757 // F(X) = A X - 1 [which has a zero at X = 1/A]
6759 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
6760 // does not require additional intermediate precision]
6762 // Convergence is quadratic, so we essentially double the number of digits
6763 // correct after every iteration. The minimum architected relative
6764 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6765 // 23 digits and double has 52 digits.
6766 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6767 if (VT.getScalarType() == MVT::f64)
6770 SelectionDAG &DAG = DCI.DAG;
6774 DAG.getConstantFP(1.0, VT.getScalarType());
6775 if (VT.isVector()) {
6776 assert(VT.getVectorNumElements() == 4 &&
6777 "Unknown vector type");
6778 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6779 FPOne, FPOne, FPOne, FPOne);
6782 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
6783 DCI.AddToWorklist(Est.getNode());
6785 // Newton iterations: Est = Est + Est (1 - Arg * Est)
6786 for (int i = 0; i < Iterations; ++i) {
6787 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
6788 DCI.AddToWorklist(NewEst.getNode());
6790 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
6791 DCI.AddToWorklist(NewEst.getNode());
6793 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6794 DCI.AddToWorklist(NewEst.getNode());
6796 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
6797 DCI.AddToWorklist(Est.getNode());
6806 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
6807 DAGCombinerInfo &DCI) const {
6808 if (DCI.isAfterLegalizeVectorOps())
6811 EVT VT = Op.getValueType();
6813 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
6814 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
6815 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6817 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6818 // For the reciprocal sqrt, we need to find the zero of the function:
6819 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
6821 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
6822 // As a result, we precompute A/2 prior to the iteration loop.
6824 // Convergence is quadratic, so we essentially double the number of digits
6825 // correct after every iteration. The minimum architected relative
6826 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6827 // 23 digits and double has 52 digits.
6828 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6829 if (VT.getScalarType() == MVT::f64)
6832 SelectionDAG &DAG = DCI.DAG;
6835 SDValue FPThreeHalves =
6836 DAG.getConstantFP(1.5, VT.getScalarType());
6837 if (VT.isVector()) {
6838 assert(VT.getVectorNumElements() == 4 &&
6839 "Unknown vector type");
6840 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6841 FPThreeHalves, FPThreeHalves,
6842 FPThreeHalves, FPThreeHalves);
6845 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
6846 DCI.AddToWorklist(Est.getNode());
6848 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
6849 // this entire sequence requires only one FP constant.
6850 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
6851 DCI.AddToWorklist(HalfArg.getNode());
6853 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
6854 DCI.AddToWorklist(HalfArg.getNode());
6856 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
6857 for (int i = 0; i < Iterations; ++i) {
6858 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
6859 DCI.AddToWorklist(NewEst.getNode());
6861 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
6862 DCI.AddToWorklist(NewEst.getNode());
6864 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
6865 DCI.AddToWorklist(NewEst.getNode());
6867 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6868 DCI.AddToWorklist(Est.getNode());
6877 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
6878 // not enforce equality of the chain operands.
6879 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
6880 unsigned Bytes, int Dist,
6881 SelectionDAG &DAG) {
6882 EVT VT = LS->getMemoryVT();
6883 if (VT.getSizeInBits() / 8 != Bytes)
6886 SDValue Loc = LS->getBasePtr();
6887 SDValue BaseLoc = Base->getBasePtr();
6888 if (Loc.getOpcode() == ISD::FrameIndex) {
6889 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6891 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6892 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6893 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6894 int FS = MFI->getObjectSize(FI);
6895 int BFS = MFI->getObjectSize(BFI);
6896 if (FS != BFS || FS != (int)Bytes) return false;
6897 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6901 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
6902 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
6905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6906 const GlobalValue *GV1 = NULL;
6907 const GlobalValue *GV2 = NULL;
6908 int64_t Offset1 = 0;
6909 int64_t Offset2 = 0;
6910 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6911 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6912 if (isGA1 && isGA2 && GV1 == GV2)
6913 return Offset1 == (Offset2 + Dist*Bytes);
6917 // Return true is there is a nearyby consecutive load to the one provided
6918 // (regardless of alignment). We search up and down the chain, looking though
6919 // token factors and other loads (but nothing else). As a result, a true
6920 // results indicates that it is safe to create a new consecutive load adjacent
6921 // to the load provided.
6922 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
6923 SDValue Chain = LD->getChain();
6924 EVT VT = LD->getMemoryVT();
6926 SmallSet<SDNode *, 16> LoadRoots;
6927 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
6928 SmallSet<SDNode *, 16> Visited;
6930 // First, search up the chain, branching to follow all token-factor operands.
6931 // If we find a consecutive load, then we're done, otherwise, record all
6932 // nodes just above the top-level loads and token factors.
6933 while (!Queue.empty()) {
6934 SDNode *ChainNext = Queue.pop_back_val();
6935 if (!Visited.insert(ChainNext))
6938 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
6939 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
6942 if (!Visited.count(ChainLD->getChain().getNode()))
6943 Queue.push_back(ChainLD->getChain().getNode());
6944 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
6945 for (SDNode::op_iterator O = ChainNext->op_begin(),
6946 OE = ChainNext->op_end(); O != OE; ++O)
6947 if (!Visited.count(O->getNode()))
6948 Queue.push_back(O->getNode());
6950 LoadRoots.insert(ChainNext);
6953 // Second, search down the chain, starting from the top-level nodes recorded
6954 // in the first phase. These top-level nodes are the nodes just above all
6955 // loads and token factors. Starting with their uses, recursively look though
6956 // all loads (just the chain uses) and token factors to find a consecutive
6961 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
6962 IE = LoadRoots.end(); I != IE; ++I) {
6963 Queue.push_back(*I);
6965 while (!Queue.empty()) {
6966 SDNode *LoadRoot = Queue.pop_back_val();
6967 if (!Visited.insert(LoadRoot))
6970 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
6971 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
6974 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
6975 UE = LoadRoot->use_end(); UI != UE; ++UI)
6976 if (((isa<LoadSDNode>(*UI) &&
6977 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
6978 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
6979 Queue.push_back(*UI);
6986 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6987 DAGCombinerInfo &DCI) const {
6988 const TargetMachine &TM = getTargetMachine();
6989 SelectionDAG &DAG = DCI.DAG;
6991 switch (N->getOpcode()) {
6994 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6995 if (C->isNullValue()) // 0 << V -> 0.
6996 return N->getOperand(0);
7000 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7001 if (C->isNullValue()) // 0 >>u V -> 0.
7002 return N->getOperand(0);
7006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7007 if (C->isNullValue() || // 0 >>s V -> 0.
7008 C->isAllOnesValue()) // -1 >>s V -> -1.
7009 return N->getOperand(0);
7013 assert(TM.Options.UnsafeFPMath &&
7014 "Reciprocal estimates require UnsafeFPMath");
7016 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7018 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7019 if (RV.getNode() != 0) {
7020 DCI.AddToWorklist(RV.getNode());
7021 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7022 N->getOperand(0), RV);
7024 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7025 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7027 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7029 if (RV.getNode() != 0) {
7030 DCI.AddToWorklist(RV.getNode());
7031 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7032 N->getValueType(0), RV);
7033 DCI.AddToWorklist(RV.getNode());
7034 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7035 N->getOperand(0), RV);
7037 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7038 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7040 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7042 if (RV.getNode() != 0) {
7043 DCI.AddToWorklist(RV.getNode());
7044 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7045 N->getValueType(0), RV,
7046 N->getOperand(1).getOperand(1));
7047 DCI.AddToWorklist(RV.getNode());
7048 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7049 N->getOperand(0), RV);
7053 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7054 if (RV.getNode() != 0) {
7055 DCI.AddToWorklist(RV.getNode());
7056 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7057 N->getOperand(0), RV);
7063 assert(TM.Options.UnsafeFPMath &&
7064 "Reciprocal estimates require UnsafeFPMath");
7066 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7068 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7069 if (RV.getNode() != 0) {
7070 DCI.AddToWorklist(RV.getNode());
7071 RV = DAGCombineFastRecip(RV, DCI);
7072 if (RV.getNode() != 0) {
7073 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7074 // this case and force the answer to 0.
7076 EVT VT = RV.getValueType();
7078 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7079 if (VT.isVector()) {
7080 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7081 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7085 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7086 N->getOperand(0), Zero, ISD::SETEQ);
7087 DCI.AddToWorklist(ZeroCmp.getNode());
7088 DCI.AddToWorklist(RV.getNode());
7090 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7098 case ISD::SINT_TO_FP:
7099 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7100 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7101 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7102 // We allow the src/dst to be either f32/f64, but the intermediate
7103 // type must be i64.
7104 if (N->getOperand(0).getValueType() == MVT::i64 &&
7105 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7106 SDValue Val = N->getOperand(0).getOperand(0);
7107 if (Val.getValueType() == MVT::f32) {
7108 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7109 DCI.AddToWorklist(Val.getNode());
7112 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7113 DCI.AddToWorklist(Val.getNode());
7114 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7115 DCI.AddToWorklist(Val.getNode());
7116 if (N->getValueType(0) == MVT::f32) {
7117 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7118 DAG.getIntPtrConstant(0));
7119 DCI.AddToWorklist(Val.getNode());
7122 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7123 // If the intermediate type is i32, we can avoid the load/store here
7130 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7131 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7132 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7133 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7134 N->getOperand(1).getValueType() == MVT::i32 &&
7135 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7136 SDValue Val = N->getOperand(1).getOperand(0);
7137 if (Val.getValueType() == MVT::f32) {
7138 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7139 DCI.AddToWorklist(Val.getNode());
7141 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7142 DCI.AddToWorklist(Val.getNode());
7145 N->getOperand(0), Val, N->getOperand(2),
7146 DAG.getValueType(N->getOperand(1).getValueType())
7149 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7150 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7151 cast<StoreSDNode>(N)->getMemoryVT(),
7152 cast<StoreSDNode>(N)->getMemOperand());
7153 DCI.AddToWorklist(Val.getNode());
7157 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7158 if (cast<StoreSDNode>(N)->isUnindexed() &&
7159 N->getOperand(1).getOpcode() == ISD::BSWAP &&
7160 N->getOperand(1).getNode()->hasOneUse() &&
7161 (N->getOperand(1).getValueType() == MVT::i32 ||
7162 N->getOperand(1).getValueType() == MVT::i16 ||
7163 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7164 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7165 N->getOperand(1).getValueType() == MVT::i64))) {
7166 SDValue BSwapOp = N->getOperand(1).getOperand(0);
7167 // Do an any-extend to 32-bits if this is a half-word input.
7168 if (BSwapOp.getValueType() == MVT::i16)
7169 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7172 N->getOperand(0), BSwapOp, N->getOperand(2),
7173 DAG.getValueType(N->getOperand(1).getValueType())
7176 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7177 Ops, array_lengthof(Ops),
7178 cast<StoreSDNode>(N)->getMemoryVT(),
7179 cast<StoreSDNode>(N)->getMemOperand());
7183 LoadSDNode *LD = cast<LoadSDNode>(N);
7184 EVT VT = LD->getValueType(0);
7185 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
7186 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
7187 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
7188 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
7189 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
7190 VT == MVT::v4i32 || VT == MVT::v4f32) &&
7191 LD->getAlignment() < ABIAlignment) {
7192 // This is a type-legal unaligned Altivec load.
7193 SDValue Chain = LD->getChain();
7194 SDValue Ptr = LD->getBasePtr();
7196 // This implements the loading of unaligned vectors as described in
7197 // the venerable Apple Velocity Engine overview. Specifically:
7198 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
7199 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
7201 // The general idea is to expand a sequence of one or more unaligned
7202 // loads into a alignment-based permutation-control instruction (lvsl),
7203 // a series of regular vector loads (which always truncate their
7204 // input address to an aligned address), and a series of permutations.
7205 // The results of these permutations are the requested loaded values.
7206 // The trick is that the last "extra" load is not taken from the address
7207 // you might suspect (sizeof(vector) bytes after the last requested
7208 // load), but rather sizeof(vector) - 1 bytes after the last
7209 // requested vector. The point of this is to avoid a page fault if the
7210 // base address happend to be aligned. This works because if the base
7211 // address is aligned, then adding less than a full vector length will
7212 // cause the last vector in the sequence to be (re)loaded. Otherwise,
7213 // the next vector will be fetched as you might suspect was necessary.
7215 // We might be able to reuse the permutation generation from
7216 // a different base address offset from this one by an aligned amount.
7217 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
7218 // optimization later.
7219 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
7220 DAG, dl, MVT::v16i8);
7222 // Refine the alignment of the original load (a "new" load created here
7223 // which was identical to the first except for the alignment would be
7224 // merged with the existing node regardless).
7225 MachineFunction &MF = DAG.getMachineFunction();
7226 MachineMemOperand *MMO =
7227 MF.getMachineMemOperand(LD->getPointerInfo(),
7228 LD->getMemOperand()->getFlags(),
7229 LD->getMemoryVT().getStoreSize(),
7231 LD->refineAlignment(MMO);
7232 SDValue BaseLoad = SDValue(LD, 0);
7234 // Note that the value of IncOffset (which is provided to the next
7235 // load's pointer info offset value, and thus used to calculate the
7236 // alignment), and the value of IncValue (which is actually used to
7237 // increment the pointer value) are different! This is because we
7238 // require the next load to appear to be aligned, even though it
7239 // is actually offset from the base pointer by a lesser amount.
7240 int IncOffset = VT.getSizeInBits() / 8;
7241 int IncValue = IncOffset;
7243 // Walk (both up and down) the chain looking for another load at the real
7244 // (aligned) offset (the alignment of the other load does not matter in
7245 // this case). If found, then do not use the offset reduction trick, as
7246 // that will prevent the loads from being later combined (as they would
7247 // otherwise be duplicates).
7248 if (!findConsecutiveLoad(LD, DAG))
7251 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
7252 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
7255 DAG.getLoad(VT, dl, Chain, Ptr,
7256 LD->getPointerInfo().getWithOffset(IncOffset),
7257 LD->isVolatile(), LD->isNonTemporal(),
7258 LD->isInvariant(), ABIAlignment);
7260 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7261 BaseLoad.getValue(1), ExtraLoad.getValue(1));
7263 if (BaseLoad.getValueType() != MVT::v4i32)
7264 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
7266 if (ExtraLoad.getValueType() != MVT::v4i32)
7267 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
7269 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
7270 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
7272 if (VT != MVT::v4i32)
7273 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
7275 // Now we need to be really careful about how we update the users of the
7276 // original load. We cannot just call DCI.CombineTo (or
7277 // DAG.ReplaceAllUsesWith for that matter), because the load still has
7278 // uses created here (the permutation for example) that need to stay.
7279 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7281 SDUse &Use = UI.getUse();
7283 // Note: BaseLoad is checked here because it might not be N, but a
7285 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
7286 User == TF.getNode() || Use.getResNo() > 1) {
7291 SDValue To = Use.getResNo() ? TF : Perm;
7294 SmallVector<SDValue, 8> Ops;
7295 for (SDNode::op_iterator O = User->op_begin(),
7296 OE = User->op_end(); O != OE; ++O) {
7303 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
7306 return SDValue(N, 0);
7310 case ISD::INTRINSIC_WO_CHAIN:
7311 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
7312 Intrinsic::ppc_altivec_lvsl &&
7313 N->getOperand(1)->getOpcode() == ISD::ADD) {
7314 SDValue Add = N->getOperand(1);
7316 if (DAG.MaskedValueIsZero(Add->getOperand(1),
7317 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
7318 Add.getValueType().getScalarType().getSizeInBits()))) {
7319 SDNode *BasePtr = Add->getOperand(0).getNode();
7320 for (SDNode::use_iterator UI = BasePtr->use_begin(),
7321 UE = BasePtr->use_end(); UI != UE; ++UI) {
7322 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
7323 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
7324 Intrinsic::ppc_altivec_lvsl) {
7325 // We've found another LVSL, and this address if an aligned
7326 // multiple of that one. The results will be the same, so use the
7327 // one we've just found instead.
7329 return SDValue(*UI, 0);
7337 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
7338 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
7339 N->getOperand(0).hasOneUse() &&
7340 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
7341 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7342 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7343 N->getValueType(0) == MVT::i64))) {
7344 SDValue Load = N->getOperand(0);
7345 LoadSDNode *LD = cast<LoadSDNode>(Load);
7346 // Create the byte-swapping load.
7348 LD->getChain(), // Chain
7349 LD->getBasePtr(), // Ptr
7350 DAG.getValueType(N->getValueType(0)) // VT
7353 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
7354 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
7355 MVT::i64 : MVT::i32, MVT::Other),
7356 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
7358 // If this is an i16 load, insert the truncate.
7359 SDValue ResVal = BSLoad;
7360 if (N->getValueType(0) == MVT::i16)
7361 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
7363 // First, combine the bswap away. This makes the value produced by the
7365 DCI.CombineTo(N, ResVal);
7367 // Next, combine the load away, we give it a bogus result value but a real
7368 // chain result. The result value is dead because the bswap is dead.
7369 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
7371 // Return N so it doesn't get rechecked!
7372 return SDValue(N, 0);
7376 case PPCISD::VCMP: {
7377 // If a VCMPo node already exists with exactly the same operands as this
7378 // node, use its result instead of this node (VCMPo computes both a CR6 and
7379 // a normal output).
7381 if (!N->getOperand(0).hasOneUse() &&
7382 !N->getOperand(1).hasOneUse() &&
7383 !N->getOperand(2).hasOneUse()) {
7385 // Scan all of the users of the LHS, looking for VCMPo's that match.
7386 SDNode *VCMPoNode = 0;
7388 SDNode *LHSN = N->getOperand(0).getNode();
7389 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
7391 if (UI->getOpcode() == PPCISD::VCMPo &&
7392 UI->getOperand(1) == N->getOperand(1) &&
7393 UI->getOperand(2) == N->getOperand(2) &&
7394 UI->getOperand(0) == N->getOperand(0)) {
7399 // If there is no VCMPo node, or if the flag value has a single use, don't
7401 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
7404 // Look at the (necessarily single) use of the flag value. If it has a
7405 // chain, this transformation is more complex. Note that multiple things
7406 // could use the value result, which we should ignore.
7407 SDNode *FlagUser = 0;
7408 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
7409 FlagUser == 0; ++UI) {
7410 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
7412 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
7413 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
7420 // If the user is a MFOCRF instruction, we know this is safe.
7421 // Otherwise we give up for right now.
7422 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
7423 return SDValue(VCMPoNode, 0);
7428 // If this is a branch on an altivec predicate comparison, lower this so
7429 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
7430 // lowering is done pre-legalize, because the legalizer lowers the predicate
7431 // compare down to code that is difficult to reassemble.
7432 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
7433 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
7435 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
7436 // value. If so, pass-through the AND to get to the intrinsic.
7437 if (LHS.getOpcode() == ISD::AND &&
7438 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
7439 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
7440 Intrinsic::ppc_is_decremented_ctr_nonzero &&
7441 isa<ConstantSDNode>(LHS.getOperand(1)) &&
7442 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
7444 LHS = LHS.getOperand(0);
7446 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
7447 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
7448 Intrinsic::ppc_is_decremented_ctr_nonzero &&
7449 isa<ConstantSDNode>(RHS)) {
7450 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
7451 "Counter decrement comparison is not EQ or NE");
7453 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
7454 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
7455 (CC == ISD::SETNE && !Val);
7457 // We now need to make the intrinsic dead (it cannot be instruction
7459 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
7460 assert(LHS.getNode()->hasOneUse() &&
7461 "Counter decrement has more than one use");
7463 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
7464 N->getOperand(0), N->getOperand(4));
7470 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
7471 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
7472 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
7473 assert(isDot && "Can't compare against a vector result!");
7475 // If this is a comparison against something other than 0/1, then we know
7476 // that the condition is never/always true.
7477 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
7478 if (Val != 0 && Val != 1) {
7479 if (CC == ISD::SETEQ) // Cond never true, remove branch.
7480 return N->getOperand(0);
7481 // Always !=, turn it into an unconditional branch.
7482 return DAG.getNode(ISD::BR, dl, MVT::Other,
7483 N->getOperand(0), N->getOperand(4));
7486 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
7488 // Create the PPCISD altivec 'dot' comparison node.
7490 LHS.getOperand(2), // LHS of compare
7491 LHS.getOperand(3), // RHS of compare
7492 DAG.getConstant(CompareOpc, MVT::i32)
7494 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
7495 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
7497 // Unpack the result based on how the target uses it.
7498 PPC::Predicate CompOpc;
7499 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
7500 default: // Can't happen, don't crash on invalid number though.
7501 case 0: // Branch on the value of the EQ bit of CR6.
7502 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
7504 case 1: // Branch on the inverted value of the EQ bit of CR6.
7505 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
7507 case 2: // Branch on the value of the LT bit of CR6.
7508 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
7510 case 3: // Branch on the inverted value of the LT bit of CR6.
7511 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
7515 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
7516 DAG.getConstant(CompOpc, MVT::i32),
7517 DAG.getRegister(PPC::CR6, MVT::i32),
7518 N->getOperand(4), CompNode.getValue(1));
7527 //===----------------------------------------------------------------------===//
7528 // Inline Assembly Support
7529 //===----------------------------------------------------------------------===//
7531 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7534 const SelectionDAG &DAG,
7535 unsigned Depth) const {
7536 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
7537 switch (Op.getOpcode()) {
7539 case PPCISD::LBRX: {
7540 // lhbrx is known to have the top bits cleared out.
7541 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
7542 KnownZero = 0xFFFF0000;
7545 case ISD::INTRINSIC_WO_CHAIN: {
7546 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
7548 case Intrinsic::ppc_altivec_vcmpbfp_p:
7549 case Intrinsic::ppc_altivec_vcmpeqfp_p:
7550 case Intrinsic::ppc_altivec_vcmpequb_p:
7551 case Intrinsic::ppc_altivec_vcmpequh_p:
7552 case Intrinsic::ppc_altivec_vcmpequw_p:
7553 case Intrinsic::ppc_altivec_vcmpgefp_p:
7554 case Intrinsic::ppc_altivec_vcmpgtfp_p:
7555 case Intrinsic::ppc_altivec_vcmpgtsb_p:
7556 case Intrinsic::ppc_altivec_vcmpgtsh_p:
7557 case Intrinsic::ppc_altivec_vcmpgtsw_p:
7558 case Intrinsic::ppc_altivec_vcmpgtub_p:
7559 case Intrinsic::ppc_altivec_vcmpgtuh_p:
7560 case Intrinsic::ppc_altivec_vcmpgtuw_p:
7561 KnownZero = ~1U; // All bits but the low one are known to be zero.
7569 /// getConstraintType - Given a constraint, return the type of
7570 /// constraint it is for this target.
7571 PPCTargetLowering::ConstraintType
7572 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
7573 if (Constraint.size() == 1) {
7574 switch (Constraint[0]) {
7581 return C_RegisterClass;
7583 // FIXME: While Z does indicate a memory constraint, it specifically
7584 // indicates an r+r address (used in conjunction with the 'y' modifier
7585 // in the replacement string). Currently, we're forcing the base
7586 // register to be r0 in the asm printer (which is interpreted as zero)
7587 // and forming the complete address in the second register. This is
7592 return TargetLowering::getConstraintType(Constraint);
7595 /// Examine constraint type and operand type and determine a weight value.
7596 /// This object must already have been set up with the operand type
7597 /// and the current alternative constraint selected.
7598 TargetLowering::ConstraintWeight
7599 PPCTargetLowering::getSingleConstraintMatchWeight(
7600 AsmOperandInfo &info, const char *constraint) const {
7601 ConstraintWeight weight = CW_Invalid;
7602 Value *CallOperandVal = info.CallOperandVal;
7603 // If we don't have a value, we can't do a match,
7604 // but allow it at the lowest weight.
7605 if (CallOperandVal == NULL)
7607 Type *type = CallOperandVal->getType();
7608 // Look at the constraint type.
7609 switch (*constraint) {
7611 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7614 if (type->isIntegerTy())
7615 weight = CW_Register;
7618 if (type->isFloatTy())
7619 weight = CW_Register;
7622 if (type->isDoubleTy())
7623 weight = CW_Register;
7626 if (type->isVectorTy())
7627 weight = CW_Register;
7630 weight = CW_Register;
7639 std::pair<unsigned, const TargetRegisterClass*>
7640 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7642 if (Constraint.size() == 1) {
7643 // GCC RS6000 Constraint Letters
7644 switch (Constraint[0]) {
7646 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
7647 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
7648 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
7650 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
7651 return std::make_pair(0U, &PPC::G8RCRegClass);
7652 return std::make_pair(0U, &PPC::GPRCRegClass);
7654 if (VT == MVT::f32 || VT == MVT::i32)
7655 return std::make_pair(0U, &PPC::F4RCRegClass);
7656 if (VT == MVT::f64 || VT == MVT::i64)
7657 return std::make_pair(0U, &PPC::F8RCRegClass);
7660 return std::make_pair(0U, &PPC::VRRCRegClass);
7662 return std::make_pair(0U, &PPC::CRRCRegClass);
7666 std::pair<unsigned, const TargetRegisterClass*> R =
7667 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7669 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
7670 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
7671 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
7673 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
7674 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
7675 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
7676 PPC::GPRCRegClass.contains(R.first)) {
7677 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
7678 return std::make_pair(TRI->getMatchingSuperReg(R.first,
7679 PPC::sub_32, &PPC::G8RCRegClass),
7680 &PPC::G8RCRegClass);
7687 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7688 /// vector. If it is invalid, don't add anything to Ops.
7689 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7690 std::string &Constraint,
7691 std::vector<SDValue>&Ops,
7692 SelectionDAG &DAG) const {
7693 SDValue Result(0,0);
7695 // Only support length 1 constraints.
7696 if (Constraint.length() > 1) return;
7698 char Letter = Constraint[0];
7709 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
7710 if (!CST) return; // Must be an immediate to match.
7711 unsigned Value = CST->getZExtValue();
7713 default: llvm_unreachable("Unknown constraint letter!");
7714 case 'I': // "I" is a signed 16-bit constant.
7715 if ((short)Value == (int)Value)
7716 Result = DAG.getTargetConstant(Value, Op.getValueType());
7718 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
7719 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
7720 if ((short)Value == 0)
7721 Result = DAG.getTargetConstant(Value, Op.getValueType());
7723 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
7724 if ((Value >> 16) == 0)
7725 Result = DAG.getTargetConstant(Value, Op.getValueType());
7727 case 'M': // "M" is a constant that is greater than 31.
7729 Result = DAG.getTargetConstant(Value, Op.getValueType());
7731 case 'N': // "N" is a positive constant that is an exact power of two.
7732 if ((int)Value > 0 && isPowerOf2_32(Value))
7733 Result = DAG.getTargetConstant(Value, Op.getValueType());
7735 case 'O': // "O" is the constant zero.
7737 Result = DAG.getTargetConstant(Value, Op.getValueType());
7739 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
7740 if ((short)-Value == (int)-Value)
7741 Result = DAG.getTargetConstant(Value, Op.getValueType());
7748 if (Result.getNode()) {
7749 Ops.push_back(Result);
7753 // Handle standard constraint letters.
7754 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7757 // isLegalAddressingMode - Return true if the addressing mode represented
7758 // by AM is legal for this target, for a load/store of the specified type.
7759 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
7761 // FIXME: PPC does not allow r+i addressing modes for vectors!
7763 // PPC allows a sign-extended 16-bit immediate field.
7764 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
7767 // No global is ever allowed as a base.
7771 // PPC only support r+r,
7773 case 0: // "r+i" or just "i", depending on HasBaseReg.
7776 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
7778 // Otherwise we have r+r or r+i.
7781 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
7783 // Allow 2*r as r+r.
7786 // No other scales are supported.
7793 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
7794 SelectionDAG &DAG) const {
7795 MachineFunction &MF = DAG.getMachineFunction();
7796 MachineFrameInfo *MFI = MF.getFrameInfo();
7797 MFI->setReturnAddressIsTaken(true);
7799 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
7803 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7805 // Make sure the function does not optimize away the store of the RA to
7807 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7808 FuncInfo->setLRStoreRequired();
7809 bool isPPC64 = PPCSubTarget.isPPC64();
7810 bool isDarwinABI = PPCSubTarget.isDarwinABI();
7813 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7816 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
7817 isPPC64? MVT::i64 : MVT::i32);
7818 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7819 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7821 MachinePointerInfo(), false, false, false, 0);
7824 // Just load the return address off the stack.
7825 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
7826 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7827 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
7830 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
7831 SelectionDAG &DAG) const {
7833 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7835 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
7836 bool isPPC64 = PtrVT == MVT::i64;
7838 MachineFunction &MF = DAG.getMachineFunction();
7839 MachineFrameInfo *MFI = MF.getFrameInfo();
7840 MFI->setFrameAddressIsTaken(true);
7842 // Naked functions never have a frame pointer, and so we use r1. For all
7843 // other functions, this decision must be delayed until during PEI.
7845 if (MF.getFunction()->getAttributes().hasAttribute(
7846 AttributeSet::FunctionIndex, Attribute::Naked))
7847 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
7849 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
7851 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
7854 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
7855 FrameAddr, MachinePointerInfo(), false, false,
7861 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7862 // The PowerPC target isn't yet aware of offsets.
7866 /// getOptimalMemOpType - Returns the target specific optimal type for load
7867 /// and store operations as a result of memset, memcpy, and memmove
7868 /// lowering. If DstAlign is zero that means it's safe to destination
7869 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
7870 /// means there isn't a need to check it against alignment requirement,
7871 /// probably because the source does not need to be loaded. If 'IsMemset' is
7872 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
7873 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
7874 /// source is constant so it does not need to be loaded.
7875 /// It returns EVT::Other if the type should be determined using generic
7876 /// target-independent logic.
7877 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
7878 unsigned DstAlign, unsigned SrcAlign,
7879 bool IsMemset, bool ZeroMemset,
7881 MachineFunction &MF) const {
7882 if (this->PPCSubTarget.isPPC64()) {
7889 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
7891 if (DisablePPCUnaligned)
7894 // PowerPC supports unaligned memory access for simple non-vector types.
7895 // Although accessing unaligned addresses is not as efficient as accessing
7896 // aligned addresses, it is generally more efficient than manual expansion,
7897 // and generally only traps for software emulation when crossing page
7903 if (VT.getSimpleVT().isVector())
7906 if (VT == MVT::ppcf128)
7915 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7916 VT = VT.getScalarType();
7921 switch (VT.getSimpleVT().SimpleTy) {
7932 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
7933 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
7934 return TargetLowering::getSchedulingPreference(N);
7939 // Create a fast isel object.
7941 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
7942 const TargetLibraryInfo *LibInfo) const {
7943 return PPC::createFastISel(FuncInfo, LibInfo);