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/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
42 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
43 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
45 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
46 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
48 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
49 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
51 // FIXME: Remove this once the bug has been fixed!
52 extern cl::opt<bool> ANDIGlueBug;
54 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
55 // If it isn't a Mach-O file then it's going to be a linux ELF
58 return new TargetLoweringObjectFileMachO();
60 return new PPC64LinuxTargetObjectFile();
63 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
64 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))),
65 Subtarget(*TM.getSubtargetImpl()) {
68 // Use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(true);
70 setUseUnderscoreLongJmp(true);
72 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
73 // arguments are at least 4/8 bytes aligned.
74 bool isPPC64 = Subtarget.isPPC64();
75 setMinStackArgumentAlignment(isPPC64 ? 8:4);
77 // Set up the register classes.
78 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
79 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
80 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
82 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
84 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
86 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
88 // PowerPC has pre-inc load and store's.
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
93 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
100 if (Subtarget.useCRBits()) {
101 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103 if (isPPC64 || Subtarget.hasFPCVT()) {
104 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
105 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
106 isPPC64 ? MVT::i64 : MVT::i32);
107 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
108 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
109 isPPC64 ? MVT::i64 : MVT::i32);
111 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
112 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
115 // PowerPC does not support direct load / store of condition registers
116 setOperationAction(ISD::LOAD, MVT::i1, Custom);
117 setOperationAction(ISD::STORE, MVT::i1, Custom);
119 // FIXME: Remove this once the ANDI glue bug is fixed:
121 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
126 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
127 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
128 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
133 // This is used in the ppcf128->int sequence. Note it has different semantics
134 // from FP_ROUND: that rounds to nearest, this rounds to zero.
135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137 // We do not currently implement these libm ops for PowerPC.
138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145 // PowerPC has no SREM/UREM instructions
146 setOperationAction(ISD::SREM, MVT::i32, Expand);
147 setOperationAction(ISD::UREM, MVT::i32, Expand);
148 setOperationAction(ISD::SREM, MVT::i64, Expand);
149 setOperationAction(ISD::UREM, MVT::i64, Expand);
151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161 // We don't support sin/cos/sqrt/fmod/pow
162 setOperationAction(ISD::FSIN , MVT::f64, Expand);
163 setOperationAction(ISD::FCOS , MVT::f64, Expand);
164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165 setOperationAction(ISD::FREM , MVT::f64, Expand);
166 setOperationAction(ISD::FPOW , MVT::f64, Expand);
167 setOperationAction(ISD::FMA , MVT::f64, Legal);
168 setOperationAction(ISD::FSIN , MVT::f32, Expand);
169 setOperationAction(ISD::FCOS , MVT::f32, Expand);
170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171 setOperationAction(ISD::FREM , MVT::f32, Expand);
172 setOperationAction(ISD::FPOW , MVT::f32, Expand);
173 setOperationAction(ISD::FMA , MVT::f32, Legal);
175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177 // If we're enabling GP optimizations, use hardware square root
178 if (!Subtarget.hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath &&
180 Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
181 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183 if (!Subtarget.hasFSQRT() &&
184 !(TM.Options.UnsafeFPMath &&
185 Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
186 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188 if (Subtarget.hasFCPSGN()) {
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
196 if (Subtarget.hasFPRND()) {
197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200 setOperationAction(ISD::FROUND, MVT::f64, Legal);
202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205 setOperationAction(ISD::FROUND, MVT::f32, Legal);
208 // PowerPC does not have BSWAP, CTPOP or CTTZ
209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218 if (Subtarget.hasPOPCNTD()) {
219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
226 // PowerPC does not have ROTR
227 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
228 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
230 if (!Subtarget.useCRBits()) {
231 // PowerPC does not have Select
232 setOperationAction(ISD::SELECT, MVT::i32, Expand);
233 setOperationAction(ISD::SELECT, MVT::i64, Expand);
234 setOperationAction(ISD::SELECT, MVT::f32, Expand);
235 setOperationAction(ISD::SELECT, MVT::f64, Expand);
238 // PowerPC wants to turn select_cc of FP into fsel when possible.
239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 // PowerPC wants to optimize integer setcc a bit
243 if (!Subtarget.useCRBits())
244 setOperationAction(ISD::SETCC, MVT::i32, Custom);
246 // PowerPC does not have BRCOND which requires SetCC
247 if (!Subtarget.useCRBits())
248 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 // PowerPC does not have [U|S]INT_TO_FP
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264 // We cannot sextinreg(i1). Expand to shifts.
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269 // support continuation, user-level threading, and etc.. As a result, no
270 // other SjLj exception interfaces are implemented and please don't build
271 // your own exception handling based on them.
272 // LLVM/Clang supports zero-cost DWARF exception handling.
273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276 // We want to legalize GlobalAddress and ConstantPool nodes into the
277 // appropriate instructions to materialize the address.
278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
287 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
292 // TRAMPOLINE is custom lowered.
293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 if (Subtarget.isSVR4ABI()) {
301 // VAARG always uses double-word chunks, so promote anything smaller.
302 setOperationAction(ISD::VAARG, MVT::i1, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i8, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i16, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i32, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::Other, Expand);
312 // VAARG is custom lowered with the 32-bit SVR4 ABI.
313 setOperationAction(ISD::VAARG, MVT::Other, Custom);
314 setOperationAction(ISD::VAARG, MVT::i64, Custom);
317 setOperationAction(ISD::VAARG, MVT::Other, Expand);
319 if (Subtarget.isSVR4ABI() && !isPPC64)
320 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
323 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
325 // Use the default implementation.
326 setOperationAction(ISD::VAEND , MVT::Other, Expand);
327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
332 // We want to custom lower some of our intrinsics.
333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335 // To handle counter-based loop conditions.
336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338 // Comparisons that require checking two conditions.
339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352 if (Subtarget.has64BitSupport()) {
353 // They also have instructions for converting between i64 and fp.
354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358 // This is just the low 32 bits of a (signed) fp->i64 conversion.
359 // We cannot do this with Promote because i64 is not a legal type.
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
369 // With the instructions enabled under FPCVT, we can do everything.
370 if (Subtarget.hasFPCVT()) {
371 if (Subtarget.has64BitSupport()) {
372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
384 if (Subtarget.use64BitRegs()) {
385 // 64-bit PowerPC implementations can support i64 types directly
386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389 // 64-bit PowerPC wants to expand i128 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394 // 32-bit PowerPC wants to expand i64 shifts itself.
395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
400 if (Subtarget.hasAltivec()) {
401 // First set operation action for all vector types to expand. Then we
402 // will selectively turn on ones that can be effectively codegen'd.
403 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
405 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
407 // add/sub are legal for all supported vector VT's.
408 setOperationAction(ISD::ADD , VT, Legal);
409 setOperationAction(ISD::SUB , VT, Legal);
411 // We promote all shuffles to v16i8.
412 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
413 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
415 // We promote all non-typed operations to v4i32.
416 setOperationAction(ISD::AND , VT, Promote);
417 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
418 setOperationAction(ISD::OR , VT, Promote);
419 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
420 setOperationAction(ISD::XOR , VT, Promote);
421 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
422 setOperationAction(ISD::LOAD , VT, Promote);
423 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
424 setOperationAction(ISD::SELECT, VT, Promote);
425 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
426 setOperationAction(ISD::STORE, VT, Promote);
427 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
429 // No other operations are legal.
430 setOperationAction(ISD::MUL , VT, Expand);
431 setOperationAction(ISD::SDIV, VT, Expand);
432 setOperationAction(ISD::SREM, VT, Expand);
433 setOperationAction(ISD::UDIV, VT, Expand);
434 setOperationAction(ISD::UREM, VT, Expand);
435 setOperationAction(ISD::FDIV, VT, Expand);
436 setOperationAction(ISD::FREM, VT, Expand);
437 setOperationAction(ISD::FNEG, VT, Expand);
438 setOperationAction(ISD::FSQRT, VT, Expand);
439 setOperationAction(ISD::FLOG, VT, Expand);
440 setOperationAction(ISD::FLOG10, VT, Expand);
441 setOperationAction(ISD::FLOG2, VT, Expand);
442 setOperationAction(ISD::FEXP, VT, Expand);
443 setOperationAction(ISD::FEXP2, VT, Expand);
444 setOperationAction(ISD::FSIN, VT, Expand);
445 setOperationAction(ISD::FCOS, VT, Expand);
446 setOperationAction(ISD::FABS, VT, Expand);
447 setOperationAction(ISD::FPOWI, VT, Expand);
448 setOperationAction(ISD::FFLOOR, VT, Expand);
449 setOperationAction(ISD::FCEIL, VT, Expand);
450 setOperationAction(ISD::FTRUNC, VT, Expand);
451 setOperationAction(ISD::FRINT, VT, Expand);
452 setOperationAction(ISD::FNEARBYINT, VT, Expand);
453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
454 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
455 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
456 setOperationAction(ISD::MULHU, VT, Expand);
457 setOperationAction(ISD::MULHS, VT, Expand);
458 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
459 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
460 setOperationAction(ISD::UDIVREM, VT, Expand);
461 setOperationAction(ISD::SDIVREM, VT, Expand);
462 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
463 setOperationAction(ISD::FPOW, VT, Expand);
464 setOperationAction(ISD::BSWAP, VT, Expand);
465 setOperationAction(ISD::CTPOP, VT, Expand);
466 setOperationAction(ISD::CTLZ, VT, Expand);
467 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
468 setOperationAction(ISD::CTTZ, VT, Expand);
469 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
470 setOperationAction(ISD::VSELECT, VT, Expand);
471 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
473 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
474 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
475 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
476 setTruncStoreAction(VT, InnerVT, Expand);
478 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
479 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
480 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
483 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
484 // with merges, splats, etc.
485 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
487 setOperationAction(ISD::AND , MVT::v4i32, Legal);
488 setOperationAction(ISD::OR , MVT::v4i32, Legal);
489 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
490 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
491 setOperationAction(ISD::SELECT, MVT::v4i32,
492 Subtarget.useCRBits() ? Legal : Expand);
493 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
494 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
495 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
496 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
497 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
498 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
499 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
500 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
501 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
503 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
504 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
505 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
506 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
508 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
509 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
511 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
512 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
513 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
516 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
517 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
518 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
520 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
521 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
523 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
524 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
525 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
526 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
528 // Altivec does not contain unordered floating-point compare instructions
529 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
530 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
531 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
532 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
534 if (Subtarget.hasVSX()) {
535 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
536 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
538 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
539 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
540 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
541 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
542 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
544 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
546 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
547 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
549 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
550 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
552 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
553 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
554 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
555 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
558 // Share the Altivec comparison restrictions.
559 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
560 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
561 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
562 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
564 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
565 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
567 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
569 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
571 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
572 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
574 // VSX v2i64 only supports non-arithmetic operations.
575 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
576 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
578 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
579 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
580 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
582 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
584 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
585 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
586 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
587 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
589 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
591 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
592 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
593 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
594 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
596 // Vector operation legalization checks the result type of
597 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
598 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
599 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
600 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
601 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
603 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
607 if (Subtarget.has64BitSupport()) {
608 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
609 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
612 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
613 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
614 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
615 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
617 setBooleanContents(ZeroOrOneBooleanContent);
618 // Altivec instructions set fields to all zeros or all ones.
619 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
622 // These libcalls are not available in 32-bit.
623 setLibcallName(RTLIB::SHL_I128, nullptr);
624 setLibcallName(RTLIB::SRL_I128, nullptr);
625 setLibcallName(RTLIB::SRA_I128, nullptr);
629 setStackPointerRegisterToSaveRestore(PPC::X1);
630 setExceptionPointerRegister(PPC::X3);
631 setExceptionSelectorRegister(PPC::X4);
633 setStackPointerRegisterToSaveRestore(PPC::R1);
634 setExceptionPointerRegister(PPC::R3);
635 setExceptionSelectorRegister(PPC::R4);
638 // We have target-specific dag combine patterns for the following nodes:
639 setTargetDAGCombine(ISD::SINT_TO_FP);
640 setTargetDAGCombine(ISD::LOAD);
641 setTargetDAGCombine(ISD::STORE);
642 setTargetDAGCombine(ISD::BR_CC);
643 if (Subtarget.useCRBits())
644 setTargetDAGCombine(ISD::BRCOND);
645 setTargetDAGCombine(ISD::BSWAP);
646 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
648 setTargetDAGCombine(ISD::SIGN_EXTEND);
649 setTargetDAGCombine(ISD::ZERO_EXTEND);
650 setTargetDAGCombine(ISD::ANY_EXTEND);
652 if (Subtarget.useCRBits()) {
653 setTargetDAGCombine(ISD::TRUNCATE);
654 setTargetDAGCombine(ISD::SETCC);
655 setTargetDAGCombine(ISD::SELECT_CC);
658 // Use reciprocal estimates.
659 if (TM.Options.UnsafeFPMath) {
660 setTargetDAGCombine(ISD::FDIV);
661 setTargetDAGCombine(ISD::FSQRT);
664 // Darwin long double math library functions have $LDBL128 appended.
665 if (Subtarget.isDarwin()) {
666 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
667 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
668 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
669 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
670 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
671 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
672 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
673 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
674 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
675 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
678 // With 32 condition bits, we don't need to sink (and duplicate) compares
679 // aggressively in CodeGenPrep.
680 if (Subtarget.useCRBits())
681 setHasMultipleConditionRegisters();
683 setMinFunctionAlignment(2);
684 if (Subtarget.isDarwin())
685 setPrefFunctionAlignment(4);
687 if (isPPC64 && Subtarget.isJITCodeModel())
688 // Temporary workaround for the inability of PPC64 JIT to handle jump
690 setSupportJumpTables(false);
692 setInsertFencesForAtomic(true);
694 if (Subtarget.enableMachineScheduler())
695 setSchedulingPreference(Sched::Source);
697 setSchedulingPreference(Sched::Hybrid);
699 computeRegisterProperties();
701 // The Freescale cores does better with aggressive inlining of memcpy and
702 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
703 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
704 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
705 MaxStoresPerMemset = 32;
706 MaxStoresPerMemsetOptSize = 16;
707 MaxStoresPerMemcpy = 32;
708 MaxStoresPerMemcpyOptSize = 8;
709 MaxStoresPerMemmove = 32;
710 MaxStoresPerMemmoveOptSize = 8;
712 setPrefFunctionAlignment(4);
716 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
717 /// the desired ByVal argument alignment.
718 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
719 unsigned MaxMaxAlign) {
720 if (MaxAlign == MaxMaxAlign)
722 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
723 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
725 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
727 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
728 unsigned EltAlign = 0;
729 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
730 if (EltAlign > MaxAlign)
732 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
733 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
734 unsigned EltAlign = 0;
735 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
736 if (EltAlign > MaxAlign)
738 if (MaxAlign == MaxMaxAlign)
744 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
745 /// function arguments in the caller parameter area.
746 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
747 // Darwin passes everything on 4 byte boundary.
748 if (Subtarget.isDarwin())
751 // 16byte and wider vectors are passed on 16byte boundary.
752 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
753 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
754 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
755 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
759 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
761 default: return nullptr;
762 case PPCISD::FSEL: return "PPCISD::FSEL";
763 case PPCISD::FCFID: return "PPCISD::FCFID";
764 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
765 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
766 case PPCISD::FRE: return "PPCISD::FRE";
767 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
768 case PPCISD::STFIWX: return "PPCISD::STFIWX";
769 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
770 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
771 case PPCISD::VPERM: return "PPCISD::VPERM";
772 case PPCISD::Hi: return "PPCISD::Hi";
773 case PPCISD::Lo: return "PPCISD::Lo";
774 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
775 case PPCISD::LOAD: return "PPCISD::LOAD";
776 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
777 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
778 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
779 case PPCISD::SRL: return "PPCISD::SRL";
780 case PPCISD::SRA: return "PPCISD::SRA";
781 case PPCISD::SHL: return "PPCISD::SHL";
782 case PPCISD::CALL: return "PPCISD::CALL";
783 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
784 case PPCISD::MTCTR: return "PPCISD::MTCTR";
785 case PPCISD::BCTRL: return "PPCISD::BCTRL";
786 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
787 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
788 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
789 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
790 case PPCISD::VCMP: return "PPCISD::VCMP";
791 case PPCISD::VCMPo: return "PPCISD::VCMPo";
792 case PPCISD::LBRX: return "PPCISD::LBRX";
793 case PPCISD::STBRX: return "PPCISD::STBRX";
794 case PPCISD::LARX: return "PPCISD::LARX";
795 case PPCISD::STCX: return "PPCISD::STCX";
796 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
797 case PPCISD::BDNZ: return "PPCISD::BDNZ";
798 case PPCISD::BDZ: return "PPCISD::BDZ";
799 case PPCISD::MFFS: return "PPCISD::MFFS";
800 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
801 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
802 case PPCISD::CR6SET: return "PPCISD::CR6SET";
803 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
804 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
805 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
806 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
807 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
808 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
809 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
810 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
811 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
812 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
813 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
814 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
815 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
816 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
817 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
818 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
819 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
820 case PPCISD::SC: return "PPCISD::SC";
824 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
826 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
827 return VT.changeVectorElementTypeToInteger();
830 //===----------------------------------------------------------------------===//
831 // Node matching predicates, for use by the tblgen matching code.
832 //===----------------------------------------------------------------------===//
834 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
835 static bool isFloatingPointZero(SDValue Op) {
836 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
837 return CFP->getValueAPF().isZero();
838 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
839 // Maybe this has already been legalized into the constant pool?
840 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
841 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
842 return CFP->getValueAPF().isZero();
847 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
848 /// true if Op is undef or if it matches the specified value.
849 static bool isConstantOrUndef(int Op, int Val) {
850 return Op < 0 || Op == Val;
853 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
854 /// VPKUHUM instruction.
855 /// The ShuffleKind distinguishes between big-endian operations with
856 /// two different inputs (0), either-endian operations with two identical
857 /// inputs (1), and little-endian operantion with two different inputs (2).
858 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
859 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
862 DAG.getTarget().getSubtargetImpl()->getDataLayout()->isLittleEndian();
863 if (ShuffleKind == 0) {
866 for (unsigned i = 0; i != 16; ++i)
867 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
869 } else if (ShuffleKind == 2) {
872 for (unsigned i = 0; i != 16; ++i)
873 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
875 } else if (ShuffleKind == 1) {
876 unsigned j = IsLE ? 0 : 1;
877 for (unsigned i = 0; i != 8; ++i)
878 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
879 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
885 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
886 /// VPKUWUM instruction.
887 /// The ShuffleKind distinguishes between big-endian operations with
888 /// two different inputs (0), either-endian operations with two identical
889 /// inputs (1), and little-endian operantion with two different inputs (2).
890 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
891 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
894 DAG.getTarget().getSubtargetImpl()->getDataLayout()->isLittleEndian();
895 if (ShuffleKind == 0) {
898 for (unsigned i = 0; i != 16; i += 2)
899 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
900 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
902 } else if (ShuffleKind == 2) {
905 for (unsigned i = 0; i != 16; i += 2)
906 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
907 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
909 } else if (ShuffleKind == 1) {
910 unsigned j = IsLE ? 0 : 2;
911 for (unsigned i = 0; i != 8; i += 2)
912 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
913 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
914 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
915 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
921 /// isVMerge - Common function, used to match vmrg* shuffles.
923 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
924 unsigned LHSStart, unsigned RHSStart) {
925 if (N->getValueType(0) != MVT::v16i8)
927 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
928 "Unsupported merge size!");
930 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
931 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
932 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
933 LHSStart+j+i*UnitSize) ||
934 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
935 RHSStart+j+i*UnitSize))
941 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
942 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
943 /// The ShuffleKind distinguishes between big-endian merges with two
944 /// different inputs (0), either-endian merges with two identical inputs (1),
945 /// and little-endian merges with two different inputs (2). For the latter,
946 /// the input operands are swapped (see PPCInstrAltivec.td).
947 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
948 unsigned ShuffleKind, SelectionDAG &DAG) {
949 if (DAG.getTarget().getSubtargetImpl()->getDataLayout()->isLittleEndian()) {
950 if (ShuffleKind == 1) // unary
951 return isVMerge(N, UnitSize, 0, 0);
952 else if (ShuffleKind == 2) // swapped
953 return isVMerge(N, UnitSize, 0, 16);
957 if (ShuffleKind == 1) // unary
958 return isVMerge(N, UnitSize, 8, 8);
959 else if (ShuffleKind == 0) // normal
960 return isVMerge(N, UnitSize, 8, 24);
966 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
967 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
968 /// The ShuffleKind distinguishes between big-endian merges with two
969 /// different inputs (0), either-endian merges with two identical inputs (1),
970 /// and little-endian merges with two different inputs (2). For the latter,
971 /// the input operands are swapped (see PPCInstrAltivec.td).
972 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
973 unsigned ShuffleKind, SelectionDAG &DAG) {
974 if (DAG.getTarget().getSubtargetImpl()->getDataLayout()->isLittleEndian()) {
975 if (ShuffleKind == 1) // unary
976 return isVMerge(N, UnitSize, 8, 8);
977 else if (ShuffleKind == 2) // swapped
978 return isVMerge(N, UnitSize, 8, 24);
982 if (ShuffleKind == 1) // unary
983 return isVMerge(N, UnitSize, 0, 0);
984 else if (ShuffleKind == 0) // normal
985 return isVMerge(N, UnitSize, 0, 16);
992 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
993 /// amount, otherwise return -1.
994 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary, SelectionDAG &DAG) {
995 if (N->getValueType(0) != MVT::v16i8)
998 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1000 // Find the first non-undef value in the shuffle mask.
1002 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1005 if (i == 16) return -1; // all undef.
1007 // Otherwise, check to see if the rest of the elements are consecutively
1008 // numbered from this value.
1009 unsigned ShiftAmt = SVOp->getMaskElt(i);
1010 if (ShiftAmt < i) return -1;
1015 // Check the rest of the elements to see if they are consecutive.
1016 for (++i; i != 16; ++i)
1017 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1020 // Check the rest of the elements to see if they are consecutive.
1021 for (++i; i != 16; ++i)
1022 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1029 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1030 /// specifies a splat of a single element that is suitable for input to
1031 /// VSPLTB/VSPLTH/VSPLTW.
1032 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1033 assert(N->getValueType(0) == MVT::v16i8 &&
1034 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1036 // This is a splat operation if each element of the permute is the same, and
1037 // if the value doesn't reference the second vector.
1038 unsigned ElementBase = N->getMaskElt(0);
1040 // FIXME: Handle UNDEF elements too!
1041 if (ElementBase >= 16)
1044 // Check that the indices are consecutive, in the case of a multi-byte element
1045 // splatted with a v16i8 mask.
1046 for (unsigned i = 1; i != EltSize; ++i)
1047 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1050 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1051 if (N->getMaskElt(i) < 0) continue;
1052 for (unsigned j = 0; j != EltSize; ++j)
1053 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1059 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1061 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1062 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1064 APInt APVal, APUndef;
1068 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1069 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1070 return CFP->getValueAPF().isNegZero();
1075 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1076 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1077 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1078 SelectionDAG &DAG) {
1079 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1080 assert(isSplatShuffleMask(SVOp, EltSize));
1081 if (DAG.getTarget().getSubtargetImpl()->getDataLayout()->isLittleEndian())
1082 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1084 return SVOp->getMaskElt(0) / EltSize;
1087 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1088 /// by using a vspltis[bhw] instruction of the specified element size, return
1089 /// the constant being splatted. The ByteSize field indicates the number of
1090 /// bytes of each element [124] -> [bhw].
1091 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1092 SDValue OpVal(nullptr, 0);
1094 // If ByteSize of the splat is bigger than the element size of the
1095 // build_vector, then we have a case where we are checking for a splat where
1096 // multiple elements of the buildvector are folded together into a single
1097 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1098 unsigned EltSize = 16/N->getNumOperands();
1099 if (EltSize < ByteSize) {
1100 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1101 SDValue UniquedVals[4];
1102 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1104 // See if all of the elements in the buildvector agree across.
1105 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1106 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1107 // If the element isn't a constant, bail fully out.
1108 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1111 if (!UniquedVals[i&(Multiple-1)].getNode())
1112 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1113 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1114 return SDValue(); // no match.
1117 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1118 // either constant or undef values that are identical for each chunk. See
1119 // if these chunks can form into a larger vspltis*.
1121 // Check to see if all of the leading entries are either 0 or -1. If
1122 // neither, then this won't fit into the immediate field.
1123 bool LeadingZero = true;
1124 bool LeadingOnes = true;
1125 for (unsigned i = 0; i != Multiple-1; ++i) {
1126 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1128 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1129 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1131 // Finally, check the least significant entry.
1133 if (!UniquedVals[Multiple-1].getNode())
1134 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1135 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1137 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1140 if (!UniquedVals[Multiple-1].getNode())
1141 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1142 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1143 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1144 return DAG.getTargetConstant(Val, MVT::i32);
1150 // Check to see if this buildvec has a single non-undef value in its elements.
1151 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1152 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1153 if (!OpVal.getNode())
1154 OpVal = N->getOperand(i);
1155 else if (OpVal != N->getOperand(i))
1159 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1161 unsigned ValSizeInBytes = EltSize;
1163 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1164 Value = CN->getZExtValue();
1165 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1166 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1167 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1170 // If the splat value is larger than the element value, then we can never do
1171 // this splat. The only case that we could fit the replicated bits into our
1172 // immediate field for would be zero, and we prefer to use vxor for it.
1173 if (ValSizeInBytes < ByteSize) return SDValue();
1175 // If the element value is larger than the splat value, cut it in half and
1176 // check to see if the two halves are equal. Continue doing this until we
1177 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1178 while (ValSizeInBytes > ByteSize) {
1179 ValSizeInBytes >>= 1;
1181 // If the top half equals the bottom half, we're still ok.
1182 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1183 (Value & ((1 << (8*ValSizeInBytes))-1)))
1187 // Properly sign extend the value.
1188 int MaskVal = SignExtend32(Value, ByteSize * 8);
1190 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1191 if (MaskVal == 0) return SDValue();
1193 // Finally, if this value fits in a 5 bit sext field, return it
1194 if (SignExtend32<5>(MaskVal) == MaskVal)
1195 return DAG.getTargetConstant(MaskVal, MVT::i32);
1199 //===----------------------------------------------------------------------===//
1200 // Addressing Mode Selection
1201 //===----------------------------------------------------------------------===//
1203 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1204 /// or 64-bit immediate, and if the value can be accurately represented as a
1205 /// sign extension from a 16-bit value. If so, this returns true and the
1207 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1208 if (!isa<ConstantSDNode>(N))
1211 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1212 if (N->getValueType(0) == MVT::i32)
1213 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1215 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1217 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1218 return isIntS16Immediate(Op.getNode(), Imm);
1222 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1223 /// can be represented as an indexed [r+r] operation. Returns false if it
1224 /// can be more efficiently represented with [r+imm].
1225 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1227 SelectionDAG &DAG) const {
1229 if (N.getOpcode() == ISD::ADD) {
1230 if (isIntS16Immediate(N.getOperand(1), imm))
1231 return false; // r+i
1232 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1233 return false; // r+i
1235 Base = N.getOperand(0);
1236 Index = N.getOperand(1);
1238 } else if (N.getOpcode() == ISD::OR) {
1239 if (isIntS16Immediate(N.getOperand(1), imm))
1240 return false; // r+i can fold it if we can.
1242 // If this is an or of disjoint bitfields, we can codegen this as an add
1243 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1245 APInt LHSKnownZero, LHSKnownOne;
1246 APInt RHSKnownZero, RHSKnownOne;
1247 DAG.computeKnownBits(N.getOperand(0),
1248 LHSKnownZero, LHSKnownOne);
1250 if (LHSKnownZero.getBoolValue()) {
1251 DAG.computeKnownBits(N.getOperand(1),
1252 RHSKnownZero, RHSKnownOne);
1253 // If all of the bits are known zero on the LHS or RHS, the add won't
1255 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1256 Base = N.getOperand(0);
1257 Index = N.getOperand(1);
1266 // If we happen to be doing an i64 load or store into a stack slot that has
1267 // less than a 4-byte alignment, then the frame-index elimination may need to
1268 // use an indexed load or store instruction (because the offset may not be a
1269 // multiple of 4). The extra register needed to hold the offset comes from the
1270 // register scavenger, and it is possible that the scavenger will need to use
1271 // an emergency spill slot. As a result, we need to make sure that a spill slot
1272 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1274 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1275 // FIXME: This does not handle the LWA case.
1279 // NOTE: We'll exclude negative FIs here, which come from argument
1280 // lowering, because there are no known test cases triggering this problem
1281 // using packed structures (or similar). We can remove this exclusion if
1282 // we find such a test case. The reason why this is so test-case driven is
1283 // because this entire 'fixup' is only to prevent crashes (from the
1284 // register scavenger) on not-really-valid inputs. For example, if we have:
1286 // %b = bitcast i1* %a to i64*
1287 // store i64* a, i64 b
1288 // then the store should really be marked as 'align 1', but is not. If it
1289 // were marked as 'align 1' then the indexed form would have been
1290 // instruction-selected initially, and the problem this 'fixup' is preventing
1291 // won't happen regardless.
1295 MachineFunction &MF = DAG.getMachineFunction();
1296 MachineFrameInfo *MFI = MF.getFrameInfo();
1298 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1302 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1303 FuncInfo->setHasNonRISpills();
1306 /// Returns true if the address N can be represented by a base register plus
1307 /// a signed 16-bit displacement [r+imm], and if it is not better
1308 /// represented as reg+reg. If Aligned is true, only accept displacements
1309 /// suitable for STD and friends, i.e. multiples of 4.
1310 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1313 bool Aligned) const {
1314 // FIXME dl should come from parent load or store, not from address
1316 // If this can be more profitably realized as r+r, fail.
1317 if (SelectAddressRegReg(N, Disp, Base, DAG))
1320 if (N.getOpcode() == ISD::ADD) {
1322 if (isIntS16Immediate(N.getOperand(1), imm) &&
1323 (!Aligned || (imm & 3) == 0)) {
1324 Disp = DAG.getTargetConstant(imm, N.getValueType());
1325 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1326 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1327 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1329 Base = N.getOperand(0);
1331 return true; // [r+i]
1332 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1333 // Match LOAD (ADD (X, Lo(G))).
1334 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1335 && "Cannot handle constant offsets yet!");
1336 Disp = N.getOperand(1).getOperand(0); // The global address.
1337 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1338 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1339 Disp.getOpcode() == ISD::TargetConstantPool ||
1340 Disp.getOpcode() == ISD::TargetJumpTable);
1341 Base = N.getOperand(0);
1342 return true; // [&g+r]
1344 } else if (N.getOpcode() == ISD::OR) {
1346 if (isIntS16Immediate(N.getOperand(1), imm) &&
1347 (!Aligned || (imm & 3) == 0)) {
1348 // If this is an or of disjoint bitfields, we can codegen this as an add
1349 // (for better address arithmetic) if the LHS and RHS of the OR are
1350 // provably disjoint.
1351 APInt LHSKnownZero, LHSKnownOne;
1352 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1354 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1355 // If all of the bits are known zero on the LHS or RHS, the add won't
1357 if (FrameIndexSDNode *FI =
1358 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1359 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1360 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1362 Base = N.getOperand(0);
1364 Disp = DAG.getTargetConstant(imm, N.getValueType());
1368 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1369 // Loading from a constant address.
1371 // If this address fits entirely in a 16-bit sext immediate field, codegen
1374 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1375 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1376 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1377 CN->getValueType(0));
1381 // Handle 32-bit sext immediates with LIS + addr mode.
1382 if ((CN->getValueType(0) == MVT::i32 ||
1383 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1384 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1385 int Addr = (int)CN->getZExtValue();
1387 // Otherwise, break this down into an LIS + disp.
1388 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1390 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1391 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1392 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1397 Disp = DAG.getTargetConstant(0, getPointerTy());
1398 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1399 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1400 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1403 return true; // [r+0]
1406 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1407 /// represented as an indexed [r+r] operation.
1408 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1410 SelectionDAG &DAG) const {
1411 // Check to see if we can easily represent this as an [r+r] address. This
1412 // will fail if it thinks that the address is more profitably represented as
1413 // reg+imm, e.g. where imm = 0.
1414 if (SelectAddressRegReg(N, Base, Index, DAG))
1417 // If the operand is an addition, always emit this as [r+r], since this is
1418 // better (for code size, and execution, as the memop does the add for free)
1419 // than emitting an explicit add.
1420 if (N.getOpcode() == ISD::ADD) {
1421 Base = N.getOperand(0);
1422 Index = N.getOperand(1);
1426 // Otherwise, do it the hard way, using R0 as the base register.
1427 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1433 /// getPreIndexedAddressParts - returns true by value, base pointer and
1434 /// offset pointer and addressing mode by reference if the node's address
1435 /// can be legally represented as pre-indexed load / store address.
1436 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1438 ISD::MemIndexedMode &AM,
1439 SelectionDAG &DAG) const {
1440 if (DisablePPCPreinc) return false;
1446 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1447 Ptr = LD->getBasePtr();
1448 VT = LD->getMemoryVT();
1449 Alignment = LD->getAlignment();
1450 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1451 Ptr = ST->getBasePtr();
1452 VT = ST->getMemoryVT();
1453 Alignment = ST->getAlignment();
1458 // PowerPC doesn't have preinc load/store instructions for vectors.
1462 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1464 // Common code will reject creating a pre-inc form if the base pointer
1465 // is a frame index, or if N is a store and the base pointer is either
1466 // the same as or a predecessor of the value being stored. Check for
1467 // those situations here, and try with swapped Base/Offset instead.
1470 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1473 SDValue Val = cast<StoreSDNode>(N)->getValue();
1474 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1479 std::swap(Base, Offset);
1485 // LDU/STU can only handle immediates that are a multiple of 4.
1486 if (VT != MVT::i64) {
1487 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1490 // LDU/STU need an address with at least 4-byte alignment.
1494 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1498 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1499 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1500 // sext i32 to i64 when addr mode is r+i.
1501 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1502 LD->getExtensionType() == ISD::SEXTLOAD &&
1503 isa<ConstantSDNode>(Offset))
1511 //===----------------------------------------------------------------------===//
1512 // LowerOperation implementation
1513 //===----------------------------------------------------------------------===//
1515 /// GetLabelAccessInfo - Return true if we should reference labels using a
1516 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1517 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1518 unsigned &LoOpFlags,
1519 const GlobalValue *GV = nullptr) {
1520 HiOpFlags = PPCII::MO_HA;
1521 LoOpFlags = PPCII::MO_LO;
1523 // Don't use the pic base if not in PIC relocation model.
1524 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1527 HiOpFlags |= PPCII::MO_PIC_FLAG;
1528 LoOpFlags |= PPCII::MO_PIC_FLAG;
1531 // If this is a reference to a global value that requires a non-lazy-ptr, make
1532 // sure that instruction lowering adds it.
1533 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1534 HiOpFlags |= PPCII::MO_NLP_FLAG;
1535 LoOpFlags |= PPCII::MO_NLP_FLAG;
1537 if (GV->hasHiddenVisibility()) {
1538 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1539 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1546 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1547 SelectionDAG &DAG) {
1548 EVT PtrVT = HiPart.getValueType();
1549 SDValue Zero = DAG.getConstant(0, PtrVT);
1552 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1553 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1555 // With PIC, the first instruction is actually "GR+hi(&G)".
1557 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1558 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1560 // Generate non-pic code that has direct accesses to the constant pool.
1561 // The address of the global is just (hi(&g)+lo(&g)).
1562 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1565 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1566 SelectionDAG &DAG) const {
1567 EVT PtrVT = Op.getValueType();
1568 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1569 const Constant *C = CP->getConstVal();
1571 // 64-bit SVR4 ABI code is always position-independent.
1572 // The actual address of the GlobalValue is stored in the TOC.
1573 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1574 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1575 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1576 DAG.getRegister(PPC::X2, MVT::i64));
1579 unsigned MOHiFlag, MOLoFlag;
1580 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1582 if (isPIC && Subtarget.isSVR4ABI()) {
1583 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1584 PPCII::MO_PIC_FLAG);
1586 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1587 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1591 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1593 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1594 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1597 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1598 EVT PtrVT = Op.getValueType();
1599 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1601 // 64-bit SVR4 ABI code is always position-independent.
1602 // The actual address of the GlobalValue is stored in the TOC.
1603 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1604 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1605 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1606 DAG.getRegister(PPC::X2, MVT::i64));
1609 unsigned MOHiFlag, MOLoFlag;
1610 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1612 if (isPIC && Subtarget.isSVR4ABI()) {
1613 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1614 PPCII::MO_PIC_FLAG);
1616 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1617 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1620 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1621 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1622 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1625 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1626 SelectionDAG &DAG) const {
1627 EVT PtrVT = Op.getValueType();
1629 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1631 unsigned MOHiFlag, MOLoFlag;
1632 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1633 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1634 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1635 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1638 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1639 SelectionDAG &DAG) const {
1641 // FIXME: TLS addresses currently use medium model code sequences,
1642 // which is the most useful form. Eventually support for small and
1643 // large models could be added if users need it, at the cost of
1644 // additional complexity.
1645 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1647 const GlobalValue *GV = GA->getGlobal();
1648 EVT PtrVT = getPointerTy();
1649 bool is64bit = Subtarget.isPPC64();
1651 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1653 if (Model == TLSModel::LocalExec) {
1654 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1655 PPCII::MO_TPREL_HA);
1656 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1657 PPCII::MO_TPREL_LO);
1658 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1659 is64bit ? MVT::i64 : MVT::i32);
1660 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1661 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1664 if (Model == TLSModel::InitialExec) {
1665 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1666 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1670 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1671 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1672 PtrVT, GOTReg, TGA);
1674 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1675 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1676 PtrVT, TGA, GOTPtr);
1677 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1680 if (Model == TLSModel::GeneralDynamic) {
1681 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1684 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1685 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1688 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1690 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1693 // We need a chain node, and don't have one handy. The underlying
1694 // call has no side effects, so using the function entry node
1696 SDValue Chain = DAG.getEntryNode();
1697 Chain = DAG.getCopyToReg(Chain, dl,
1698 is64bit ? PPC::X3 : PPC::R3, GOTEntry);
1699 SDValue ParmReg = DAG.getRegister(is64bit ? PPC::X3 : PPC::R3,
1700 is64bit ? MVT::i64 : MVT::i32);
1701 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1702 PtrVT, ParmReg, TGA);
1703 // The return value from GET_TLS_ADDR really is in X3 already, but
1704 // some hacks are needed here to tie everything together. The extra
1705 // copies dissolve during subsequent transforms.
1706 Chain = DAG.getCopyToReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, TLSAddr);
1707 return DAG.getCopyFromReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, PtrVT);
1710 if (Model == TLSModel::LocalDynamic) {
1711 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1714 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1715 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1718 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1720 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1723 // We need a chain node, and don't have one handy. The underlying
1724 // call has no side effects, so using the function entry node
1726 SDValue Chain = DAG.getEntryNode();
1727 Chain = DAG.getCopyToReg(Chain, dl,
1728 is64bit ? PPC::X3 : PPC::R3, GOTEntry);
1729 SDValue ParmReg = DAG.getRegister(is64bit ? PPC::X3 : PPC::R3,
1730 is64bit ? MVT::i64 : MVT::i32);
1731 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1732 PtrVT, ParmReg, TGA);
1733 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1734 // some hacks are needed here to tie everything together. The extra
1735 // copies dissolve during subsequent transforms.
1736 Chain = DAG.getCopyToReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, TLSAddr);
1737 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1738 Chain, ParmReg, TGA);
1739 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1742 llvm_unreachable("Unknown TLS model!");
1745 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1746 SelectionDAG &DAG) const {
1747 EVT PtrVT = Op.getValueType();
1748 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1750 const GlobalValue *GV = GSDN->getGlobal();
1752 // 64-bit SVR4 ABI code is always position-independent.
1753 // The actual address of the GlobalValue is stored in the TOC.
1754 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1755 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1756 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1757 DAG.getRegister(PPC::X2, MVT::i64));
1760 unsigned MOHiFlag, MOLoFlag;
1761 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1763 if (isPIC && Subtarget.isSVR4ABI()) {
1764 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1766 PPCII::MO_PIC_FLAG);
1767 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1768 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1772 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1774 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1776 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1778 // If the global reference is actually to a non-lazy-pointer, we have to do an
1779 // extra load to get the address of the global.
1780 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1781 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1782 false, false, false, 0);
1786 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1787 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1790 if (Op.getValueType() == MVT::v2i64) {
1791 // When the operands themselves are v2i64 values, we need to do something
1792 // special because VSX has no underlying comparison operations for these.
1793 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1794 // Equality can be handled by casting to the legal type for Altivec
1795 // comparisons, everything else needs to be expanded.
1796 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1797 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1798 DAG.getSetCC(dl, MVT::v4i32,
1799 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1800 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1807 // We handle most of these in the usual way.
1811 // If we're comparing for equality to zero, expose the fact that this is
1812 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1813 // fold the new nodes.
1814 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1815 if (C->isNullValue() && CC == ISD::SETEQ) {
1816 EVT VT = Op.getOperand(0).getValueType();
1817 SDValue Zext = Op.getOperand(0);
1818 if (VT.bitsLT(MVT::i32)) {
1820 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1822 unsigned Log2b = Log2_32(VT.getSizeInBits());
1823 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1824 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1825 DAG.getConstant(Log2b, MVT::i32));
1826 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1828 // Leave comparisons against 0 and -1 alone for now, since they're usually
1829 // optimized. FIXME: revisit this when we can custom lower all setcc
1831 if (C->isAllOnesValue() || C->isNullValue())
1835 // If we have an integer seteq/setne, turn it into a compare against zero
1836 // by xor'ing the rhs with the lhs, which is faster than setting a
1837 // condition register, reading it back out, and masking the correct bit. The
1838 // normal approach here uses sub to do this instead of xor. Using xor exposes
1839 // the result to other bit-twiddling opportunities.
1840 EVT LHSVT = Op.getOperand(0).getValueType();
1841 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1842 EVT VT = Op.getValueType();
1843 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1845 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1850 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1851 const PPCSubtarget &Subtarget) const {
1852 SDNode *Node = Op.getNode();
1853 EVT VT = Node->getValueType(0);
1854 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1855 SDValue InChain = Node->getOperand(0);
1856 SDValue VAListPtr = Node->getOperand(1);
1857 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1860 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1863 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1864 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1865 false, false, false, 0);
1866 InChain = GprIndex.getValue(1);
1868 if (VT == MVT::i64) {
1869 // Check if GprIndex is even
1870 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1871 DAG.getConstant(1, MVT::i32));
1872 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1873 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1874 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1875 DAG.getConstant(1, MVT::i32));
1876 // Align GprIndex to be even if it isn't
1877 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1881 // fpr index is 1 byte after gpr
1882 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1883 DAG.getConstant(1, MVT::i32));
1886 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1887 FprPtr, MachinePointerInfo(SV), MVT::i8,
1888 false, false, false, 0);
1889 InChain = FprIndex.getValue(1);
1891 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1892 DAG.getConstant(8, MVT::i32));
1894 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1895 DAG.getConstant(4, MVT::i32));
1898 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1899 MachinePointerInfo(), false, false,
1901 InChain = OverflowArea.getValue(1);
1903 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1904 MachinePointerInfo(), false, false,
1906 InChain = RegSaveArea.getValue(1);
1908 // select overflow_area if index > 8
1909 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1910 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1912 // adjustment constant gpr_index * 4/8
1913 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1914 VT.isInteger() ? GprIndex : FprIndex,
1915 DAG.getConstant(VT.isInteger() ? 4 : 8,
1918 // OurReg = RegSaveArea + RegConstant
1919 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1922 // Floating types are 32 bytes into RegSaveArea
1923 if (VT.isFloatingPoint())
1924 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1925 DAG.getConstant(32, MVT::i32));
1927 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1928 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1929 VT.isInteger() ? GprIndex : FprIndex,
1930 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1933 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1934 VT.isInteger() ? VAListPtr : FprPtr,
1935 MachinePointerInfo(SV),
1936 MVT::i8, false, false, 0);
1938 // determine if we should load from reg_save_area or overflow_area
1939 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1941 // increase overflow_area by 4/8 if gpr/fpr > 8
1942 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1943 DAG.getConstant(VT.isInteger() ? 4 : 8,
1946 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1949 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1951 MachinePointerInfo(),
1952 MVT::i32, false, false, 0);
1954 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1955 false, false, false, 0);
1958 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1959 const PPCSubtarget &Subtarget) const {
1960 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1962 // We have to copy the entire va_list struct:
1963 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1964 return DAG.getMemcpy(Op.getOperand(0), Op,
1965 Op.getOperand(1), Op.getOperand(2),
1966 DAG.getConstant(12, MVT::i32), 8, false, true,
1967 MachinePointerInfo(), MachinePointerInfo());
1970 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1971 SelectionDAG &DAG) const {
1972 return Op.getOperand(0);
1975 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1976 SelectionDAG &DAG) const {
1977 SDValue Chain = Op.getOperand(0);
1978 SDValue Trmp = Op.getOperand(1); // trampoline
1979 SDValue FPtr = Op.getOperand(2); // nested function
1980 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1983 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1984 bool isPPC64 = (PtrVT == MVT::i64);
1986 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1989 TargetLowering::ArgListTy Args;
1990 TargetLowering::ArgListEntry Entry;
1992 Entry.Ty = IntPtrTy;
1993 Entry.Node = Trmp; Args.push_back(Entry);
1995 // TrampSize == (isPPC64 ? 48 : 40);
1996 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1997 isPPC64 ? MVT::i64 : MVT::i32);
1998 Args.push_back(Entry);
2000 Entry.Node = FPtr; Args.push_back(Entry);
2001 Entry.Node = Nest; Args.push_back(Entry);
2003 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2004 TargetLowering::CallLoweringInfo CLI(DAG);
2005 CLI.setDebugLoc(dl).setChain(Chain)
2006 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2007 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2008 std::move(Args), 0);
2010 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2011 return CallResult.second;
2014 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2015 const PPCSubtarget &Subtarget) const {
2016 MachineFunction &MF = DAG.getMachineFunction();
2017 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2021 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2022 // vastart just stores the address of the VarArgsFrameIndex slot into the
2023 // memory location argument.
2024 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2025 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2026 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2027 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2028 MachinePointerInfo(SV),
2032 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2033 // We suppose the given va_list is already allocated.
2036 // char gpr; /* index into the array of 8 GPRs
2037 // * stored in the register save area
2038 // * gpr=0 corresponds to r3,
2039 // * gpr=1 to r4, etc.
2041 // char fpr; /* index into the array of 8 FPRs
2042 // * stored in the register save area
2043 // * fpr=0 corresponds to f1,
2044 // * fpr=1 to f2, etc.
2046 // char *overflow_arg_area;
2047 // /* location on stack that holds
2048 // * the next overflow argument
2050 // char *reg_save_area;
2051 // /* where r3:r10 and f1:f8 (if saved)
2057 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2058 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2061 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2063 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2065 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2068 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2069 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2071 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2072 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2074 uint64_t FPROffset = 1;
2075 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2077 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2079 // Store first byte : number of int regs
2080 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2082 MachinePointerInfo(SV),
2083 MVT::i8, false, false, 0);
2084 uint64_t nextOffset = FPROffset;
2085 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2088 // Store second byte : number of float regs
2089 SDValue secondStore =
2090 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2091 MachinePointerInfo(SV, nextOffset), MVT::i8,
2093 nextOffset += StackOffset;
2094 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2096 // Store second word : arguments given on stack
2097 SDValue thirdStore =
2098 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2099 MachinePointerInfo(SV, nextOffset),
2101 nextOffset += FrameOffset;
2102 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2104 // Store third word : arguments given in registers
2105 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2106 MachinePointerInfo(SV, nextOffset),
2111 #include "PPCGenCallingConv.inc"
2113 // Function whose sole purpose is to kill compiler warnings
2114 // stemming from unused functions included from PPCGenCallingConv.inc.
2115 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2116 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2119 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2120 CCValAssign::LocInfo &LocInfo,
2121 ISD::ArgFlagsTy &ArgFlags,
2126 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2128 CCValAssign::LocInfo &LocInfo,
2129 ISD::ArgFlagsTy &ArgFlags,
2131 static const MCPhysReg ArgRegs[] = {
2132 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2133 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2135 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2137 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2139 // Skip one register if the first unallocated register has an even register
2140 // number and there are still argument registers available which have not been
2141 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2142 // need to skip a register if RegNum is odd.
2143 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2144 State.AllocateReg(ArgRegs[RegNum]);
2147 // Always return false here, as this function only makes sure that the first
2148 // unallocated register has an odd register number and does not actually
2149 // allocate a register for the current argument.
2153 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2155 CCValAssign::LocInfo &LocInfo,
2156 ISD::ArgFlagsTy &ArgFlags,
2158 static const MCPhysReg ArgRegs[] = {
2159 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2163 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2165 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2167 // If there is only one Floating-point register left we need to put both f64
2168 // values of a split ppc_fp128 value on the stack.
2169 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2170 State.AllocateReg(ArgRegs[RegNum]);
2173 // Always return false here, as this function only makes sure that the two f64
2174 // values a ppc_fp128 value is split into are both passed in registers or both
2175 // passed on the stack and does not actually allocate a register for the
2176 // current argument.
2180 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2182 static const MCPhysReg *GetFPR() {
2183 static const MCPhysReg FPR[] = {
2184 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2185 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2191 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2193 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2194 unsigned PtrByteSize) {
2195 unsigned ArgSize = ArgVT.getStoreSize();
2196 if (Flags.isByVal())
2197 ArgSize = Flags.getByValSize();
2199 // Round up to multiples of the pointer size, except for array members,
2200 // which are always packed.
2201 if (!Flags.isInConsecutiveRegs())
2202 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2207 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2209 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2210 ISD::ArgFlagsTy Flags,
2211 unsigned PtrByteSize) {
2212 unsigned Align = PtrByteSize;
2214 // Altivec parameters are padded to a 16 byte boundary.
2215 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2216 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2217 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2220 // ByVal parameters are aligned as requested.
2221 if (Flags.isByVal()) {
2222 unsigned BVAlign = Flags.getByValAlign();
2223 if (BVAlign > PtrByteSize) {
2224 if (BVAlign % PtrByteSize != 0)
2226 "ByVal alignment is not a multiple of the pointer size");
2232 // Array members are always packed to their original alignment.
2233 if (Flags.isInConsecutiveRegs()) {
2234 // If the array member was split into multiple registers, the first
2235 // needs to be aligned to the size of the full type. (Except for
2236 // ppcf128, which is only aligned as its f64 components.)
2237 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2238 Align = OrigVT.getStoreSize();
2240 Align = ArgVT.getStoreSize();
2246 /// CalculateStackSlotUsed - Return whether this argument will use its
2247 /// stack slot (instead of being passed in registers). ArgOffset,
2248 /// AvailableFPRs, and AvailableVRs must hold the current argument
2249 /// position, and will be updated to account for this argument.
2250 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2251 ISD::ArgFlagsTy Flags,
2252 unsigned PtrByteSize,
2253 unsigned LinkageSize,
2254 unsigned ParamAreaSize,
2255 unsigned &ArgOffset,
2256 unsigned &AvailableFPRs,
2257 unsigned &AvailableVRs) {
2258 bool UseMemory = false;
2260 // Respect alignment of argument on the stack.
2262 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2263 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2264 // If there's no space left in the argument save area, we must
2265 // use memory (this check also catches zero-sized arguments).
2266 if (ArgOffset >= LinkageSize + ParamAreaSize)
2269 // Allocate argument on the stack.
2270 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2271 if (Flags.isInConsecutiveRegsLast())
2272 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2273 // If we overran the argument save area, we must use memory
2274 // (this check catches arguments passed partially in memory)
2275 if (ArgOffset > LinkageSize + ParamAreaSize)
2278 // However, if the argument is actually passed in an FPR or a VR,
2279 // we don't use memory after all.
2280 if (!Flags.isByVal()) {
2281 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2282 if (AvailableFPRs > 0) {
2286 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2287 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2288 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2289 if (AvailableVRs > 0) {
2298 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2299 /// ensure minimum alignment required for target.
2300 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2301 unsigned NumBytes) {
2302 unsigned TargetAlign =
2303 Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2304 unsigned AlignMask = TargetAlign - 1;
2305 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2310 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2311 CallingConv::ID CallConv, bool isVarArg,
2312 const SmallVectorImpl<ISD::InputArg>
2314 SDLoc dl, SelectionDAG &DAG,
2315 SmallVectorImpl<SDValue> &InVals)
2317 if (Subtarget.isSVR4ABI()) {
2318 if (Subtarget.isPPC64())
2319 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2322 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2325 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2331 PPCTargetLowering::LowerFormalArguments_32SVR4(
2333 CallingConv::ID CallConv, bool isVarArg,
2334 const SmallVectorImpl<ISD::InputArg>
2336 SDLoc dl, SelectionDAG &DAG,
2337 SmallVectorImpl<SDValue> &InVals) const {
2339 // 32-bit SVR4 ABI Stack Frame Layout:
2340 // +-----------------------------------+
2341 // +--> | Back chain |
2342 // | +-----------------------------------+
2343 // | | Floating-point register save area |
2344 // | +-----------------------------------+
2345 // | | General register save area |
2346 // | +-----------------------------------+
2347 // | | CR save word |
2348 // | +-----------------------------------+
2349 // | | VRSAVE save word |
2350 // | +-----------------------------------+
2351 // | | Alignment padding |
2352 // | +-----------------------------------+
2353 // | | Vector register save area |
2354 // | +-----------------------------------+
2355 // | | Local variable space |
2356 // | +-----------------------------------+
2357 // | | Parameter list area |
2358 // | +-----------------------------------+
2359 // | | LR save word |
2360 // | +-----------------------------------+
2361 // SP--> +--- | Back chain |
2362 // +-----------------------------------+
2365 // System V Application Binary Interface PowerPC Processor Supplement
2366 // AltiVec Technology Programming Interface Manual
2368 MachineFunction &MF = DAG.getMachineFunction();
2369 MachineFrameInfo *MFI = MF.getFrameInfo();
2370 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2372 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2373 // Potential tail calls could cause overwriting of argument stack slots.
2374 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2375 (CallConv == CallingConv::Fast));
2376 unsigned PtrByteSize = 4;
2378 // Assign locations to all of the incoming arguments.
2379 SmallVector<CCValAssign, 16> ArgLocs;
2380 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2381 getTargetMachine(), ArgLocs, *DAG.getContext());
2383 // Reserve space for the linkage area on the stack.
2384 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2385 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2387 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2389 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2390 CCValAssign &VA = ArgLocs[i];
2392 // Arguments stored in registers.
2393 if (VA.isRegLoc()) {
2394 const TargetRegisterClass *RC;
2395 EVT ValVT = VA.getValVT();
2397 switch (ValVT.getSimpleVT().SimpleTy) {
2399 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2402 RC = &PPC::GPRCRegClass;
2405 RC = &PPC::F4RCRegClass;
2408 if (Subtarget.hasVSX())
2409 RC = &PPC::VSFRCRegClass;
2411 RC = &PPC::F8RCRegClass;
2417 RC = &PPC::VRRCRegClass;
2421 RC = &PPC::VSHRCRegClass;
2425 // Transform the arguments stored in physical registers into virtual ones.
2426 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2427 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2428 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2430 if (ValVT == MVT::i1)
2431 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2433 InVals.push_back(ArgValue);
2435 // Argument stored in memory.
2436 assert(VA.isMemLoc());
2438 unsigned ArgSize = VA.getLocVT().getStoreSize();
2439 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2442 // Create load nodes to retrieve arguments from the stack.
2443 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2444 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2445 MachinePointerInfo(),
2446 false, false, false, 0));
2450 // Assign locations to all of the incoming aggregate by value arguments.
2451 // Aggregates passed by value are stored in the local variable space of the
2452 // caller's stack frame, right above the parameter list area.
2453 SmallVector<CCValAssign, 16> ByValArgLocs;
2454 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2455 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2457 // Reserve stack space for the allocations in CCInfo.
2458 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2460 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2462 // Area that is at least reserved in the caller of this function.
2463 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2464 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2466 // Set the size that is at least reserved in caller of this function. Tail
2467 // call optimized function's reserved stack space needs to be aligned so that
2468 // taking the difference between two stack areas will result in an aligned
2470 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2471 FuncInfo->setMinReservedArea(MinReservedArea);
2473 SmallVector<SDValue, 8> MemOps;
2475 // If the function takes variable number of arguments, make a frame index for
2476 // the start of the first vararg value... for expansion of llvm.va_start.
2478 static const MCPhysReg GPArgRegs[] = {
2479 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2480 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2482 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2484 static const MCPhysReg FPArgRegs[] = {
2485 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2488 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2490 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2492 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2495 // Make room for NumGPArgRegs and NumFPArgRegs.
2496 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2497 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2499 FuncInfo->setVarArgsStackOffset(
2500 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2501 CCInfo.getNextStackOffset(), true));
2503 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2504 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2506 // The fixed integer arguments of a variadic function are stored to the
2507 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2508 // the result of va_next.
2509 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2510 // Get an existing live-in vreg, or add a new one.
2511 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2513 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2515 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2516 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2517 MachinePointerInfo(), false, false, 0);
2518 MemOps.push_back(Store);
2519 // Increment the address by four for the next argument to store
2520 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2521 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2524 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2526 // The double arguments are stored to the VarArgsFrameIndex
2528 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2529 // Get an existing live-in vreg, or add a new one.
2530 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2532 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2534 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2535 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2536 MachinePointerInfo(), false, false, 0);
2537 MemOps.push_back(Store);
2538 // Increment the address by eight for the next argument to store
2539 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2541 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2545 if (!MemOps.empty())
2546 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2551 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2552 // value to MVT::i64 and then truncate to the correct register size.
2554 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2555 SelectionDAG &DAG, SDValue ArgVal,
2558 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2559 DAG.getValueType(ObjectVT));
2560 else if (Flags.isZExt())
2561 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2562 DAG.getValueType(ObjectVT));
2564 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2568 PPCTargetLowering::LowerFormalArguments_64SVR4(
2570 CallingConv::ID CallConv, bool isVarArg,
2571 const SmallVectorImpl<ISD::InputArg>
2573 SDLoc dl, SelectionDAG &DAG,
2574 SmallVectorImpl<SDValue> &InVals) const {
2575 // TODO: add description of PPC stack frame format, or at least some docs.
2577 bool isELFv2ABI = Subtarget.isELFv2ABI();
2578 bool isLittleEndian = Subtarget.isLittleEndian();
2579 MachineFunction &MF = DAG.getMachineFunction();
2580 MachineFrameInfo *MFI = MF.getFrameInfo();
2581 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2583 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2584 // Potential tail calls could cause overwriting of argument stack slots.
2585 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2586 (CallConv == CallingConv::Fast));
2587 unsigned PtrByteSize = 8;
2589 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2592 static const MCPhysReg GPR[] = {
2593 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2594 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2597 static const MCPhysReg *FPR = GetFPR();
2599 static const MCPhysReg VR[] = {
2600 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2601 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2603 static const MCPhysReg VSRH[] = {
2604 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2605 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2608 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2609 const unsigned Num_FPR_Regs = 13;
2610 const unsigned Num_VR_Regs = array_lengthof(VR);
2612 // Do a first pass over the arguments to determine whether the ABI
2613 // guarantees that our caller has allocated the parameter save area
2614 // on its stack frame. In the ELFv1 ABI, this is always the case;
2615 // in the ELFv2 ABI, it is true if this is a vararg function or if
2616 // any parameter is located in a stack slot.
2618 bool HasParameterArea = !isELFv2ABI || isVarArg;
2619 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2620 unsigned NumBytes = LinkageSize;
2621 unsigned AvailableFPRs = Num_FPR_Regs;
2622 unsigned AvailableVRs = Num_VR_Regs;
2623 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2624 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2625 PtrByteSize, LinkageSize, ParamAreaSize,
2626 NumBytes, AvailableFPRs, AvailableVRs))
2627 HasParameterArea = true;
2629 // Add DAG nodes to load the arguments or copy them out of registers. On
2630 // entry to a function on PPC, the arguments start after the linkage area,
2631 // although the first ones are often in registers.
2633 unsigned ArgOffset = LinkageSize;
2634 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2635 SmallVector<SDValue, 8> MemOps;
2636 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2637 unsigned CurArgIdx = 0;
2638 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2640 bool needsLoad = false;
2641 EVT ObjectVT = Ins[ArgNo].VT;
2642 EVT OrigVT = Ins[ArgNo].ArgVT;
2643 unsigned ObjSize = ObjectVT.getStoreSize();
2644 unsigned ArgSize = ObjSize;
2645 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2646 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2647 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2649 /* Respect alignment of argument on the stack. */
2651 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2652 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2653 unsigned CurArgOffset = ArgOffset;
2655 /* Compute GPR index associated with argument offset. */
2656 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2657 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2659 // FIXME the codegen can be much improved in some cases.
2660 // We do not have to keep everything in memory.
2661 if (Flags.isByVal()) {
2662 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2663 ObjSize = Flags.getByValSize();
2664 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2665 // Empty aggregate parameters do not take up registers. Examples:
2669 // etc. However, we have to provide a place-holder in InVals, so
2670 // pretend we have an 8-byte item at the current address for that
2673 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2674 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2675 InVals.push_back(FIN);
2679 // Create a stack object covering all stack doublewords occupied
2680 // by the argument. If the argument is (fully or partially) on
2681 // the stack, or if the argument is fully in registers but the
2682 // caller has allocated the parameter save anyway, we can refer
2683 // directly to the caller's stack frame. Otherwise, create a
2684 // local copy in our own frame.
2686 if (HasParameterArea ||
2687 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2688 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2690 FI = MFI->CreateStackObject(ArgSize, Align, false);
2691 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2693 // Handle aggregates smaller than 8 bytes.
2694 if (ObjSize < PtrByteSize) {
2695 // The value of the object is its address, which differs from the
2696 // address of the enclosing doubleword on big-endian systems.
2698 if (!isLittleEndian) {
2699 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2700 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2702 InVals.push_back(Arg);
2704 if (GPR_idx != Num_GPR_Regs) {
2705 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2706 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2709 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2710 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2711 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2712 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2713 MachinePointerInfo(FuncArg),
2714 ObjType, false, false, 0);
2716 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2717 // store the whole register as-is to the parameter save area
2719 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2720 MachinePointerInfo(FuncArg),
2724 MemOps.push_back(Store);
2726 // Whether we copied from a register or not, advance the offset
2727 // into the parameter save area by a full doubleword.
2728 ArgOffset += PtrByteSize;
2732 // The value of the object is its address, which is the address of
2733 // its first stack doubleword.
2734 InVals.push_back(FIN);
2736 // Store whatever pieces of the object are in registers to memory.
2737 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2738 if (GPR_idx == Num_GPR_Regs)
2741 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2742 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2745 SDValue Off = DAG.getConstant(j, PtrVT);
2746 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2748 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2749 MachinePointerInfo(FuncArg, j),
2751 MemOps.push_back(Store);
2754 ArgOffset += ArgSize;
2758 switch (ObjectVT.getSimpleVT().SimpleTy) {
2759 default: llvm_unreachable("Unhandled argument type!");
2763 // These can be scalar arguments or elements of an integer array type
2764 // passed directly. Clang may use those instead of "byval" aggregate
2765 // types to avoid forcing arguments to memory unnecessarily.
2766 if (GPR_idx != Num_GPR_Regs) {
2767 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2768 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2770 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2771 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2772 // value to MVT::i64 and then truncate to the correct register size.
2773 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2776 ArgSize = PtrByteSize;
2783 // These can be scalar arguments or elements of a float array type
2784 // passed directly. The latter are used to implement ELFv2 homogenous
2785 // float aggregates.
2786 if (FPR_idx != Num_FPR_Regs) {
2789 if (ObjectVT == MVT::f32)
2790 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2792 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2793 &PPC::VSFRCRegClass :
2794 &PPC::F8RCRegClass);
2796 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2798 } else if (GPR_idx != Num_GPR_Regs) {
2799 // This can only ever happen in the presence of f32 array types,
2800 // since otherwise we never run out of FPRs before running out
2802 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2803 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2805 if (ObjectVT == MVT::f32) {
2806 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2807 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2808 DAG.getConstant(32, MVT::i32));
2809 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2812 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2817 // When passing an array of floats, the array occupies consecutive
2818 // space in the argument area; only round up to the next doubleword
2819 // at the end of the array. Otherwise, each float takes 8 bytes.
2820 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2821 ArgOffset += ArgSize;
2822 if (Flags.isInConsecutiveRegsLast())
2823 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2831 // These can be scalar arguments or elements of a vector array type
2832 // passed directly. The latter are used to implement ELFv2 homogenous
2833 // vector aggregates.
2834 if (VR_idx != Num_VR_Regs) {
2835 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2836 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2837 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2838 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2847 // We need to load the argument to a virtual register if we determined
2848 // above that we ran out of physical registers of the appropriate type.
2850 if (ObjSize < ArgSize && !isLittleEndian)
2851 CurArgOffset += ArgSize - ObjSize;
2852 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2853 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2854 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2855 false, false, false, 0);
2858 InVals.push_back(ArgVal);
2861 // Area that is at least reserved in the caller of this function.
2862 unsigned MinReservedArea;
2863 if (HasParameterArea)
2864 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2866 MinReservedArea = LinkageSize;
2868 // Set the size that is at least reserved in caller of this function. Tail
2869 // call optimized functions' reserved stack space needs to be aligned so that
2870 // taking the difference between two stack areas will result in an aligned
2872 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2873 FuncInfo->setMinReservedArea(MinReservedArea);
2875 // If the function takes variable number of arguments, make a frame index for
2876 // the start of the first vararg value... for expansion of llvm.va_start.
2878 int Depth = ArgOffset;
2880 FuncInfo->setVarArgsFrameIndex(
2881 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2882 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2884 // If this function is vararg, store any remaining integer argument regs
2885 // to their spots on the stack so that they may be loaded by deferencing the
2886 // result of va_next.
2887 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2888 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2889 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2890 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2891 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2892 MachinePointerInfo(), false, false, 0);
2893 MemOps.push_back(Store);
2894 // Increment the address by four for the next argument to store
2895 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2896 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2900 if (!MemOps.empty())
2901 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2907 PPCTargetLowering::LowerFormalArguments_Darwin(
2909 CallingConv::ID CallConv, bool isVarArg,
2910 const SmallVectorImpl<ISD::InputArg>
2912 SDLoc dl, SelectionDAG &DAG,
2913 SmallVectorImpl<SDValue> &InVals) const {
2914 // TODO: add description of PPC stack frame format, or at least some docs.
2916 MachineFunction &MF = DAG.getMachineFunction();
2917 MachineFrameInfo *MFI = MF.getFrameInfo();
2918 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2920 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2921 bool isPPC64 = PtrVT == MVT::i64;
2922 // Potential tail calls could cause overwriting of argument stack slots.
2923 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2924 (CallConv == CallingConv::Fast));
2925 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2927 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2929 unsigned ArgOffset = LinkageSize;
2930 // Area that is at least reserved in caller of this function.
2931 unsigned MinReservedArea = ArgOffset;
2933 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2934 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2935 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2937 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2938 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2939 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2942 static const MCPhysReg *FPR = GetFPR();
2944 static const MCPhysReg VR[] = {
2945 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2946 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2949 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2950 const unsigned Num_FPR_Regs = 13;
2951 const unsigned Num_VR_Regs = array_lengthof( VR);
2953 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2955 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2957 // In 32-bit non-varargs functions, the stack space for vectors is after the
2958 // stack space for non-vectors. We do not use this space unless we have
2959 // too many vectors to fit in registers, something that only occurs in
2960 // constructed examples:), but we have to walk the arglist to figure
2961 // that out...for the pathological case, compute VecArgOffset as the
2962 // start of the vector parameter area. Computing VecArgOffset is the
2963 // entire point of the following loop.
2964 unsigned VecArgOffset = ArgOffset;
2965 if (!isVarArg && !isPPC64) {
2966 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2968 EVT ObjectVT = Ins[ArgNo].VT;
2969 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2971 if (Flags.isByVal()) {
2972 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2973 unsigned ObjSize = Flags.getByValSize();
2975 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2976 VecArgOffset += ArgSize;
2980 switch(ObjectVT.getSimpleVT().SimpleTy) {
2981 default: llvm_unreachable("Unhandled argument type!");
2987 case MVT::i64: // PPC64
2989 // FIXME: We are guaranteed to be !isPPC64 at this point.
2990 // Does MVT::i64 apply?
2997 // Nothing to do, we're only looking at Nonvector args here.
3002 // We've found where the vector parameter area in memory is. Skip the
3003 // first 12 parameters; these don't use that memory.
3004 VecArgOffset = ((VecArgOffset+15)/16)*16;
3005 VecArgOffset += 12*16;
3007 // Add DAG nodes to load the arguments or copy them out of registers. On
3008 // entry to a function on PPC, the arguments start after the linkage area,
3009 // although the first ones are often in registers.
3011 SmallVector<SDValue, 8> MemOps;
3012 unsigned nAltivecParamsAtEnd = 0;
3013 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3014 unsigned CurArgIdx = 0;
3015 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3017 bool needsLoad = false;
3018 EVT ObjectVT = Ins[ArgNo].VT;
3019 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3020 unsigned ArgSize = ObjSize;
3021 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3022 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3023 CurArgIdx = Ins[ArgNo].OrigArgIndex;
3025 unsigned CurArgOffset = ArgOffset;
3027 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3028 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3029 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3030 if (isVarArg || isPPC64) {
3031 MinReservedArea = ((MinReservedArea+15)/16)*16;
3032 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3035 } else nAltivecParamsAtEnd++;
3037 // Calculate min reserved area.
3038 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3042 // FIXME the codegen can be much improved in some cases.
3043 // We do not have to keep everything in memory.
3044 if (Flags.isByVal()) {
3045 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3046 ObjSize = Flags.getByValSize();
3047 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3048 // Objects of size 1 and 2 are right justified, everything else is
3049 // left justified. This means the memory address is adjusted forwards.
3050 if (ObjSize==1 || ObjSize==2) {
3051 CurArgOffset = CurArgOffset + (4 - ObjSize);
3053 // The value of the object is its address.
3054 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
3055 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3056 InVals.push_back(FIN);
3057 if (ObjSize==1 || ObjSize==2) {
3058 if (GPR_idx != Num_GPR_Regs) {
3061 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3063 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3064 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3065 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3066 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3067 MachinePointerInfo(FuncArg),
3068 ObjType, false, false, 0);
3069 MemOps.push_back(Store);
3073 ArgOffset += PtrByteSize;
3077 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3078 // Store whatever pieces of the object are in registers
3079 // to memory. ArgOffset will be the address of the beginning
3081 if (GPR_idx != Num_GPR_Regs) {
3084 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3086 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3087 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3088 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3089 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3090 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3091 MachinePointerInfo(FuncArg, j),
3093 MemOps.push_back(Store);
3095 ArgOffset += PtrByteSize;
3097 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3104 switch (ObjectVT.getSimpleVT().SimpleTy) {
3105 default: llvm_unreachable("Unhandled argument type!");
3109 if (GPR_idx != Num_GPR_Regs) {
3110 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3111 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3113 if (ObjectVT == MVT::i1)
3114 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3119 ArgSize = PtrByteSize;
3121 // All int arguments reserve stack space in the Darwin ABI.
3122 ArgOffset += PtrByteSize;
3126 case MVT::i64: // PPC64
3127 if (GPR_idx != Num_GPR_Regs) {
3128 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3129 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3131 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3132 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3133 // value to MVT::i64 and then truncate to the correct register size.
3134 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3139 ArgSize = PtrByteSize;
3141 // All int arguments reserve stack space in the Darwin ABI.
3147 // Every 4 bytes of argument space consumes one of the GPRs available for
3148 // argument passing.
3149 if (GPR_idx != Num_GPR_Regs) {
3151 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3154 if (FPR_idx != Num_FPR_Regs) {
3157 if (ObjectVT == MVT::f32)
3158 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3160 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3162 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3168 // All FP arguments reserve stack space in the Darwin ABI.
3169 ArgOffset += isPPC64 ? 8 : ObjSize;
3175 // Note that vector arguments in registers don't reserve stack space,
3176 // except in varargs functions.
3177 if (VR_idx != Num_VR_Regs) {
3178 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3179 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3181 while ((ArgOffset % 16) != 0) {
3182 ArgOffset += PtrByteSize;
3183 if (GPR_idx != Num_GPR_Regs)
3187 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3191 if (!isVarArg && !isPPC64) {
3192 // Vectors go after all the nonvectors.
3193 CurArgOffset = VecArgOffset;
3196 // Vectors are aligned.
3197 ArgOffset = ((ArgOffset+15)/16)*16;
3198 CurArgOffset = ArgOffset;
3206 // We need to load the argument to a virtual register if we determined above
3207 // that we ran out of physical registers of the appropriate type.
3209 int FI = MFI->CreateFixedObject(ObjSize,
3210 CurArgOffset + (ArgSize - ObjSize),
3212 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3213 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3214 false, false, false, 0);
3217 InVals.push_back(ArgVal);
3220 // Allow for Altivec parameters at the end, if needed.
3221 if (nAltivecParamsAtEnd) {
3222 MinReservedArea = ((MinReservedArea+15)/16)*16;
3223 MinReservedArea += 16*nAltivecParamsAtEnd;
3226 // Area that is at least reserved in the caller of this function.
3227 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3229 // Set the size that is at least reserved in caller of this function. Tail
3230 // call optimized functions' reserved stack space needs to be aligned so that
3231 // taking the difference between two stack areas will result in an aligned
3233 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3234 FuncInfo->setMinReservedArea(MinReservedArea);
3236 // If the function takes variable number of arguments, make a frame index for
3237 // the start of the first vararg value... for expansion of llvm.va_start.
3239 int Depth = ArgOffset;
3241 FuncInfo->setVarArgsFrameIndex(
3242 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3244 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3246 // If this function is vararg, store any remaining integer argument regs
3247 // to their spots on the stack so that they may be loaded by deferencing the
3248 // result of va_next.
3249 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3253 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3255 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3257 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3258 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3259 MachinePointerInfo(), false, false, 0);
3260 MemOps.push_back(Store);
3261 // Increment the address by four for the next argument to store
3262 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3263 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3267 if (!MemOps.empty())
3268 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3273 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3274 /// adjusted to accommodate the arguments for the tailcall.
3275 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3276 unsigned ParamSize) {
3278 if (!isTailCall) return 0;
3280 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3281 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3282 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3283 // Remember only if the new adjustement is bigger.
3284 if (SPDiff < FI->getTailCallSPDelta())
3285 FI->setTailCallSPDelta(SPDiff);
3290 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3291 /// for tail call optimization. Targets which want to do tail call
3292 /// optimization should implement this function.
3294 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3295 CallingConv::ID CalleeCC,
3297 const SmallVectorImpl<ISD::InputArg> &Ins,
3298 SelectionDAG& DAG) const {
3299 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3302 // Variable argument functions are not supported.
3306 MachineFunction &MF = DAG.getMachineFunction();
3307 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3308 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3309 // Functions containing by val parameters are not supported.
3310 for (unsigned i = 0; i != Ins.size(); i++) {
3311 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3312 if (Flags.isByVal()) return false;
3315 // Non-PIC/GOT tail calls are supported.
3316 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3319 // At the moment we can only do local tail calls (in same module, hidden
3320 // or protected) if we are generating PIC.
3321 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3322 return G->getGlobal()->hasHiddenVisibility()
3323 || G->getGlobal()->hasProtectedVisibility();
3329 /// isCallCompatibleAddress - Return the immediate to use if the specified
3330 /// 32-bit value is representable in the immediate field of a BxA instruction.
3331 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3332 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3333 if (!C) return nullptr;
3335 int Addr = C->getZExtValue();
3336 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3337 SignExtend32<26>(Addr) != Addr)
3338 return nullptr; // Top 6 bits have to be sext of immediate.
3340 return DAG.getConstant((int)C->getZExtValue() >> 2,
3341 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3346 struct TailCallArgumentInfo {
3351 TailCallArgumentInfo() : FrameIdx(0) {}
3356 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3358 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3360 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3361 SmallVectorImpl<SDValue> &MemOpChains,
3363 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3364 SDValue Arg = TailCallArgs[i].Arg;
3365 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3366 int FI = TailCallArgs[i].FrameIdx;
3367 // Store relative to framepointer.
3368 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3369 MachinePointerInfo::getFixedStack(FI),
3374 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3375 /// the appropriate stack slot for the tail call optimized function call.
3376 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3377 MachineFunction &MF,
3386 // Calculate the new stack slot for the return address.
3387 int SlotSize = isPPC64 ? 8 : 4;
3388 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3390 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3391 NewRetAddrLoc, true);
3392 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3393 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3394 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3395 MachinePointerInfo::getFixedStack(NewRetAddr),
3398 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3399 // slot as the FP is never overwritten.
3402 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3403 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3405 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3406 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3407 MachinePointerInfo::getFixedStack(NewFPIdx),
3414 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3415 /// the position of the argument.
3417 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3418 SDValue Arg, int SPDiff, unsigned ArgOffset,
3419 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3420 int Offset = ArgOffset + SPDiff;
3421 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3422 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3423 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3424 SDValue FIN = DAG.getFrameIndex(FI, VT);
3425 TailCallArgumentInfo Info;
3427 Info.FrameIdxOp = FIN;
3429 TailCallArguments.push_back(Info);
3432 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3433 /// stack slot. Returns the chain as result and the loaded frame pointers in
3434 /// LROpOut/FPOpout. Used when tail calling.
3435 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3443 // Load the LR and FP stack slot for later adjusting.
3444 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3445 LROpOut = getReturnAddrFrameIndex(DAG);
3446 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3447 false, false, false, 0);
3448 Chain = SDValue(LROpOut.getNode(), 1);
3450 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3451 // slot as the FP is never overwritten.
3453 FPOpOut = getFramePointerFrameIndex(DAG);
3454 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3455 false, false, false, 0);
3456 Chain = SDValue(FPOpOut.getNode(), 1);
3462 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3463 /// by "Src" to address "Dst" of size "Size". Alignment information is
3464 /// specified by the specific parameter attribute. The copy will be passed as
3465 /// a byval function parameter.
3466 /// Sometimes what we are copying is the end of a larger object, the part that
3467 /// does not fit in registers.
3469 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3470 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3472 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3473 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3474 false, false, MachinePointerInfo(),
3475 MachinePointerInfo());
3478 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3481 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3482 SDValue Arg, SDValue PtrOff, int SPDiff,
3483 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3484 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3485 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3487 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3492 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3494 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3495 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3496 DAG.getConstant(ArgOffset, PtrVT));
3498 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3499 MachinePointerInfo(), false, false, 0));
3500 // Calculate and remember argument location.
3501 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3506 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3507 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3508 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3509 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3510 MachineFunction &MF = DAG.getMachineFunction();
3512 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3513 // might overwrite each other in case of tail call optimization.
3514 SmallVector<SDValue, 8> MemOpChains2;
3515 // Do not flag preceding copytoreg stuff together with the following stuff.
3517 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3519 if (!MemOpChains2.empty())
3520 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3522 // Store the return address to the appropriate stack slot.
3523 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3524 isPPC64, isDarwinABI, dl);
3526 // Emit callseq_end just before tailcall node.
3527 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3528 DAG.getIntPtrConstant(0, true), InFlag, dl);
3529 InFlag = Chain.getValue(1);
3533 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3534 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3535 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3536 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3537 const PPCSubtarget &Subtarget) {
3539 bool isPPC64 = Subtarget.isPPC64();
3540 bool isSVR4ABI = Subtarget.isSVR4ABI();
3541 bool isELFv2ABI = Subtarget.isELFv2ABI();
3543 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3544 NodeTys.push_back(MVT::Other); // Returns a chain
3545 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3547 unsigned CallOpc = PPCISD::CALL;
3549 bool needIndirectCall = true;
3550 if (!isSVR4ABI || !isPPC64)
3551 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3552 // If this is an absolute destination address, use the munged value.
3553 Callee = SDValue(Dest, 0);
3554 needIndirectCall = false;
3557 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3558 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3559 // Use indirect calls for ALL functions calls in JIT mode, since the
3560 // far-call stubs may be outside relocation limits for a BL instruction.
3561 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3562 unsigned OpFlags = 0;
3563 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3564 (Subtarget.getTargetTriple().isMacOSX() &&
3565 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3566 (G->getGlobal()->isDeclaration() ||
3567 G->getGlobal()->isWeakForLinker())) ||
3568 (Subtarget.isTargetELF() && !isPPC64 &&
3569 !G->getGlobal()->hasLocalLinkage() &&
3570 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3571 // PC-relative references to external symbols should go through $stub,
3572 // unless we're building with the leopard linker or later, which
3573 // automatically synthesizes these stubs.
3574 OpFlags = PPCII::MO_PLT_OR_STUB;
3577 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3578 // every direct call is) turn it into a TargetGlobalAddress /
3579 // TargetExternalSymbol node so that legalize doesn't hack it.
3580 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3581 Callee.getValueType(),
3583 needIndirectCall = false;
3587 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3588 unsigned char OpFlags = 0;
3590 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3591 (Subtarget.getTargetTriple().isMacOSX() &&
3592 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3593 (Subtarget.isTargetELF() && !isPPC64 &&
3594 DAG.getTarget().getRelocationModel() == Reloc::PIC_) ) {
3595 // PC-relative references to external symbols should go through $stub,
3596 // unless we're building with the leopard linker or later, which
3597 // automatically synthesizes these stubs.
3598 OpFlags = PPCII::MO_PLT_OR_STUB;
3601 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3603 needIndirectCall = false;
3606 if (needIndirectCall) {
3607 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3608 // to do the call, we can't use PPCISD::CALL.
3609 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3611 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3612 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3613 // entry point, but to the function descriptor (the function entry point
3614 // address is part of the function descriptor though).
3615 // The function descriptor is a three doubleword structure with the
3616 // following fields: function entry point, TOC base address and
3617 // environment pointer.
3618 // Thus for a call through a function pointer, the following actions need
3620 // 1. Save the TOC of the caller in the TOC save area of its stack
3621 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3622 // 2. Load the address of the function entry point from the function
3624 // 3. Load the TOC of the callee from the function descriptor into r2.
3625 // 4. Load the environment pointer from the function descriptor into
3627 // 5. Branch to the function entry point address.
3628 // 6. On return of the callee, the TOC of the caller needs to be
3629 // restored (this is done in FinishCall()).
3631 // All those operations are flagged together to ensure that no other
3632 // operations can be scheduled in between. E.g. without flagging the
3633 // operations together, a TOC access in the caller could be scheduled
3634 // between the load of the callee TOC and the branch to the callee, which
3635 // results in the TOC access going through the TOC of the callee instead
3636 // of going through the TOC of the caller, which leads to incorrect code.
3638 // Load the address of the function entry point from the function
3640 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3641 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3642 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3643 Chain = LoadFuncPtr.getValue(1);
3644 InFlag = LoadFuncPtr.getValue(2);
3646 // Load environment pointer into r11.
3647 // Offset of the environment pointer within the function descriptor.
3648 SDValue PtrOff = DAG.getIntPtrConstant(16);
3650 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3651 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3653 Chain = LoadEnvPtr.getValue(1);
3654 InFlag = LoadEnvPtr.getValue(2);
3656 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3658 Chain = EnvVal.getValue(0);
3659 InFlag = EnvVal.getValue(1);
3661 // Load TOC of the callee into r2. We are using a target-specific load
3662 // with r2 hard coded, because the result of a target-independent load
3663 // would never go directly into r2, since r2 is a reserved register (which
3664 // prevents the register allocator from allocating it), resulting in an
3665 // additional register being allocated and an unnecessary move instruction
3667 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3668 SDValue TOCOff = DAG.getIntPtrConstant(8);
3669 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3670 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3672 Chain = LoadTOCPtr.getValue(0);
3673 InFlag = LoadTOCPtr.getValue(1);
3675 MTCTROps[0] = Chain;
3676 MTCTROps[1] = LoadFuncPtr;
3677 MTCTROps[2] = InFlag;
3680 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3681 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3682 InFlag = Chain.getValue(1);
3685 NodeTys.push_back(MVT::Other);
3686 NodeTys.push_back(MVT::Glue);
3687 Ops.push_back(Chain);
3688 CallOpc = PPCISD::BCTRL;
3689 Callee.setNode(nullptr);
3690 // Add use of X11 (holding environment pointer)
3691 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3692 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3693 // Add CTR register as callee so a bctr can be emitted later.
3695 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3698 // If this is a direct call, pass the chain and the callee.
3699 if (Callee.getNode()) {
3700 Ops.push_back(Chain);
3701 Ops.push_back(Callee);
3703 // If this is a tail call add stack pointer delta.
3705 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3707 // Add argument registers to the end of the list so that they are known live
3709 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3710 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3711 RegsToPass[i].second.getValueType()));
3713 // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3714 if (Callee.getNode() && isELFv2ABI)
3715 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3721 bool isLocalCall(const SDValue &Callee)
3723 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3724 return !G->getGlobal()->isDeclaration() &&
3725 !G->getGlobal()->isWeakForLinker();
3730 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3731 CallingConv::ID CallConv, bool isVarArg,
3732 const SmallVectorImpl<ISD::InputArg> &Ins,
3733 SDLoc dl, SelectionDAG &DAG,
3734 SmallVectorImpl<SDValue> &InVals) const {
3736 SmallVector<CCValAssign, 16> RVLocs;
3737 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3738 getTargetMachine(), RVLocs, *DAG.getContext());
3739 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3741 // Copy all of the result registers out of their specified physreg.
3742 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3743 CCValAssign &VA = RVLocs[i];
3744 assert(VA.isRegLoc() && "Can only return in registers!");
3746 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3747 VA.getLocReg(), VA.getLocVT(), InFlag);
3748 Chain = Val.getValue(1);
3749 InFlag = Val.getValue(2);
3751 switch (VA.getLocInfo()) {
3752 default: llvm_unreachable("Unknown loc info!");
3753 case CCValAssign::Full: break;
3754 case CCValAssign::AExt:
3755 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3757 case CCValAssign::ZExt:
3758 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3759 DAG.getValueType(VA.getValVT()));
3760 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3762 case CCValAssign::SExt:
3763 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3764 DAG.getValueType(VA.getValVT()));
3765 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3769 InVals.push_back(Val);
3776 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3777 bool isTailCall, bool isVarArg,
3779 SmallVector<std::pair<unsigned, SDValue>, 8>
3781 SDValue InFlag, SDValue Chain,
3783 int SPDiff, unsigned NumBytes,
3784 const SmallVectorImpl<ISD::InputArg> &Ins,
3785 SmallVectorImpl<SDValue> &InVals) const {
3787 bool isELFv2ABI = Subtarget.isELFv2ABI();
3788 std::vector<EVT> NodeTys;
3789 SmallVector<SDValue, 8> Ops;
3790 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3791 isTailCall, RegsToPass, Ops, NodeTys,
3794 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3795 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3796 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3798 // When performing tail call optimization the callee pops its arguments off
3799 // the stack. Account for this here so these bytes can be pushed back on in
3800 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3801 int BytesCalleePops =
3802 (CallConv == CallingConv::Fast &&
3803 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3805 // Add a register mask operand representing the call-preserved registers.
3806 const TargetRegisterInfo *TRI =
3807 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3808 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3809 assert(Mask && "Missing call preserved mask for calling convention");
3810 Ops.push_back(DAG.getRegisterMask(Mask));
3812 if (InFlag.getNode())
3813 Ops.push_back(InFlag);
3817 assert(((Callee.getOpcode() == ISD::Register &&
3818 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3819 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3820 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3821 isa<ConstantSDNode>(Callee)) &&
3822 "Expecting an global address, external symbol, absolute value or register");
3824 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3827 // Add a NOP immediately after the branch instruction when using the 64-bit
3828 // SVR4 ABI. At link time, if caller and callee are in a different module and
3829 // thus have a different TOC, the call will be replaced with a call to a stub
3830 // function which saves the current TOC, loads the TOC of the callee and
3831 // branches to the callee. The NOP will be replaced with a load instruction
3832 // which restores the TOC of the caller from the TOC save slot of the current
3833 // stack frame. If caller and callee belong to the same module (and have the
3834 // same TOC), the NOP will remain unchanged.
3836 bool needsTOCRestore = false;
3837 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3838 if (CallOpc == PPCISD::BCTRL) {
3839 // This is a call through a function pointer.
3840 // Restore the caller TOC from the save area into R2.
3841 // See PrepareCall() for more information about calls through function
3842 // pointers in the 64-bit SVR4 ABI.
3843 // We are using a target-specific load with r2 hard coded, because the
3844 // result of a target-independent load would never go directly into r2,
3845 // since r2 is a reserved register (which prevents the register allocator
3846 // from allocating it), resulting in an additional register being
3847 // allocated and an unnecessary move instruction being generated.
3848 needsTOCRestore = true;
3849 } else if ((CallOpc == PPCISD::CALL) &&
3850 (!isLocalCall(Callee) ||
3851 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3852 // Otherwise insert NOP for non-local calls.
3853 CallOpc = PPCISD::CALL_NOP;
3857 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3858 InFlag = Chain.getValue(1);
3860 if (needsTOCRestore) {
3861 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3862 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3863 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3864 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3865 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3866 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3867 Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
3868 InFlag = Chain.getValue(1);
3871 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3872 DAG.getIntPtrConstant(BytesCalleePops, true),
3875 InFlag = Chain.getValue(1);
3877 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3878 Ins, dl, DAG, InVals);
3882 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3883 SmallVectorImpl<SDValue> &InVals) const {
3884 SelectionDAG &DAG = CLI.DAG;
3886 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3887 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3888 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3889 SDValue Chain = CLI.Chain;
3890 SDValue Callee = CLI.Callee;
3891 bool &isTailCall = CLI.IsTailCall;
3892 CallingConv::ID CallConv = CLI.CallConv;
3893 bool isVarArg = CLI.IsVarArg;
3896 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3899 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3900 report_fatal_error("failed to perform tail call elimination on a call "
3901 "site marked musttail");
3903 if (Subtarget.isSVR4ABI()) {
3904 if (Subtarget.isPPC64())
3905 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3906 isTailCall, Outs, OutVals, Ins,
3909 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3910 isTailCall, Outs, OutVals, Ins,
3914 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3915 isTailCall, Outs, OutVals, Ins,
3920 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3921 CallingConv::ID CallConv, bool isVarArg,
3923 const SmallVectorImpl<ISD::OutputArg> &Outs,
3924 const SmallVectorImpl<SDValue> &OutVals,
3925 const SmallVectorImpl<ISD::InputArg> &Ins,
3926 SDLoc dl, SelectionDAG &DAG,
3927 SmallVectorImpl<SDValue> &InVals) const {
3928 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3929 // of the 32-bit SVR4 ABI stack frame layout.
3931 assert((CallConv == CallingConv::C ||
3932 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3934 unsigned PtrByteSize = 4;
3936 MachineFunction &MF = DAG.getMachineFunction();
3938 // Mark this function as potentially containing a function that contains a
3939 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3940 // and restoring the callers stack pointer in this functions epilog. This is
3941 // done because by tail calling the called function might overwrite the value
3942 // in this function's (MF) stack pointer stack slot 0(SP).
3943 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3944 CallConv == CallingConv::Fast)
3945 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3947 // Count how many bytes are to be pushed on the stack, including the linkage
3948 // area, parameter list area and the part of the local variable space which
3949 // contains copies of aggregates which are passed by value.
3951 // Assign locations to all of the outgoing arguments.
3952 SmallVector<CCValAssign, 16> ArgLocs;
3953 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3954 getTargetMachine(), ArgLocs, *DAG.getContext());
3956 // Reserve space for the linkage area on the stack.
3957 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
3961 // Handle fixed and variable vector arguments differently.
3962 // Fixed vector arguments go into registers as long as registers are
3963 // available. Variable vector arguments always go into memory.
3964 unsigned NumArgs = Outs.size();
3966 for (unsigned i = 0; i != NumArgs; ++i) {
3967 MVT ArgVT = Outs[i].VT;
3968 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3971 if (Outs[i].IsFixed) {
3972 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3975 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3981 errs() << "Call operand #" << i << " has unhandled type "
3982 << EVT(ArgVT).getEVTString() << "\n";
3984 llvm_unreachable(nullptr);
3988 // All arguments are treated the same.
3989 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3992 // Assign locations to all of the outgoing aggregate by value arguments.
3993 SmallVector<CCValAssign, 16> ByValArgLocs;
3994 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3995 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3997 // Reserve stack space for the allocations in CCInfo.
3998 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4000 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4002 // Size of the linkage area, parameter list area and the part of the local
4003 // space variable where copies of aggregates which are passed by value are
4005 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4007 // Calculate by how many bytes the stack has to be adjusted in case of tail
4008 // call optimization.
4009 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4011 // Adjust the stack pointer for the new arguments...
4012 // These operations are automatically eliminated by the prolog/epilog pass
4013 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4015 SDValue CallSeqStart = Chain;
4017 // Load the return address and frame pointer so it can be moved somewhere else
4020 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4023 // Set up a copy of the stack pointer for use loading and storing any
4024 // arguments that may not fit in the registers available for argument
4026 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4028 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4029 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4030 SmallVector<SDValue, 8> MemOpChains;
4032 bool seenFloatArg = false;
4033 // Walk the register/memloc assignments, inserting copies/loads.
4034 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4037 CCValAssign &VA = ArgLocs[i];
4038 SDValue Arg = OutVals[i];
4039 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4041 if (Flags.isByVal()) {
4042 // Argument is an aggregate which is passed by value, thus we need to
4043 // create a copy of it in the local variable space of the current stack
4044 // frame (which is the stack frame of the caller) and pass the address of
4045 // this copy to the callee.
4046 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4047 CCValAssign &ByValVA = ByValArgLocs[j++];
4048 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4050 // Memory reserved in the local variable space of the callers stack frame.
4051 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4053 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4054 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4056 // Create a copy of the argument in the local area of the current
4058 SDValue MemcpyCall =
4059 CreateCopyOfByValArgument(Arg, PtrOff,
4060 CallSeqStart.getNode()->getOperand(0),
4063 // This must go outside the CALLSEQ_START..END.
4064 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4065 CallSeqStart.getNode()->getOperand(1),
4067 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4068 NewCallSeqStart.getNode());
4069 Chain = CallSeqStart = NewCallSeqStart;
4071 // Pass the address of the aggregate copy on the stack either in a
4072 // physical register or in the parameter list area of the current stack
4073 // frame to the callee.
4077 if (VA.isRegLoc()) {
4078 if (Arg.getValueType() == MVT::i1)
4079 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4081 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4082 // Put argument in a physical register.
4083 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4085 // Put argument in the parameter list area of the current stack frame.
4086 assert(VA.isMemLoc());
4087 unsigned LocMemOffset = VA.getLocMemOffset();
4090 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4091 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4093 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4094 MachinePointerInfo(),
4097 // Calculate and remember argument location.
4098 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4104 if (!MemOpChains.empty())
4105 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4107 // Build a sequence of copy-to-reg nodes chained together with token chain
4108 // and flag operands which copy the outgoing args into the appropriate regs.
4110 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4111 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4112 RegsToPass[i].second, InFlag);
4113 InFlag = Chain.getValue(1);
4116 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4119 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4120 SDValue Ops[] = { Chain, InFlag };
4122 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4123 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4125 InFlag = Chain.getValue(1);
4129 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4130 false, TailCallArguments);
4132 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4133 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4137 // Copy an argument into memory, being careful to do this outside the
4138 // call sequence for the call to which the argument belongs.
4140 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4141 SDValue CallSeqStart,
4142 ISD::ArgFlagsTy Flags,
4145 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4146 CallSeqStart.getNode()->getOperand(0),
4148 // The MEMCPY must go outside the CALLSEQ_START..END.
4149 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4150 CallSeqStart.getNode()->getOperand(1),
4152 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4153 NewCallSeqStart.getNode());
4154 return NewCallSeqStart;
4158 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4159 CallingConv::ID CallConv, bool isVarArg,
4161 const SmallVectorImpl<ISD::OutputArg> &Outs,
4162 const SmallVectorImpl<SDValue> &OutVals,
4163 const SmallVectorImpl<ISD::InputArg> &Ins,
4164 SDLoc dl, SelectionDAG &DAG,
4165 SmallVectorImpl<SDValue> &InVals) const {
4167 bool isELFv2ABI = Subtarget.isELFv2ABI();
4168 bool isLittleEndian = Subtarget.isLittleEndian();
4169 unsigned NumOps = Outs.size();
4171 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4172 unsigned PtrByteSize = 8;
4174 MachineFunction &MF = DAG.getMachineFunction();
4176 // Mark this function as potentially containing a function that contains a
4177 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4178 // and restoring the callers stack pointer in this functions epilog. This is
4179 // done because by tail calling the called function might overwrite the value
4180 // in this function's (MF) stack pointer stack slot 0(SP).
4181 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4182 CallConv == CallingConv::Fast)
4183 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4185 // Count how many bytes are to be pushed on the stack, including the linkage
4186 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4187 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4188 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4189 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4191 unsigned NumBytes = LinkageSize;
4193 // Add up all the space actually used.
4194 for (unsigned i = 0; i != NumOps; ++i) {
4195 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4196 EVT ArgVT = Outs[i].VT;
4197 EVT OrigVT = Outs[i].ArgVT;
4199 /* Respect alignment of argument on the stack. */
4201 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4202 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4204 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4205 if (Flags.isInConsecutiveRegsLast())
4206 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4209 unsigned NumBytesActuallyUsed = NumBytes;
4211 // The prolog code of the callee may store up to 8 GPR argument registers to
4212 // the stack, allowing va_start to index over them in memory if its varargs.
4213 // Because we cannot tell if this is needed on the caller side, we have to
4214 // conservatively assume that it is needed. As such, make sure we have at
4215 // least enough stack space for the caller to store the 8 GPRs.
4216 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4217 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4219 // Tail call needs the stack to be aligned.
4220 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4221 CallConv == CallingConv::Fast)
4222 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4224 // Calculate by how many bytes the stack has to be adjusted in case of tail
4225 // call optimization.
4226 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4228 // To protect arguments on the stack from being clobbered in a tail call,
4229 // force all the loads to happen before doing any other lowering.
4231 Chain = DAG.getStackArgumentTokenFactor(Chain);
4233 // Adjust the stack pointer for the new arguments...
4234 // These operations are automatically eliminated by the prolog/epilog pass
4235 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4237 SDValue CallSeqStart = Chain;
4239 // Load the return address and frame pointer so it can be move somewhere else
4242 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4245 // Set up a copy of the stack pointer for use loading and storing any
4246 // arguments that may not fit in the registers available for argument
4248 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4250 // Figure out which arguments are going to go in registers, and which in
4251 // memory. Also, if this is a vararg function, floating point operations
4252 // must be stored to our stack, and loaded into integer regs as well, if
4253 // any integer regs are available for argument passing.
4254 unsigned ArgOffset = LinkageSize;
4255 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4257 static const MCPhysReg GPR[] = {
4258 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4259 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4261 static const MCPhysReg *FPR = GetFPR();
4263 static const MCPhysReg VR[] = {
4264 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4265 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4267 static const MCPhysReg VSRH[] = {
4268 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4269 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4272 const unsigned NumGPRs = array_lengthof(GPR);
4273 const unsigned NumFPRs = 13;
4274 const unsigned NumVRs = array_lengthof(VR);
4276 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4277 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4279 SmallVector<SDValue, 8> MemOpChains;
4280 for (unsigned i = 0; i != NumOps; ++i) {
4281 SDValue Arg = OutVals[i];
4282 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4283 EVT ArgVT = Outs[i].VT;
4284 EVT OrigVT = Outs[i].ArgVT;
4286 /* Respect alignment of argument on the stack. */
4288 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4289 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4291 /* Compute GPR index associated with argument offset. */
4292 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4293 GPR_idx = std::min(GPR_idx, NumGPRs);
4295 // PtrOff will be used to store the current argument to the stack if a
4296 // register cannot be found for it.
4299 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4301 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4303 // Promote integers to 64-bit values.
4304 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4305 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4306 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4307 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4310 // FIXME memcpy is used way more than necessary. Correctness first.
4311 // Note: "by value" is code for passing a structure by value, not
4313 if (Flags.isByVal()) {
4314 // Note: Size includes alignment padding, so
4315 // struct x { short a; char b; }
4316 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4317 // These are the proper values we need for right-justifying the
4318 // aggregate in a parameter register.
4319 unsigned Size = Flags.getByValSize();
4321 // An empty aggregate parameter takes up no storage and no
4326 // All aggregates smaller than 8 bytes must be passed right-justified.
4327 if (Size==1 || Size==2 || Size==4) {
4328 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4329 if (GPR_idx != NumGPRs) {
4330 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4331 MachinePointerInfo(), VT,
4332 false, false, false, 0);
4333 MemOpChains.push_back(Load.getValue(1));
4334 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4336 ArgOffset += PtrByteSize;
4341 if (GPR_idx == NumGPRs && Size < 8) {
4342 SDValue AddPtr = PtrOff;
4343 if (!isLittleEndian) {
4344 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4345 PtrOff.getValueType());
4346 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4348 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4351 ArgOffset += PtrByteSize;
4354 // Copy entire object into memory. There are cases where gcc-generated
4355 // code assumes it is there, even if it could be put entirely into
4356 // registers. (This is not what the doc says.)
4358 // FIXME: The above statement is likely due to a misunderstanding of the
4359 // documents. All arguments must be copied into the parameter area BY
4360 // THE CALLEE in the event that the callee takes the address of any
4361 // formal argument. That has not yet been implemented. However, it is
4362 // reasonable to use the stack area as a staging area for the register
4365 // Skip this for small aggregates, as we will use the same slot for a
4366 // right-justified copy, below.
4368 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4372 // When a register is available, pass a small aggregate right-justified.
4373 if (Size < 8 && GPR_idx != NumGPRs) {
4374 // The easiest way to get this right-justified in a register
4375 // is to copy the structure into the rightmost portion of a
4376 // local variable slot, then load the whole slot into the
4378 // FIXME: The memcpy seems to produce pretty awful code for
4379 // small aggregates, particularly for packed ones.
4380 // FIXME: It would be preferable to use the slot in the
4381 // parameter save area instead of a new local variable.
4382 SDValue AddPtr = PtrOff;
4383 if (!isLittleEndian) {
4384 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4385 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4387 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4391 // Load the slot into the register.
4392 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4393 MachinePointerInfo(),
4394 false, false, false, 0);
4395 MemOpChains.push_back(Load.getValue(1));
4396 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4398 // Done with this argument.
4399 ArgOffset += PtrByteSize;
4403 // For aggregates larger than PtrByteSize, copy the pieces of the
4404 // object that fit into registers from the parameter save area.
4405 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4406 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4407 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4408 if (GPR_idx != NumGPRs) {
4409 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4410 MachinePointerInfo(),
4411 false, false, false, 0);
4412 MemOpChains.push_back(Load.getValue(1));
4413 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4414 ArgOffset += PtrByteSize;
4416 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4423 switch (Arg.getSimpleValueType().SimpleTy) {
4424 default: llvm_unreachable("Unexpected ValueType for argument!");
4428 // These can be scalar arguments or elements of an integer array type
4429 // passed directly. Clang may use those instead of "byval" aggregate
4430 // types to avoid forcing arguments to memory unnecessarily.
4431 if (GPR_idx != NumGPRs) {
4432 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4434 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4435 true, isTailCall, false, MemOpChains,
4436 TailCallArguments, dl);
4438 ArgOffset += PtrByteSize;
4442 // These can be scalar arguments or elements of a float array type
4443 // passed directly. The latter are used to implement ELFv2 homogenous
4444 // float aggregates.
4446 // Named arguments go into FPRs first, and once they overflow, the
4447 // remaining arguments go into GPRs and then the parameter save area.
4448 // Unnamed arguments for vararg functions always go to GPRs and
4449 // then the parameter save area. For now, put all arguments to vararg
4450 // routines always in both locations (FPR *and* GPR or stack slot).
4451 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4453 // First load the argument into the next available FPR.
4454 if (FPR_idx != NumFPRs)
4455 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4457 // Next, load the argument into GPR or stack slot if needed.
4458 if (!NeedGPROrStack)
4460 else if (GPR_idx != NumGPRs) {
4461 // In the non-vararg case, this can only ever happen in the
4462 // presence of f32 array types, since otherwise we never run
4463 // out of FPRs before running out of GPRs.
4466 // Double values are always passed in a single GPR.
4467 if (Arg.getValueType() != MVT::f32) {
4468 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4470 // Non-array float values are extended and passed in a GPR.
4471 } else if (!Flags.isInConsecutiveRegs()) {
4472 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4473 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4475 // If we have an array of floats, we collect every odd element
4476 // together with its predecessor into one GPR.
4477 } else if (ArgOffset % PtrByteSize != 0) {
4479 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4480 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4481 if (!isLittleEndian)
4483 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4485 // The final element, if even, goes into the first half of a GPR.
4486 } else if (Flags.isInConsecutiveRegsLast()) {
4487 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4488 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4489 if (!isLittleEndian)
4490 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4491 DAG.getConstant(32, MVT::i32));
4493 // Non-final even elements are skipped; they will be handled
4494 // together the with subsequent argument on the next go-around.
4498 if (ArgVal.getNode())
4499 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4501 // Single-precision floating-point values are mapped to the
4502 // second (rightmost) word of the stack doubleword.
4503 if (Arg.getValueType() == MVT::f32 &&
4504 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4505 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4506 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4509 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4510 true, isTailCall, false, MemOpChains,
4511 TailCallArguments, dl);
4513 // When passing an array of floats, the array occupies consecutive
4514 // space in the argument area; only round up to the next doubleword
4515 // at the end of the array. Otherwise, each float takes 8 bytes.
4516 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4517 Flags.isInConsecutiveRegs()) ? 4 : 8;
4518 if (Flags.isInConsecutiveRegsLast())
4519 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4528 // These can be scalar arguments or elements of a vector array type
4529 // passed directly. The latter are used to implement ELFv2 homogenous
4530 // vector aggregates.
4532 // For a varargs call, named arguments go into VRs or on the stack as
4533 // usual; unnamed arguments always go to the stack or the corresponding
4534 // GPRs when within range. For now, we always put the value in both
4535 // locations (or even all three).
4537 // We could elide this store in the case where the object fits
4538 // entirely in R registers. Maybe later.
4539 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4540 MachinePointerInfo(), false, false, 0);
4541 MemOpChains.push_back(Store);
4542 if (VR_idx != NumVRs) {
4543 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4544 MachinePointerInfo(),
4545 false, false, false, 0);
4546 MemOpChains.push_back(Load.getValue(1));
4548 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4549 Arg.getSimpleValueType() == MVT::v2i64) ?
4550 VSRH[VR_idx] : VR[VR_idx];
4553 RegsToPass.push_back(std::make_pair(VReg, Load));
4556 for (unsigned i=0; i<16; i+=PtrByteSize) {
4557 if (GPR_idx == NumGPRs)
4559 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4560 DAG.getConstant(i, PtrVT));
4561 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4562 false, false, false, 0);
4563 MemOpChains.push_back(Load.getValue(1));
4564 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4569 // Non-varargs Altivec params go into VRs or on the stack.
4570 if (VR_idx != NumVRs) {
4571 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4572 Arg.getSimpleValueType() == MVT::v2i64) ?
4573 VSRH[VR_idx] : VR[VR_idx];
4576 RegsToPass.push_back(std::make_pair(VReg, Arg));
4578 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4579 true, isTailCall, true, MemOpChains,
4580 TailCallArguments, dl);
4587 assert(NumBytesActuallyUsed == ArgOffset);
4588 (void)NumBytesActuallyUsed;
4590 if (!MemOpChains.empty())
4591 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4593 // Check if this is an indirect call (MTCTR/BCTRL).
4594 // See PrepareCall() for more information about calls through function
4595 // pointers in the 64-bit SVR4 ABI.
4597 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4598 !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4599 // Load r2 into a virtual register and store it to the TOC save area.
4600 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4601 // TOC save area offset.
4602 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4603 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4604 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4605 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4607 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4608 // This does not mean the MTCTR instruction must use R12; it's easier
4609 // to model this as an extra parameter, so do that.
4611 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4614 // Build a sequence of copy-to-reg nodes chained together with token chain
4615 // and flag operands which copy the outgoing args into the appropriate regs.
4617 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4618 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4619 RegsToPass[i].second, InFlag);
4620 InFlag = Chain.getValue(1);
4624 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4625 FPOp, true, TailCallArguments);
4627 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4628 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4633 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4634 CallingConv::ID CallConv, bool isVarArg,
4636 const SmallVectorImpl<ISD::OutputArg> &Outs,
4637 const SmallVectorImpl<SDValue> &OutVals,
4638 const SmallVectorImpl<ISD::InputArg> &Ins,
4639 SDLoc dl, SelectionDAG &DAG,
4640 SmallVectorImpl<SDValue> &InVals) const {
4642 unsigned NumOps = Outs.size();
4644 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4645 bool isPPC64 = PtrVT == MVT::i64;
4646 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4648 MachineFunction &MF = DAG.getMachineFunction();
4650 // Mark this function as potentially containing a function that contains a
4651 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4652 // and restoring the callers stack pointer in this functions epilog. This is
4653 // done because by tail calling the called function might overwrite the value
4654 // in this function's (MF) stack pointer stack slot 0(SP).
4655 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4656 CallConv == CallingConv::Fast)
4657 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4659 // Count how many bytes are to be pushed on the stack, including the linkage
4660 // area, and parameter passing area. We start with 24/48 bytes, which is
4661 // prereserved space for [SP][CR][LR][3 x unused].
4662 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4664 unsigned NumBytes = LinkageSize;
4666 // Add up all the space actually used.
4667 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4668 // they all go in registers, but we must reserve stack space for them for
4669 // possible use by the caller. In varargs or 64-bit calls, parameters are
4670 // assigned stack space in order, with padding so Altivec parameters are
4672 unsigned nAltivecParamsAtEnd = 0;
4673 for (unsigned i = 0; i != NumOps; ++i) {
4674 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4675 EVT ArgVT = Outs[i].VT;
4676 // Varargs Altivec parameters are padded to a 16 byte boundary.
4677 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4678 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4679 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4680 if (!isVarArg && !isPPC64) {
4681 // Non-varargs Altivec parameters go after all the non-Altivec
4682 // parameters; handle those later so we know how much padding we need.
4683 nAltivecParamsAtEnd++;
4686 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4687 NumBytes = ((NumBytes+15)/16)*16;
4689 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4692 // Allow for Altivec parameters at the end, if needed.
4693 if (nAltivecParamsAtEnd) {
4694 NumBytes = ((NumBytes+15)/16)*16;
4695 NumBytes += 16*nAltivecParamsAtEnd;
4698 // The prolog code of the callee may store up to 8 GPR argument registers to
4699 // the stack, allowing va_start to index over them in memory if its varargs.
4700 // Because we cannot tell if this is needed on the caller side, we have to
4701 // conservatively assume that it is needed. As such, make sure we have at
4702 // least enough stack space for the caller to store the 8 GPRs.
4703 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4705 // Tail call needs the stack to be aligned.
4706 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4707 CallConv == CallingConv::Fast)
4708 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4710 // Calculate by how many bytes the stack has to be adjusted in case of tail
4711 // call optimization.
4712 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4714 // To protect arguments on the stack from being clobbered in a tail call,
4715 // force all the loads to happen before doing any other lowering.
4717 Chain = DAG.getStackArgumentTokenFactor(Chain);
4719 // Adjust the stack pointer for the new arguments...
4720 // These operations are automatically eliminated by the prolog/epilog pass
4721 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4723 SDValue CallSeqStart = Chain;
4725 // Load the return address and frame pointer so it can be move somewhere else
4728 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4731 // Set up a copy of the stack pointer for use loading and storing any
4732 // arguments that may not fit in the registers available for argument
4736 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4738 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4740 // Figure out which arguments are going to go in registers, and which in
4741 // memory. Also, if this is a vararg function, floating point operations
4742 // must be stored to our stack, and loaded into integer regs as well, if
4743 // any integer regs are available for argument passing.
4744 unsigned ArgOffset = LinkageSize;
4745 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4747 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4748 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4749 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4751 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4752 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4753 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4755 static const MCPhysReg *FPR = GetFPR();
4757 static const MCPhysReg VR[] = {
4758 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4759 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4761 const unsigned NumGPRs = array_lengthof(GPR_32);
4762 const unsigned NumFPRs = 13;
4763 const unsigned NumVRs = array_lengthof(VR);
4765 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4767 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4768 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4770 SmallVector<SDValue, 8> MemOpChains;
4771 for (unsigned i = 0; i != NumOps; ++i) {
4772 SDValue Arg = OutVals[i];
4773 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4775 // PtrOff will be used to store the current argument to the stack if a
4776 // register cannot be found for it.
4779 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4781 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4783 // On PPC64, promote integers to 64-bit values.
4784 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4785 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4786 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4787 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4790 // FIXME memcpy is used way more than necessary. Correctness first.
4791 // Note: "by value" is code for passing a structure by value, not
4793 if (Flags.isByVal()) {
4794 unsigned Size = Flags.getByValSize();
4795 // Very small objects are passed right-justified. Everything else is
4796 // passed left-justified.
4797 if (Size==1 || Size==2) {
4798 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4799 if (GPR_idx != NumGPRs) {
4800 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4801 MachinePointerInfo(), VT,
4802 false, false, false, 0);
4803 MemOpChains.push_back(Load.getValue(1));
4804 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4806 ArgOffset += PtrByteSize;
4808 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4809 PtrOff.getValueType());
4810 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4811 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4814 ArgOffset += PtrByteSize;
4818 // Copy entire object into memory. There are cases where gcc-generated
4819 // code assumes it is there, even if it could be put entirely into
4820 // registers. (This is not what the doc says.)
4821 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4825 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4826 // copy the pieces of the object that fit into registers from the
4827 // parameter save area.
4828 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4829 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4830 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4831 if (GPR_idx != NumGPRs) {
4832 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4833 MachinePointerInfo(),
4834 false, false, false, 0);
4835 MemOpChains.push_back(Load.getValue(1));
4836 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4837 ArgOffset += PtrByteSize;
4839 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4846 switch (Arg.getSimpleValueType().SimpleTy) {
4847 default: llvm_unreachable("Unexpected ValueType for argument!");
4851 if (GPR_idx != NumGPRs) {
4852 if (Arg.getValueType() == MVT::i1)
4853 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4855 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4857 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4858 isPPC64, isTailCall, false, MemOpChains,
4859 TailCallArguments, dl);
4861 ArgOffset += PtrByteSize;
4865 if (FPR_idx != NumFPRs) {
4866 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4869 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4870 MachinePointerInfo(), false, false, 0);
4871 MemOpChains.push_back(Store);
4873 // Float varargs are always shadowed in available integer registers
4874 if (GPR_idx != NumGPRs) {
4875 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4876 MachinePointerInfo(), false, false,
4878 MemOpChains.push_back(Load.getValue(1));
4879 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4881 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4882 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4883 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4884 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4885 MachinePointerInfo(),
4886 false, false, false, 0);
4887 MemOpChains.push_back(Load.getValue(1));
4888 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4891 // If we have any FPRs remaining, we may also have GPRs remaining.
4892 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4894 if (GPR_idx != NumGPRs)
4896 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4897 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4901 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4902 isPPC64, isTailCall, false, MemOpChains,
4903 TailCallArguments, dl);
4907 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4914 // These go aligned on the stack, or in the corresponding R registers
4915 // when within range. The Darwin PPC ABI doc claims they also go in
4916 // V registers; in fact gcc does this only for arguments that are
4917 // prototyped, not for those that match the ... We do it for all
4918 // arguments, seems to work.
4919 while (ArgOffset % 16 !=0) {
4920 ArgOffset += PtrByteSize;
4921 if (GPR_idx != NumGPRs)
4924 // We could elide this store in the case where the object fits
4925 // entirely in R registers. Maybe later.
4926 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4927 DAG.getConstant(ArgOffset, PtrVT));
4928 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4929 MachinePointerInfo(), false, false, 0);
4930 MemOpChains.push_back(Store);
4931 if (VR_idx != NumVRs) {
4932 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4933 MachinePointerInfo(),
4934 false, false, false, 0);
4935 MemOpChains.push_back(Load.getValue(1));
4936 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4939 for (unsigned i=0; i<16; i+=PtrByteSize) {
4940 if (GPR_idx == NumGPRs)
4942 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4943 DAG.getConstant(i, PtrVT));
4944 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4945 false, false, false, 0);
4946 MemOpChains.push_back(Load.getValue(1));
4947 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4952 // Non-varargs Altivec params generally go in registers, but have
4953 // stack space allocated at the end.
4954 if (VR_idx != NumVRs) {
4955 // Doesn't have GPR space allocated.
4956 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4957 } else if (nAltivecParamsAtEnd==0) {
4958 // We are emitting Altivec params in order.
4959 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4960 isPPC64, isTailCall, true, MemOpChains,
4961 TailCallArguments, dl);
4967 // If all Altivec parameters fit in registers, as they usually do,
4968 // they get stack space following the non-Altivec parameters. We
4969 // don't track this here because nobody below needs it.
4970 // If there are more Altivec parameters than fit in registers emit
4972 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4974 // Offset is aligned; skip 1st 12 params which go in V registers.
4975 ArgOffset = ((ArgOffset+15)/16)*16;
4977 for (unsigned i = 0; i != NumOps; ++i) {
4978 SDValue Arg = OutVals[i];
4979 EVT ArgType = Outs[i].VT;
4980 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4981 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4984 // We are emitting Altivec params in order.
4985 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4986 isPPC64, isTailCall, true, MemOpChains,
4987 TailCallArguments, dl);
4994 if (!MemOpChains.empty())
4995 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4997 // On Darwin, R12 must contain the address of an indirect callee. This does
4998 // not mean the MTCTR instruction must use R12; it's easier to model this as
4999 // an extra parameter, so do that.
5001 !dyn_cast<GlobalAddressSDNode>(Callee) &&
5002 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
5003 !isBLACompatibleAddress(Callee, DAG))
5004 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5005 PPC::R12), Callee));
5007 // Build a sequence of copy-to-reg nodes chained together with token chain
5008 // and flag operands which copy the outgoing args into the appropriate regs.
5010 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5011 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5012 RegsToPass[i].second, InFlag);
5013 InFlag = Chain.getValue(1);
5017 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5018 FPOp, true, TailCallArguments);
5020 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5021 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5026 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5027 MachineFunction &MF, bool isVarArg,
5028 const SmallVectorImpl<ISD::OutputArg> &Outs,
5029 LLVMContext &Context) const {
5030 SmallVector<CCValAssign, 16> RVLocs;
5031 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
5033 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5037 PPCTargetLowering::LowerReturn(SDValue Chain,
5038 CallingConv::ID CallConv, bool isVarArg,
5039 const SmallVectorImpl<ISD::OutputArg> &Outs,
5040 const SmallVectorImpl<SDValue> &OutVals,
5041 SDLoc dl, SelectionDAG &DAG) const {
5043 SmallVector<CCValAssign, 16> RVLocs;
5044 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
5045 getTargetMachine(), RVLocs, *DAG.getContext());
5046 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5049 SmallVector<SDValue, 4> RetOps(1, Chain);
5051 // Copy the result values into the output registers.
5052 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5053 CCValAssign &VA = RVLocs[i];
5054 assert(VA.isRegLoc() && "Can only return in registers!");
5056 SDValue Arg = OutVals[i];
5058 switch (VA.getLocInfo()) {
5059 default: llvm_unreachable("Unknown loc info!");
5060 case CCValAssign::Full: break;
5061 case CCValAssign::AExt:
5062 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5064 case CCValAssign::ZExt:
5065 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5067 case CCValAssign::SExt:
5068 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5072 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5073 Flag = Chain.getValue(1);
5074 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5077 RetOps[0] = Chain; // Update chain.
5079 // Add the flag if we have it.
5081 RetOps.push_back(Flag);
5083 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5086 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5087 const PPCSubtarget &Subtarget) const {
5088 // When we pop the dynamic allocation we need to restore the SP link.
5091 // Get the corect type for pointers.
5092 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5094 // Construct the stack pointer operand.
5095 bool isPPC64 = Subtarget.isPPC64();
5096 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5097 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5099 // Get the operands for the STACKRESTORE.
5100 SDValue Chain = Op.getOperand(0);
5101 SDValue SaveSP = Op.getOperand(1);
5103 // Load the old link SP.
5104 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5105 MachinePointerInfo(),
5106 false, false, false, 0);
5108 // Restore the stack pointer.
5109 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5111 // Store the old link SP.
5112 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5119 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5120 MachineFunction &MF = DAG.getMachineFunction();
5121 bool isPPC64 = Subtarget.isPPC64();
5122 bool isDarwinABI = Subtarget.isDarwinABI();
5123 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5125 // Get current frame pointer save index. The users of this index will be
5126 // primarily DYNALLOC instructions.
5127 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5128 int RASI = FI->getReturnAddrSaveIndex();
5130 // If the frame pointer save index hasn't been defined yet.
5132 // Find out what the fix offset of the frame pointer save area.
5133 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5134 // Allocate the frame index for frame pointer save area.
5135 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
5137 FI->setReturnAddrSaveIndex(RASI);
5139 return DAG.getFrameIndex(RASI, PtrVT);
5143 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5144 MachineFunction &MF = DAG.getMachineFunction();
5145 bool isPPC64 = Subtarget.isPPC64();
5146 bool isDarwinABI = Subtarget.isDarwinABI();
5147 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5149 // Get current frame pointer save index. The users of this index will be
5150 // primarily DYNALLOC instructions.
5151 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5152 int FPSI = FI->getFramePointerSaveIndex();
5154 // If the frame pointer save index hasn't been defined yet.
5156 // Find out what the fix offset of the frame pointer save area.
5157 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5160 // Allocate the frame index for frame pointer save area.
5161 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5163 FI->setFramePointerSaveIndex(FPSI);
5165 return DAG.getFrameIndex(FPSI, PtrVT);
5168 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5170 const PPCSubtarget &Subtarget) const {
5172 SDValue Chain = Op.getOperand(0);
5173 SDValue Size = Op.getOperand(1);
5176 // Get the corect type for pointers.
5177 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5179 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5180 DAG.getConstant(0, PtrVT), Size);
5181 // Construct a node for the frame pointer save index.
5182 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5183 // Build a DYNALLOC node.
5184 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5185 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5186 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5189 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5190 SelectionDAG &DAG) const {
5192 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5193 DAG.getVTList(MVT::i32, MVT::Other),
5194 Op.getOperand(0), Op.getOperand(1));
5197 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5198 SelectionDAG &DAG) const {
5200 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5201 Op.getOperand(0), Op.getOperand(1));
5204 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5205 assert(Op.getValueType() == MVT::i1 &&
5206 "Custom lowering only for i1 loads");
5208 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5211 LoadSDNode *LD = cast<LoadSDNode>(Op);
5213 SDValue Chain = LD->getChain();
5214 SDValue BasePtr = LD->getBasePtr();
5215 MachineMemOperand *MMO = LD->getMemOperand();
5217 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5218 BasePtr, MVT::i8, MMO);
5219 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5221 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5222 return DAG.getMergeValues(Ops, dl);
5225 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5226 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5227 "Custom lowering only for i1 stores");
5229 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5232 StoreSDNode *ST = cast<StoreSDNode>(Op);
5234 SDValue Chain = ST->getChain();
5235 SDValue BasePtr = ST->getBasePtr();
5236 SDValue Value = ST->getValue();
5237 MachineMemOperand *MMO = ST->getMemOperand();
5239 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5240 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5243 // FIXME: Remove this once the ANDI glue bug is fixed:
5244 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5245 assert(Op.getValueType() == MVT::i1 &&
5246 "Custom lowering only for i1 results");
5249 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5253 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5255 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5256 // Not FP? Not a fsel.
5257 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5258 !Op.getOperand(2).getValueType().isFloatingPoint())
5261 // We might be able to do better than this under some circumstances, but in
5262 // general, fsel-based lowering of select is a finite-math-only optimization.
5263 // For more information, see section F.3 of the 2.06 ISA specification.
5264 if (!DAG.getTarget().Options.NoInfsFPMath ||
5265 !DAG.getTarget().Options.NoNaNsFPMath)
5268 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5270 EVT ResVT = Op.getValueType();
5271 EVT CmpVT = Op.getOperand(0).getValueType();
5272 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5273 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5276 // If the RHS of the comparison is a 0.0, we don't need to do the
5277 // subtraction at all.
5279 if (isFloatingPointZero(RHS))
5281 default: break; // SETUO etc aren't handled by fsel.
5285 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5286 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5287 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5288 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5289 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5290 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5291 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5294 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5297 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5298 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5299 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5302 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5305 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5306 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5307 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5308 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5313 default: break; // SETUO etc aren't handled by fsel.
5317 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5318 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5319 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5320 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5321 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5322 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5323 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5324 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5327 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5328 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5329 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5330 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5333 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5334 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5335 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5336 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5339 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5340 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5341 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5342 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5345 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5346 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5347 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5348 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5353 // FIXME: Split this code up when LegalizeDAGTypes lands.
5354 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5356 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5357 SDValue Src = Op.getOperand(0);
5358 if (Src.getValueType() == MVT::f32)
5359 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5362 switch (Op.getSimpleValueType().SimpleTy) {
5363 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5365 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5366 (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5371 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5372 "i64 FP_TO_UINT is supported only with FPCVT");
5373 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5379 // Convert the FP value to an int value through memory.
5380 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5381 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5382 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5383 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5384 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5386 // Emit a store to the stack slot.
5389 MachineFunction &MF = DAG.getMachineFunction();
5390 MachineMemOperand *MMO =
5391 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5392 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5393 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5394 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5396 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5397 MPI, false, false, 0);
5399 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5401 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5402 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5403 DAG.getConstant(4, FIPtr.getValueType()));
5404 MPI = MachinePointerInfo();
5407 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5408 false, false, false, 0);
5411 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5412 SelectionDAG &DAG) const {
5414 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5415 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5418 if (Op.getOperand(0).getValueType() == MVT::i1)
5419 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5420 DAG.getConstantFP(1.0, Op.getValueType()),
5421 DAG.getConstantFP(0.0, Op.getValueType()));
5423 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5424 "UINT_TO_FP is supported only with FPCVT");
5426 // If we have FCFIDS, then use it when converting to single-precision.
5427 // Otherwise, convert to double-precision and then round.
5428 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5429 (Op.getOpcode() == ISD::UINT_TO_FP ?
5430 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5431 (Op.getOpcode() == ISD::UINT_TO_FP ?
5432 PPCISD::FCFIDU : PPCISD::FCFID);
5433 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5434 MVT::f32 : MVT::f64;
5436 if (Op.getOperand(0).getValueType() == MVT::i64) {
5437 SDValue SINT = Op.getOperand(0);
5438 // When converting to single-precision, we actually need to convert
5439 // to double-precision first and then round to single-precision.
5440 // To avoid double-rounding effects during that operation, we have
5441 // to prepare the input operand. Bits that might be truncated when
5442 // converting to double-precision are replaced by a bit that won't
5443 // be lost at this stage, but is below the single-precision rounding
5446 // However, if -enable-unsafe-fp-math is in effect, accept double
5447 // rounding to avoid the extra overhead.
5448 if (Op.getValueType() == MVT::f32 &&
5449 !Subtarget.hasFPCVT() &&
5450 !DAG.getTarget().Options.UnsafeFPMath) {
5452 // Twiddle input to make sure the low 11 bits are zero. (If this
5453 // is the case, we are guaranteed the value will fit into the 53 bit
5454 // mantissa of an IEEE double-precision value without rounding.)
5455 // If any of those low 11 bits were not zero originally, make sure
5456 // bit 12 (value 2048) is set instead, so that the final rounding
5457 // to single-precision gets the correct result.
5458 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5459 SINT, DAG.getConstant(2047, MVT::i64));
5460 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5461 Round, DAG.getConstant(2047, MVT::i64));
5462 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5463 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5464 Round, DAG.getConstant(-2048, MVT::i64));
5466 // However, we cannot use that value unconditionally: if the magnitude
5467 // of the input value is small, the bit-twiddling we did above might
5468 // end up visibly changing the output. Fortunately, in that case, we
5469 // don't need to twiddle bits since the original input will convert
5470 // exactly to double-precision floating-point already. Therefore,
5471 // construct a conditional to use the original value if the top 11
5472 // bits are all sign-bit copies, and use the rounded value computed
5474 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5475 SINT, DAG.getConstant(53, MVT::i32));
5476 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5477 Cond, DAG.getConstant(1, MVT::i64));
5478 Cond = DAG.getSetCC(dl, MVT::i32,
5479 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5481 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5484 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5485 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5487 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5488 FP = DAG.getNode(ISD::FP_ROUND, dl,
5489 MVT::f32, FP, DAG.getIntPtrConstant(0));
5493 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5494 "Unhandled INT_TO_FP type in custom expander!");
5495 // Since we only generate this in 64-bit mode, we can take advantage of
5496 // 64-bit registers. In particular, sign extend the input value into the
5497 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5498 // then lfd it and fcfid it.
5499 MachineFunction &MF = DAG.getMachineFunction();
5500 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5501 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5504 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5505 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5506 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5508 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5509 MachinePointerInfo::getFixedStack(FrameIdx),
5512 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5513 "Expected an i32 store");
5514 MachineMemOperand *MMO =
5515 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5516 MachineMemOperand::MOLoad, 4, 4);
5517 SDValue Ops[] = { Store, FIdx };
5518 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5519 PPCISD::LFIWZX : PPCISD::LFIWAX,
5520 dl, DAG.getVTList(MVT::f64, MVT::Other),
5521 Ops, MVT::i32, MMO);
5523 assert(Subtarget.isPPC64() &&
5524 "i32->FP without LFIWAX supported only on PPC64");
5526 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5527 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5529 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5532 // STD the extended value into the stack slot.
5533 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5534 MachinePointerInfo::getFixedStack(FrameIdx),
5537 // Load the value as a double.
5538 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5539 MachinePointerInfo::getFixedStack(FrameIdx),
5540 false, false, false, 0);
5543 // FCFID it and return it.
5544 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5545 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5546 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5550 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5551 SelectionDAG &DAG) const {
5554 The rounding mode is in bits 30:31 of FPSR, and has the following
5561 FLT_ROUNDS, on the other hand, expects the following:
5568 To perform the conversion, we do:
5569 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5572 MachineFunction &MF = DAG.getMachineFunction();
5573 EVT VT = Op.getValueType();
5574 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5576 // Save FP Control Word to register
5578 MVT::f64, // return register
5579 MVT::Glue // unused in this context
5581 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5583 // Save FP register to stack slot
5584 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5585 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5586 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5587 StackSlot, MachinePointerInfo(), false, false,0);
5589 // Load FP Control Word from low 32 bits of stack slot.
5590 SDValue Four = DAG.getConstant(4, PtrVT);
5591 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5592 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5593 false, false, false, 0);
5595 // Transform as necessary
5597 DAG.getNode(ISD::AND, dl, MVT::i32,
5598 CWD, DAG.getConstant(3, MVT::i32));
5600 DAG.getNode(ISD::SRL, dl, MVT::i32,
5601 DAG.getNode(ISD::AND, dl, MVT::i32,
5602 DAG.getNode(ISD::XOR, dl, MVT::i32,
5603 CWD, DAG.getConstant(3, MVT::i32)),
5604 DAG.getConstant(3, MVT::i32)),
5605 DAG.getConstant(1, MVT::i32));
5608 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5610 return DAG.getNode((VT.getSizeInBits() < 16 ?
5611 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5614 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5615 EVT VT = Op.getValueType();
5616 unsigned BitWidth = VT.getSizeInBits();
5618 assert(Op.getNumOperands() == 3 &&
5619 VT == Op.getOperand(1).getValueType() &&
5622 // Expand into a bunch of logical ops. Note that these ops
5623 // depend on the PPC behavior for oversized shift amounts.
5624 SDValue Lo = Op.getOperand(0);
5625 SDValue Hi = Op.getOperand(1);
5626 SDValue Amt = Op.getOperand(2);
5627 EVT AmtVT = Amt.getValueType();
5629 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5630 DAG.getConstant(BitWidth, AmtVT), Amt);
5631 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5632 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5633 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5634 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5635 DAG.getConstant(-BitWidth, AmtVT));
5636 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5637 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5638 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5639 SDValue OutOps[] = { OutLo, OutHi };
5640 return DAG.getMergeValues(OutOps, dl);
5643 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5644 EVT VT = Op.getValueType();
5646 unsigned BitWidth = VT.getSizeInBits();
5647 assert(Op.getNumOperands() == 3 &&
5648 VT == Op.getOperand(1).getValueType() &&
5651 // Expand into a bunch of logical ops. Note that these ops
5652 // depend on the PPC behavior for oversized shift amounts.
5653 SDValue Lo = Op.getOperand(0);
5654 SDValue Hi = Op.getOperand(1);
5655 SDValue Amt = Op.getOperand(2);
5656 EVT AmtVT = Amt.getValueType();
5658 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5659 DAG.getConstant(BitWidth, AmtVT), Amt);
5660 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5661 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5662 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5663 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5664 DAG.getConstant(-BitWidth, AmtVT));
5665 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5666 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5667 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5668 SDValue OutOps[] = { OutLo, OutHi };
5669 return DAG.getMergeValues(OutOps, dl);
5672 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5674 EVT VT = Op.getValueType();
5675 unsigned BitWidth = VT.getSizeInBits();
5676 assert(Op.getNumOperands() == 3 &&
5677 VT == Op.getOperand(1).getValueType() &&
5680 // Expand into a bunch of logical ops, followed by a select_cc.
5681 SDValue Lo = Op.getOperand(0);
5682 SDValue Hi = Op.getOperand(1);
5683 SDValue Amt = Op.getOperand(2);
5684 EVT AmtVT = Amt.getValueType();
5686 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5687 DAG.getConstant(BitWidth, AmtVT), Amt);
5688 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5689 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5690 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5691 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5692 DAG.getConstant(-BitWidth, AmtVT));
5693 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5694 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5695 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5696 Tmp4, Tmp6, ISD::SETLE);
5697 SDValue OutOps[] = { OutLo, OutHi };
5698 return DAG.getMergeValues(OutOps, dl);
5701 //===----------------------------------------------------------------------===//
5702 // Vector related lowering.
5705 /// BuildSplatI - Build a canonical splati of Val with an element size of
5706 /// SplatSize. Cast the result to VT.
5707 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5708 SelectionDAG &DAG, SDLoc dl) {
5709 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5711 static const EVT VTys[] = { // canonical VT to use for each size.
5712 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5715 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5717 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5721 EVT CanonicalVT = VTys[SplatSize-1];
5723 // Build a canonical splat for this value.
5724 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5725 SmallVector<SDValue, 8> Ops;
5726 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5727 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5728 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5731 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5732 /// specified intrinsic ID.
5733 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5734 SelectionDAG &DAG, SDLoc dl,
5735 EVT DestVT = MVT::Other) {
5736 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5737 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5738 DAG.getConstant(IID, MVT::i32), Op);
5741 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5742 /// specified intrinsic ID.
5743 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5744 SelectionDAG &DAG, SDLoc dl,
5745 EVT DestVT = MVT::Other) {
5746 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5747 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5748 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5751 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5752 /// specified intrinsic ID.
5753 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5754 SDValue Op2, SelectionDAG &DAG,
5755 SDLoc dl, EVT DestVT = MVT::Other) {
5756 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5757 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5758 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5762 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5763 /// amount. The result has the specified value type.
5764 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5765 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5766 // Force LHS/RHS to be the right type.
5767 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5768 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5771 for (unsigned i = 0; i != 16; ++i)
5773 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5774 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5777 // If this is a case we can't handle, return null and let the default
5778 // expansion code take care of it. If we CAN select this case, and if it
5779 // selects to a single instruction, return Op. Otherwise, if we can codegen
5780 // this case more efficiently than a constant pool load, lower it to the
5781 // sequence of ops that should be used.
5782 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5783 SelectionDAG &DAG) const {
5785 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5786 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5788 // Check if this is a splat of a constant value.
5789 APInt APSplatBits, APSplatUndef;
5790 unsigned SplatBitSize;
5792 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5793 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5796 unsigned SplatBits = APSplatBits.getZExtValue();
5797 unsigned SplatUndef = APSplatUndef.getZExtValue();
5798 unsigned SplatSize = SplatBitSize / 8;
5800 // First, handle single instruction cases.
5803 if (SplatBits == 0) {
5804 // Canonicalize all zero vectors to be v4i32.
5805 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5806 SDValue Z = DAG.getConstant(0, MVT::i32);
5807 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5808 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5813 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5814 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5816 if (SextVal >= -16 && SextVal <= 15)
5817 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5820 // Two instruction sequences.
5822 // If this value is in the range [-32,30] and is even, use:
5823 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5824 // If this value is in the range [17,31] and is odd, use:
5825 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5826 // If this value is in the range [-31,-17] and is odd, use:
5827 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5828 // Note the last two are three-instruction sequences.
5829 if (SextVal >= -32 && SextVal <= 31) {
5830 // To avoid having these optimizations undone by constant folding,
5831 // we convert to a pseudo that will be expanded later into one of
5833 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5834 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5835 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5836 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5837 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5838 if (VT == Op.getValueType())
5841 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5844 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5845 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5847 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5848 // Make -1 and vspltisw -1:
5849 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5851 // Make the VSLW intrinsic, computing 0x8000_0000.
5852 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5855 // xor by OnesV to invert it.
5856 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5857 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5860 // The remaining cases assume either big endian element order or
5861 // a splat-size that equates to the element size of the vector
5862 // to be built. An example that doesn't work for little endian is
5863 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5864 // and a vector element size of 16 bits. The code below will
5865 // produce the vector in big endian element order, which for little
5866 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5868 // For now, just avoid these optimizations in that case.
5869 // FIXME: Develop correct optimizations for LE with mismatched
5870 // splat and element sizes.
5872 if (Subtarget.isLittleEndian() &&
5873 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5876 // Check to see if this is a wide variety of vsplti*, binop self cases.
5877 static const signed char SplatCsts[] = {
5878 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5879 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5882 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5883 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5884 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5885 int i = SplatCsts[idx];
5887 // Figure out what shift amount will be used by altivec if shifted by i in
5889 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5891 // vsplti + shl self.
5892 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5893 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5894 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5895 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5896 Intrinsic::ppc_altivec_vslw
5898 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5899 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5902 // vsplti + srl self.
5903 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5904 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5905 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5906 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5907 Intrinsic::ppc_altivec_vsrw
5909 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5910 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5913 // vsplti + sra self.
5914 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5915 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5916 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5917 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5918 Intrinsic::ppc_altivec_vsraw
5920 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5921 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5924 // vsplti + rol self.
5925 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5926 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5927 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5928 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5929 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5930 Intrinsic::ppc_altivec_vrlw
5932 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5933 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5936 // t = vsplti c, result = vsldoi t, t, 1
5937 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5938 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5939 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5941 // t = vsplti c, result = vsldoi t, t, 2
5942 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5943 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5944 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5946 // t = vsplti c, result = vsldoi t, t, 3
5947 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5948 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5949 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5956 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5957 /// the specified operations to build the shuffle.
5958 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5959 SDValue RHS, SelectionDAG &DAG,
5961 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5962 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5963 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5966 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5978 if (OpNum == OP_COPY) {
5979 if (LHSID == (1*9+2)*9+3) return LHS;
5980 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5984 SDValue OpLHS, OpRHS;
5985 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5986 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5990 default: llvm_unreachable("Unknown i32 permute!");
5992 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5993 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5994 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5995 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5998 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5999 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6000 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6001 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6004 for (unsigned i = 0; i != 16; ++i)
6005 ShufIdxs[i] = (i&3)+0;
6008 for (unsigned i = 0; i != 16; ++i)
6009 ShufIdxs[i] = (i&3)+4;
6012 for (unsigned i = 0; i != 16; ++i)
6013 ShufIdxs[i] = (i&3)+8;
6016 for (unsigned i = 0; i != 16; ++i)
6017 ShufIdxs[i] = (i&3)+12;
6020 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6022 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6024 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6026 EVT VT = OpLHS.getValueType();
6027 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6028 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6029 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6030 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6033 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6034 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6035 /// return the code it can be lowered into. Worst case, it can always be
6036 /// lowered into a vperm.
6037 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6038 SelectionDAG &DAG) const {
6040 SDValue V1 = Op.getOperand(0);
6041 SDValue V2 = Op.getOperand(1);
6042 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6043 EVT VT = Op.getValueType();
6044 bool isLittleEndian = Subtarget.isLittleEndian();
6046 // Cases that are handled by instructions that take permute immediates
6047 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6048 // selected by the instruction selector.
6049 if (V2.getOpcode() == ISD::UNDEF) {
6050 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6051 PPC::isSplatShuffleMask(SVOp, 2) ||
6052 PPC::isSplatShuffleMask(SVOp, 4) ||
6053 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6054 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6055 PPC::isVSLDOIShuffleMask(SVOp, true, DAG) != -1 ||
6056 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6057 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6058 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6059 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6060 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6061 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6066 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6067 // and produce a fixed permutation. If any of these match, do not lower to
6069 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6070 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6071 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6072 PPC::isVSLDOIShuffleMask(SVOp, false, DAG) != -1 ||
6073 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6074 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6075 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6076 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6077 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6078 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6081 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6082 // perfect shuffle table to emit an optimal matching sequence.
6083 ArrayRef<int> PermMask = SVOp->getMask();
6085 unsigned PFIndexes[4];
6086 bool isFourElementShuffle = true;
6087 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6088 unsigned EltNo = 8; // Start out undef.
6089 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6090 if (PermMask[i*4+j] < 0)
6091 continue; // Undef, ignore it.
6093 unsigned ByteSource = PermMask[i*4+j];
6094 if ((ByteSource & 3) != j) {
6095 isFourElementShuffle = false;
6100 EltNo = ByteSource/4;
6101 } else if (EltNo != ByteSource/4) {
6102 isFourElementShuffle = false;
6106 PFIndexes[i] = EltNo;
6109 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6110 // perfect shuffle vector to determine if it is cost effective to do this as
6111 // discrete instructions, or whether we should use a vperm.
6112 // For now, we skip this for little endian until such time as we have a
6113 // little-endian perfect shuffle table.
6114 if (isFourElementShuffle && !isLittleEndian) {
6115 // Compute the index in the perfect shuffle table.
6116 unsigned PFTableIndex =
6117 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6119 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6120 unsigned Cost = (PFEntry >> 30);
6122 // Determining when to avoid vperm is tricky. Many things affect the cost
6123 // of vperm, particularly how many times the perm mask needs to be computed.
6124 // For example, if the perm mask can be hoisted out of a loop or is already
6125 // used (perhaps because there are multiple permutes with the same shuffle
6126 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6127 // the loop requires an extra register.
6129 // As a compromise, we only emit discrete instructions if the shuffle can be
6130 // generated in 3 or fewer operations. When we have loop information
6131 // available, if this block is within a loop, we should avoid using vperm
6132 // for 3-operation perms and use a constant pool load instead.
6134 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6137 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6138 // vector that will get spilled to the constant pool.
6139 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6141 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6142 // that it is in input element units, not in bytes. Convert now.
6144 // For little endian, the order of the input vectors is reversed, and
6145 // the permutation mask is complemented with respect to 31. This is
6146 // necessary to produce proper semantics with the big-endian-biased vperm
6148 EVT EltVT = V1.getValueType().getVectorElementType();
6149 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6151 SmallVector<SDValue, 16> ResultMask;
6152 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6153 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6155 for (unsigned j = 0; j != BytesPerElement; ++j)
6157 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6160 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6164 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6167 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6170 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6174 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6175 /// altivec comparison. If it is, return true and fill in Opc/isDot with
6176 /// information about the intrinsic.
6177 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6179 unsigned IntrinsicID =
6180 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6183 switch (IntrinsicID) {
6184 default: return false;
6185 // Comparison predicates.
6186 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
6187 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6188 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
6189 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
6190 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6191 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6192 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6193 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6194 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6195 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6196 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6197 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6198 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6200 // Normal Comparisons.
6201 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
6202 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
6203 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
6204 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
6205 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
6206 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
6207 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
6208 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
6209 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
6210 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
6211 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
6212 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
6213 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
6218 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6219 /// lower, do it, otherwise return null.
6220 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6221 SelectionDAG &DAG) const {
6222 // If this is a lowered altivec predicate compare, CompareOpc is set to the
6223 // opcode number of the comparison.
6227 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6228 return SDValue(); // Don't custom lower most intrinsics.
6230 // If this is a non-dot comparison, make the VCMP node and we are done.
6232 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6233 Op.getOperand(1), Op.getOperand(2),
6234 DAG.getConstant(CompareOpc, MVT::i32));
6235 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6238 // Create the PPCISD altivec 'dot' comparison node.
6240 Op.getOperand(2), // LHS
6241 Op.getOperand(3), // RHS
6242 DAG.getConstant(CompareOpc, MVT::i32)
6244 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6245 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6247 // Now that we have the comparison, emit a copy from the CR to a GPR.
6248 // This is flagged to the above dot comparison.
6249 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6250 DAG.getRegister(PPC::CR6, MVT::i32),
6251 CompNode.getValue(1));
6253 // Unpack the result based on how the target uses it.
6254 unsigned BitNo; // Bit # of CR6.
6255 bool InvertBit; // Invert result?
6256 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6257 default: // Can't happen, don't crash on invalid number though.
6258 case 0: // Return the value of the EQ bit of CR6.
6259 BitNo = 0; InvertBit = false;
6261 case 1: // Return the inverted value of the EQ bit of CR6.
6262 BitNo = 0; InvertBit = true;
6264 case 2: // Return the value of the LT bit of CR6.
6265 BitNo = 2; InvertBit = false;
6267 case 3: // Return the inverted value of the LT bit of CR6.
6268 BitNo = 2; InvertBit = true;
6272 // Shift the bit into the low position.
6273 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6274 DAG.getConstant(8-(3-BitNo), MVT::i32));
6276 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6277 DAG.getConstant(1, MVT::i32));
6279 // If we are supposed to, toggle the bit.
6281 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6282 DAG.getConstant(1, MVT::i32));
6286 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6287 SelectionDAG &DAG) const {
6289 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6290 // instructions), but for smaller types, we need to first extend up to v2i32
6291 // before doing going farther.
6292 if (Op.getValueType() == MVT::v2i64) {
6293 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6294 if (ExtVT != MVT::v2i32) {
6295 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6296 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6297 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6298 ExtVT.getVectorElementType(), 4)));
6299 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6300 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6301 DAG.getValueType(MVT::v2i32));
6310 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6311 SelectionDAG &DAG) const {
6313 // Create a stack slot that is 16-byte aligned.
6314 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6315 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6316 EVT PtrVT = getPointerTy();
6317 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6319 // Store the input value into Value#0 of the stack slot.
6320 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6321 Op.getOperand(0), FIdx, MachinePointerInfo(),
6324 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6325 false, false, false, 0);
6328 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6330 if (Op.getValueType() == MVT::v4i32) {
6331 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6333 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6334 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6336 SDValue RHSSwap = // = vrlw RHS, 16
6337 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6339 // Shrinkify inputs to v8i16.
6340 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6341 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6342 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6344 // Low parts multiplied together, generating 32-bit results (we ignore the
6346 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6347 LHS, RHS, DAG, dl, MVT::v4i32);
6349 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6350 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6351 // Shift the high parts up 16 bits.
6352 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6354 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6355 } else if (Op.getValueType() == MVT::v8i16) {
6356 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6358 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6360 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6361 LHS, RHS, Zero, DAG, dl);
6362 } else if (Op.getValueType() == MVT::v16i8) {
6363 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6364 bool isLittleEndian = Subtarget.isLittleEndian();
6366 // Multiply the even 8-bit parts, producing 16-bit sums.
6367 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6368 LHS, RHS, DAG, dl, MVT::v8i16);
6369 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6371 // Multiply the odd 8-bit parts, producing 16-bit sums.
6372 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6373 LHS, RHS, DAG, dl, MVT::v8i16);
6374 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6376 // Merge the results together. Because vmuleub and vmuloub are
6377 // instructions with a big-endian bias, we must reverse the
6378 // element numbering and reverse the meaning of "odd" and "even"
6379 // when generating little endian code.
6381 for (unsigned i = 0; i != 8; ++i) {
6382 if (isLittleEndian) {
6384 Ops[i*2+1] = 2*i+16;
6387 Ops[i*2+1] = 2*i+1+16;
6391 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6393 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6395 llvm_unreachable("Unknown mul to lower!");
6399 /// LowerOperation - Provide custom lowering hooks for some operations.
6401 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6402 switch (Op.getOpcode()) {
6403 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6404 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6405 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6406 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6407 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6408 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6409 case ISD::SETCC: return LowerSETCC(Op, DAG);
6410 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6411 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6413 return LowerVASTART(Op, DAG, Subtarget);
6416 return LowerVAARG(Op, DAG, Subtarget);
6419 return LowerVACOPY(Op, DAG, Subtarget);
6421 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
6422 case ISD::DYNAMIC_STACKALLOC:
6423 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6425 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6426 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6428 case ISD::LOAD: return LowerLOAD(Op, DAG);
6429 case ISD::STORE: return LowerSTORE(Op, DAG);
6430 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6431 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6432 case ISD::FP_TO_UINT:
6433 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6435 case ISD::UINT_TO_FP:
6436 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6437 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6439 // Lower 64-bit shifts.
6440 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6441 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6442 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6444 // Vector-related lowering.
6445 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6446 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6447 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6448 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6449 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6450 case ISD::MUL: return LowerMUL(Op, DAG);
6452 // For counter-based loop handling.
6453 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6455 // Frame & Return address.
6456 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6457 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6461 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6462 SmallVectorImpl<SDValue>&Results,
6463 SelectionDAG &DAG) const {
6464 const TargetMachine &TM = getTargetMachine();
6466 switch (N->getOpcode()) {
6468 llvm_unreachable("Do not know how to custom type legalize this operation!");
6469 case ISD::INTRINSIC_W_CHAIN: {
6470 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6471 Intrinsic::ppc_is_decremented_ctr_nonzero)
6474 assert(N->getValueType(0) == MVT::i1 &&
6475 "Unexpected result type for CTR decrement intrinsic");
6476 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6477 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6478 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6481 Results.push_back(NewInt);
6482 Results.push_back(NewInt.getValue(1));
6486 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6487 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6490 EVT VT = N->getValueType(0);
6492 if (VT == MVT::i64) {
6493 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6495 Results.push_back(NewNode);
6496 Results.push_back(NewNode.getValue(1));
6500 case ISD::FP_ROUND_INREG: {
6501 assert(N->getValueType(0) == MVT::ppcf128);
6502 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6503 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6504 MVT::f64, N->getOperand(0),
6505 DAG.getIntPtrConstant(0));
6506 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6507 MVT::f64, N->getOperand(0),
6508 DAG.getIntPtrConstant(1));
6510 // Add the two halves of the long double in round-to-zero mode.
6511 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6513 // We know the low half is about to be thrown away, so just use something
6515 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6519 case ISD::FP_TO_SINT:
6520 // LowerFP_TO_INT() can only handle f32 and f64.
6521 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6523 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6529 //===----------------------------------------------------------------------===//
6530 // Other Lowering Code
6531 //===----------------------------------------------------------------------===//
6534 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6535 bool is64bit, unsigned BinOpcode) const {
6536 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6537 const TargetInstrInfo *TII =
6538 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6540 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6541 MachineFunction *F = BB->getParent();
6542 MachineFunction::iterator It = BB;
6545 unsigned dest = MI->getOperand(0).getReg();
6546 unsigned ptrA = MI->getOperand(1).getReg();
6547 unsigned ptrB = MI->getOperand(2).getReg();
6548 unsigned incr = MI->getOperand(3).getReg();
6549 DebugLoc dl = MI->getDebugLoc();
6551 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6552 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6553 F->insert(It, loopMBB);
6554 F->insert(It, exitMBB);
6555 exitMBB->splice(exitMBB->begin(), BB,
6556 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6557 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6559 MachineRegisterInfo &RegInfo = F->getRegInfo();
6560 unsigned TmpReg = (!BinOpcode) ? incr :
6561 RegInfo.createVirtualRegister(
6562 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6563 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6567 // fallthrough --> loopMBB
6568 BB->addSuccessor(loopMBB);
6571 // l[wd]arx dest, ptr
6572 // add r0, dest, incr
6573 // st[wd]cx. r0, ptr
6575 // fallthrough --> exitMBB
6577 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6578 .addReg(ptrA).addReg(ptrB);
6580 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6581 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6582 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6583 BuildMI(BB, dl, TII->get(PPC::BCC))
6584 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6585 BB->addSuccessor(loopMBB);
6586 BB->addSuccessor(exitMBB);
6595 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6596 MachineBasicBlock *BB,
6597 bool is8bit, // operation
6598 unsigned BinOpcode) const {
6599 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6600 const TargetInstrInfo *TII =
6601 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6602 // In 64 bit mode we have to use 64 bits for addresses, even though the
6603 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6604 // registers without caring whether they're 32 or 64, but here we're
6605 // doing actual arithmetic on the addresses.
6606 bool is64bit = Subtarget.isPPC64();
6607 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6609 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6610 MachineFunction *F = BB->getParent();
6611 MachineFunction::iterator It = BB;
6614 unsigned dest = MI->getOperand(0).getReg();
6615 unsigned ptrA = MI->getOperand(1).getReg();
6616 unsigned ptrB = MI->getOperand(2).getReg();
6617 unsigned incr = MI->getOperand(3).getReg();
6618 DebugLoc dl = MI->getDebugLoc();
6620 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6621 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6622 F->insert(It, loopMBB);
6623 F->insert(It, exitMBB);
6624 exitMBB->splice(exitMBB->begin(), BB,
6625 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6626 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6628 MachineRegisterInfo &RegInfo = F->getRegInfo();
6629 const TargetRegisterClass *RC =
6630 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6631 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6632 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6633 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6634 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6635 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6636 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6637 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6638 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6639 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6640 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6641 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6642 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6644 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6648 // fallthrough --> loopMBB
6649 BB->addSuccessor(loopMBB);
6651 // The 4-byte load must be aligned, while a char or short may be
6652 // anywhere in the word. Hence all this nasty bookkeeping code.
6653 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6654 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6655 // xori shift, shift1, 24 [16]
6656 // rlwinm ptr, ptr1, 0, 0, 29
6657 // slw incr2, incr, shift
6658 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6659 // slw mask, mask2, shift
6661 // lwarx tmpDest, ptr
6662 // add tmp, tmpDest, incr2
6663 // andc tmp2, tmpDest, mask
6664 // and tmp3, tmp, mask
6665 // or tmp4, tmp3, tmp2
6668 // fallthrough --> exitMBB
6669 // srw dest, tmpDest, shift
6670 if (ptrA != ZeroReg) {
6671 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6672 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6673 .addReg(ptrA).addReg(ptrB);
6677 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6678 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6679 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6680 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6682 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6683 .addReg(Ptr1Reg).addImm(0).addImm(61);
6685 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6686 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6687 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6688 .addReg(incr).addReg(ShiftReg);
6690 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6692 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6693 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6695 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6696 .addReg(Mask2Reg).addReg(ShiftReg);
6699 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6700 .addReg(ZeroReg).addReg(PtrReg);
6702 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6703 .addReg(Incr2Reg).addReg(TmpDestReg);
6704 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6705 .addReg(TmpDestReg).addReg(MaskReg);
6706 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6707 .addReg(TmpReg).addReg(MaskReg);
6708 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6709 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6710 BuildMI(BB, dl, TII->get(PPC::STWCX))
6711 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6712 BuildMI(BB, dl, TII->get(PPC::BCC))
6713 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6714 BB->addSuccessor(loopMBB);
6715 BB->addSuccessor(exitMBB);
6720 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6725 llvm::MachineBasicBlock*
6726 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6727 MachineBasicBlock *MBB) const {
6728 DebugLoc DL = MI->getDebugLoc();
6729 const TargetInstrInfo *TII =
6730 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6732 MachineFunction *MF = MBB->getParent();
6733 MachineRegisterInfo &MRI = MF->getRegInfo();
6735 const BasicBlock *BB = MBB->getBasicBlock();
6736 MachineFunction::iterator I = MBB;
6740 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6741 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6743 unsigned DstReg = MI->getOperand(0).getReg();
6744 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6745 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6746 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6747 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6749 MVT PVT = getPointerTy();
6750 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6751 "Invalid Pointer Size!");
6752 // For v = setjmp(buf), we generate
6755 // SjLjSetup mainMBB
6761 // buf[LabelOffset] = LR
6765 // v = phi(main, restore)
6768 MachineBasicBlock *thisMBB = MBB;
6769 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6770 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6771 MF->insert(I, mainMBB);
6772 MF->insert(I, sinkMBB);
6774 MachineInstrBuilder MIB;
6776 // Transfer the remainder of BB and its successor edges to sinkMBB.
6777 sinkMBB->splice(sinkMBB->begin(), MBB,
6778 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6779 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6781 // Note that the structure of the jmp_buf used here is not compatible
6782 // with that used by libc, and is not designed to be. Specifically, it
6783 // stores only those 'reserved' registers that LLVM does not otherwise
6784 // understand how to spill. Also, by convention, by the time this
6785 // intrinsic is called, Clang has already stored the frame address in the
6786 // first slot of the buffer and stack address in the third. Following the
6787 // X86 target code, we'll store the jump address in the second slot. We also
6788 // need to save the TOC pointer (R2) to handle jumps between shared
6789 // libraries, and that will be stored in the fourth slot. The thread
6790 // identifier (R13) is not affected.
6793 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6794 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6795 const int64_t BPOffset = 4 * PVT.getStoreSize();
6797 // Prepare IP either in reg.
6798 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6799 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6800 unsigned BufReg = MI->getOperand(1).getReg();
6802 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6803 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6807 MIB.setMemRefs(MMOBegin, MMOEnd);
6810 // Naked functions never have a base pointer, and so we use r1. For all
6811 // other functions, this decision must be delayed until during PEI.
6813 if (MF->getFunction()->getAttributes().hasAttribute(
6814 AttributeSet::FunctionIndex, Attribute::Naked))
6815 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6817 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6819 MIB = BuildMI(*thisMBB, MI, DL,
6820 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6824 MIB.setMemRefs(MMOBegin, MMOEnd);
6827 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6828 const PPCRegisterInfo *TRI =
6829 getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
6830 MIB.addRegMask(TRI->getNoPreservedMask());
6832 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6834 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6836 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6838 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6839 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6843 MIB = BuildMI(mainMBB, DL,
6844 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6847 if (Subtarget.isPPC64()) {
6848 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6850 .addImm(LabelOffset)
6853 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6855 .addImm(LabelOffset)
6859 MIB.setMemRefs(MMOBegin, MMOEnd);
6861 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6862 mainMBB->addSuccessor(sinkMBB);
6865 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6866 TII->get(PPC::PHI), DstReg)
6867 .addReg(mainDstReg).addMBB(mainMBB)
6868 .addReg(restoreDstReg).addMBB(thisMBB);
6870 MI->eraseFromParent();
6875 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6876 MachineBasicBlock *MBB) const {
6877 DebugLoc DL = MI->getDebugLoc();
6878 const TargetInstrInfo *TII =
6879 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6881 MachineFunction *MF = MBB->getParent();
6882 MachineRegisterInfo &MRI = MF->getRegInfo();
6885 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6886 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6888 MVT PVT = getPointerTy();
6889 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6890 "Invalid Pointer Size!");
6892 const TargetRegisterClass *RC =
6893 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6894 unsigned Tmp = MRI.createVirtualRegister(RC);
6895 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6896 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6897 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6898 unsigned BP = (PVT == MVT::i64) ? PPC::X30 :
6899 (Subtarget.isSVR4ABI() &&
6900 MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6901 PPC::R29 : PPC::R30);
6903 MachineInstrBuilder MIB;
6905 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6906 const int64_t SPOffset = 2 * PVT.getStoreSize();
6907 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6908 const int64_t BPOffset = 4 * PVT.getStoreSize();
6910 unsigned BufReg = MI->getOperand(0).getReg();
6912 // Reload FP (the jumped-to function may not have had a
6913 // frame pointer, and if so, then its r31 will be restored
6915 if (PVT == MVT::i64) {
6916 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6920 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6924 MIB.setMemRefs(MMOBegin, MMOEnd);
6927 if (PVT == MVT::i64) {
6928 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6929 .addImm(LabelOffset)
6932 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6933 .addImm(LabelOffset)
6936 MIB.setMemRefs(MMOBegin, MMOEnd);
6939 if (PVT == MVT::i64) {
6940 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6944 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6948 MIB.setMemRefs(MMOBegin, MMOEnd);
6951 if (PVT == MVT::i64) {
6952 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6956 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6960 MIB.setMemRefs(MMOBegin, MMOEnd);
6963 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
6964 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6968 MIB.setMemRefs(MMOBegin, MMOEnd);
6972 BuildMI(*MBB, MI, DL,
6973 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6974 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6976 MI->eraseFromParent();
6981 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6982 MachineBasicBlock *BB) const {
6983 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6984 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6985 return emitEHSjLjSetJmp(MI, BB);
6986 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6987 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6988 return emitEHSjLjLongJmp(MI, BB);
6991 const TargetInstrInfo *TII =
6992 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6994 // To "insert" these instructions we actually have to insert their
6995 // control-flow patterns.
6996 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6997 MachineFunction::iterator It = BB;
7000 MachineFunction *F = BB->getParent();
7002 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7003 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7004 MI->getOpcode() == PPC::SELECT_I4 ||
7005 MI->getOpcode() == PPC::SELECT_I8)) {
7006 SmallVector<MachineOperand, 2> Cond;
7007 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7008 MI->getOpcode() == PPC::SELECT_CC_I8)
7009 Cond.push_back(MI->getOperand(4));
7011 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7012 Cond.push_back(MI->getOperand(1));
7014 DebugLoc dl = MI->getDebugLoc();
7015 const TargetInstrInfo *TII =
7016 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7017 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7018 Cond, MI->getOperand(2).getReg(),
7019 MI->getOperand(3).getReg());
7020 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7021 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7022 MI->getOpcode() == PPC::SELECT_CC_F4 ||
7023 MI->getOpcode() == PPC::SELECT_CC_F8 ||
7024 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7025 MI->getOpcode() == PPC::SELECT_I4 ||
7026 MI->getOpcode() == PPC::SELECT_I8 ||
7027 MI->getOpcode() == PPC::SELECT_F4 ||
7028 MI->getOpcode() == PPC::SELECT_F8 ||
7029 MI->getOpcode() == PPC::SELECT_VRRC) {
7030 // The incoming instruction knows the destination vreg to set, the
7031 // condition code register to branch on, the true/false values to
7032 // select between, and a branch opcode to use.
7037 // cmpTY ccX, r1, r2
7039 // fallthrough --> copy0MBB
7040 MachineBasicBlock *thisMBB = BB;
7041 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7042 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7043 DebugLoc dl = MI->getDebugLoc();
7044 F->insert(It, copy0MBB);
7045 F->insert(It, sinkMBB);
7047 // Transfer the remainder of BB and its successor edges to sinkMBB.
7048 sinkMBB->splice(sinkMBB->begin(), BB,
7049 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7050 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7052 // Next, add the true and fallthrough blocks as its successors.
7053 BB->addSuccessor(copy0MBB);
7054 BB->addSuccessor(sinkMBB);
7056 if (MI->getOpcode() == PPC::SELECT_I4 ||
7057 MI->getOpcode() == PPC::SELECT_I8 ||
7058 MI->getOpcode() == PPC::SELECT_F4 ||
7059 MI->getOpcode() == PPC::SELECT_F8 ||
7060 MI->getOpcode() == PPC::SELECT_VRRC) {
7061 BuildMI(BB, dl, TII->get(PPC::BC))
7062 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7064 unsigned SelectPred = MI->getOperand(4).getImm();
7065 BuildMI(BB, dl, TII->get(PPC::BCC))
7066 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7070 // %FalseValue = ...
7071 // # fallthrough to sinkMBB
7074 // Update machine-CFG edges
7075 BB->addSuccessor(sinkMBB);
7078 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7081 BuildMI(*BB, BB->begin(), dl,
7082 TII->get(PPC::PHI), MI->getOperand(0).getReg())
7083 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7084 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7086 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7087 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7088 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7089 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7090 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7091 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7092 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7093 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7095 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7096 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7097 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7098 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7099 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7100 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7101 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7102 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7104 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7105 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7106 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7107 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7108 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7109 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7110 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7111 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7113 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7114 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7115 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7116 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7117 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7118 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7119 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7120 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7122 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7123 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7124 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7125 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7126 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7127 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7128 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7129 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7131 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7132 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7133 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7134 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7135 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7136 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7137 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7138 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7140 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7141 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7142 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7143 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7144 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7145 BB = EmitAtomicBinary(MI, BB, false, 0);
7146 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7147 BB = EmitAtomicBinary(MI, BB, true, 0);
7149 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7150 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7151 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7153 unsigned dest = MI->getOperand(0).getReg();
7154 unsigned ptrA = MI->getOperand(1).getReg();
7155 unsigned ptrB = MI->getOperand(2).getReg();
7156 unsigned oldval = MI->getOperand(3).getReg();
7157 unsigned newval = MI->getOperand(4).getReg();
7158 DebugLoc dl = MI->getDebugLoc();
7160 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7161 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7162 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7163 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7164 F->insert(It, loop1MBB);
7165 F->insert(It, loop2MBB);
7166 F->insert(It, midMBB);
7167 F->insert(It, exitMBB);
7168 exitMBB->splice(exitMBB->begin(), BB,
7169 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7170 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7174 // fallthrough --> loopMBB
7175 BB->addSuccessor(loop1MBB);
7178 // l[wd]arx dest, ptr
7179 // cmp[wd] dest, oldval
7182 // st[wd]cx. newval, ptr
7186 // st[wd]cx. dest, ptr
7189 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7190 .addReg(ptrA).addReg(ptrB);
7191 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7192 .addReg(oldval).addReg(dest);
7193 BuildMI(BB, dl, TII->get(PPC::BCC))
7194 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7195 BB->addSuccessor(loop2MBB);
7196 BB->addSuccessor(midMBB);
7199 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7200 .addReg(newval).addReg(ptrA).addReg(ptrB);
7201 BuildMI(BB, dl, TII->get(PPC::BCC))
7202 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7203 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7204 BB->addSuccessor(loop1MBB);
7205 BB->addSuccessor(exitMBB);
7208 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7209 .addReg(dest).addReg(ptrA).addReg(ptrB);
7210 BB->addSuccessor(exitMBB);
7215 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7216 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7217 // We must use 64-bit registers for addresses when targeting 64-bit,
7218 // since we're actually doing arithmetic on them. Other registers
7220 bool is64bit = Subtarget.isPPC64();
7221 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7223 unsigned dest = MI->getOperand(0).getReg();
7224 unsigned ptrA = MI->getOperand(1).getReg();
7225 unsigned ptrB = MI->getOperand(2).getReg();
7226 unsigned oldval = MI->getOperand(3).getReg();
7227 unsigned newval = MI->getOperand(4).getReg();
7228 DebugLoc dl = MI->getDebugLoc();
7230 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7231 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7232 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7233 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7234 F->insert(It, loop1MBB);
7235 F->insert(It, loop2MBB);
7236 F->insert(It, midMBB);
7237 F->insert(It, exitMBB);
7238 exitMBB->splice(exitMBB->begin(), BB,
7239 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7240 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7242 MachineRegisterInfo &RegInfo = F->getRegInfo();
7243 const TargetRegisterClass *RC =
7244 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
7245 (const TargetRegisterClass *) &PPC::GPRCRegClass;
7246 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7247 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7248 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7249 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7250 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7251 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7252 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7253 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7254 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7255 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7256 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7257 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7258 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7260 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7261 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7264 // fallthrough --> loopMBB
7265 BB->addSuccessor(loop1MBB);
7267 // The 4-byte load must be aligned, while a char or short may be
7268 // anywhere in the word. Hence all this nasty bookkeeping code.
7269 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7270 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7271 // xori shift, shift1, 24 [16]
7272 // rlwinm ptr, ptr1, 0, 0, 29
7273 // slw newval2, newval, shift
7274 // slw oldval2, oldval,shift
7275 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7276 // slw mask, mask2, shift
7277 // and newval3, newval2, mask
7278 // and oldval3, oldval2, mask
7280 // lwarx tmpDest, ptr
7281 // and tmp, tmpDest, mask
7282 // cmpw tmp, oldval3
7285 // andc tmp2, tmpDest, mask
7286 // or tmp4, tmp2, newval3
7291 // stwcx. tmpDest, ptr
7293 // srw dest, tmpDest, shift
7294 if (ptrA != ZeroReg) {
7295 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7296 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7297 .addReg(ptrA).addReg(ptrB);
7301 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7302 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7303 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7304 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7306 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7307 .addReg(Ptr1Reg).addImm(0).addImm(61);
7309 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7310 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7311 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7312 .addReg(newval).addReg(ShiftReg);
7313 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7314 .addReg(oldval).addReg(ShiftReg);
7316 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7318 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7319 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7320 .addReg(Mask3Reg).addImm(65535);
7322 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7323 .addReg(Mask2Reg).addReg(ShiftReg);
7324 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7325 .addReg(NewVal2Reg).addReg(MaskReg);
7326 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7327 .addReg(OldVal2Reg).addReg(MaskReg);
7330 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7331 .addReg(ZeroReg).addReg(PtrReg);
7332 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7333 .addReg(TmpDestReg).addReg(MaskReg);
7334 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7335 .addReg(TmpReg).addReg(OldVal3Reg);
7336 BuildMI(BB, dl, TII->get(PPC::BCC))
7337 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7338 BB->addSuccessor(loop2MBB);
7339 BB->addSuccessor(midMBB);
7342 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7343 .addReg(TmpDestReg).addReg(MaskReg);
7344 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7345 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7346 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7347 .addReg(ZeroReg).addReg(PtrReg);
7348 BuildMI(BB, dl, TII->get(PPC::BCC))
7349 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7350 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7351 BB->addSuccessor(loop1MBB);
7352 BB->addSuccessor(exitMBB);
7355 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7356 .addReg(ZeroReg).addReg(PtrReg);
7357 BB->addSuccessor(exitMBB);
7362 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7364 } else if (MI->getOpcode() == PPC::FADDrtz) {
7365 // This pseudo performs an FADD with rounding mode temporarily forced
7366 // to round-to-zero. We emit this via custom inserter since the FPSCR
7367 // is not modeled at the SelectionDAG level.
7368 unsigned Dest = MI->getOperand(0).getReg();
7369 unsigned Src1 = MI->getOperand(1).getReg();
7370 unsigned Src2 = MI->getOperand(2).getReg();
7371 DebugLoc dl = MI->getDebugLoc();
7373 MachineRegisterInfo &RegInfo = F->getRegInfo();
7374 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7376 // Save FPSCR value.
7377 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7379 // Set rounding mode to round-to-zero.
7380 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7381 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7383 // Perform addition.
7384 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7386 // Restore FPSCR value.
7387 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7388 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7389 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7390 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7391 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7392 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7393 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7394 PPC::ANDIo8 : PPC::ANDIo;
7395 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7396 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7398 MachineRegisterInfo &RegInfo = F->getRegInfo();
7399 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7400 &PPC::GPRCRegClass :
7401 &PPC::G8RCRegClass);
7403 DebugLoc dl = MI->getDebugLoc();
7404 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7405 .addReg(MI->getOperand(1).getReg()).addImm(1);
7406 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7407 MI->getOperand(0).getReg())
7408 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7410 llvm_unreachable("Unexpected instr type to insert");
7413 MI->eraseFromParent(); // The pseudo instruction is gone now.
7417 //===----------------------------------------------------------------------===//
7418 // Target Optimization Hooks
7419 //===----------------------------------------------------------------------===//
7421 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7422 DAGCombinerInfo &DCI) const {
7423 if (DCI.isAfterLegalizeVectorOps())
7426 EVT VT = Op.getValueType();
7428 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7429 (VT == MVT::f64 && Subtarget.hasFRE()) ||
7430 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7431 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7433 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7434 // For the reciprocal, we need to find the zero of the function:
7435 // F(X) = A X - 1 [which has a zero at X = 1/A]
7437 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7438 // does not require additional intermediate precision]
7440 // Convergence is quadratic, so we essentially double the number of digits
7441 // correct after every iteration. The minimum architected relative
7442 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7443 // 23 digits and double has 52 digits.
7444 int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7445 if (VT.getScalarType() == MVT::f64)
7448 SelectionDAG &DAG = DCI.DAG;
7452 DAG.getConstantFP(1.0, VT.getScalarType());
7453 if (VT.isVector()) {
7454 assert(VT.getVectorNumElements() == 4 &&
7455 "Unknown vector type");
7456 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7457 FPOne, FPOne, FPOne, FPOne);
7460 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7461 DCI.AddToWorklist(Est.getNode());
7463 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7464 for (int i = 0; i < Iterations; ++i) {
7465 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7466 DCI.AddToWorklist(NewEst.getNode());
7468 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7469 DCI.AddToWorklist(NewEst.getNode());
7471 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7472 DCI.AddToWorklist(NewEst.getNode());
7474 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7475 DCI.AddToWorklist(Est.getNode());
7484 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7485 DAGCombinerInfo &DCI) const {
7486 if (DCI.isAfterLegalizeVectorOps())
7489 EVT VT = Op.getValueType();
7491 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7492 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7493 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7494 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7496 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7497 // For the reciprocal sqrt, we need to find the zero of the function:
7498 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7500 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7501 // As a result, we precompute A/2 prior to the iteration loop.
7503 // Convergence is quadratic, so we essentially double the number of digits
7504 // correct after every iteration. The minimum architected relative
7505 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7506 // 23 digits and double has 52 digits.
7507 int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7508 if (VT.getScalarType() == MVT::f64)
7511 SelectionDAG &DAG = DCI.DAG;
7514 SDValue FPThreeHalves =
7515 DAG.getConstantFP(1.5, VT.getScalarType());
7516 if (VT.isVector()) {
7517 assert(VT.getVectorNumElements() == 4 &&
7518 "Unknown vector type");
7519 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7520 FPThreeHalves, FPThreeHalves,
7521 FPThreeHalves, FPThreeHalves);
7524 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7525 DCI.AddToWorklist(Est.getNode());
7527 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7528 // this entire sequence requires only one FP constant.
7529 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7530 DCI.AddToWorklist(HalfArg.getNode());
7532 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7533 DCI.AddToWorklist(HalfArg.getNode());
7535 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7536 for (int i = 0; i < Iterations; ++i) {
7537 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7538 DCI.AddToWorklist(NewEst.getNode());
7540 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7541 DCI.AddToWorklist(NewEst.getNode());
7543 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7544 DCI.AddToWorklist(NewEst.getNode());
7546 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7547 DCI.AddToWorklist(Est.getNode());
7556 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7557 unsigned Bytes, int Dist,
7558 SelectionDAG &DAG) {
7559 if (VT.getSizeInBits() / 8 != Bytes)
7562 SDValue BaseLoc = Base->getBasePtr();
7563 if (Loc.getOpcode() == ISD::FrameIndex) {
7564 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7566 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7567 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7568 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7569 int FS = MFI->getObjectSize(FI);
7570 int BFS = MFI->getObjectSize(BFI);
7571 if (FS != BFS || FS != (int)Bytes) return false;
7572 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7576 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7577 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7581 const GlobalValue *GV1 = nullptr;
7582 const GlobalValue *GV2 = nullptr;
7583 int64_t Offset1 = 0;
7584 int64_t Offset2 = 0;
7585 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7586 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7587 if (isGA1 && isGA2 && GV1 == GV2)
7588 return Offset1 == (Offset2 + Dist*Bytes);
7592 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7593 // not enforce equality of the chain operands.
7594 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7595 unsigned Bytes, int Dist,
7596 SelectionDAG &DAG) {
7597 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7598 EVT VT = LS->getMemoryVT();
7599 SDValue Loc = LS->getBasePtr();
7600 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7603 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7605 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7606 default: return false;
7607 case Intrinsic::ppc_altivec_lvx:
7608 case Intrinsic::ppc_altivec_lvxl:
7611 case Intrinsic::ppc_altivec_lvebx:
7614 case Intrinsic::ppc_altivec_lvehx:
7617 case Intrinsic::ppc_altivec_lvewx:
7622 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7625 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7627 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7628 default: return false;
7629 case Intrinsic::ppc_altivec_stvx:
7630 case Intrinsic::ppc_altivec_stvxl:
7633 case Intrinsic::ppc_altivec_stvebx:
7636 case Intrinsic::ppc_altivec_stvehx:
7639 case Intrinsic::ppc_altivec_stvewx:
7644 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7650 // Return true is there is a nearyby consecutive load to the one provided
7651 // (regardless of alignment). We search up and down the chain, looking though
7652 // token factors and other loads (but nothing else). As a result, a true result
7653 // indicates that it is safe to create a new consecutive load adjacent to the
7655 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7656 SDValue Chain = LD->getChain();
7657 EVT VT = LD->getMemoryVT();
7659 SmallSet<SDNode *, 16> LoadRoots;
7660 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7661 SmallSet<SDNode *, 16> Visited;
7663 // First, search up the chain, branching to follow all token-factor operands.
7664 // If we find a consecutive load, then we're done, otherwise, record all
7665 // nodes just above the top-level loads and token factors.
7666 while (!Queue.empty()) {
7667 SDNode *ChainNext = Queue.pop_back_val();
7668 if (!Visited.insert(ChainNext))
7671 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7672 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7675 if (!Visited.count(ChainLD->getChain().getNode()))
7676 Queue.push_back(ChainLD->getChain().getNode());
7677 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7678 for (const SDUse &O : ChainNext->ops())
7679 if (!Visited.count(O.getNode()))
7680 Queue.push_back(O.getNode());
7682 LoadRoots.insert(ChainNext);
7685 // Second, search down the chain, starting from the top-level nodes recorded
7686 // in the first phase. These top-level nodes are the nodes just above all
7687 // loads and token factors. Starting with their uses, recursively look though
7688 // all loads (just the chain uses) and token factors to find a consecutive
7693 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7694 IE = LoadRoots.end(); I != IE; ++I) {
7695 Queue.push_back(*I);
7697 while (!Queue.empty()) {
7698 SDNode *LoadRoot = Queue.pop_back_val();
7699 if (!Visited.insert(LoadRoot))
7702 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7703 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7706 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7707 UE = LoadRoot->use_end(); UI != UE; ++UI)
7708 if (((isa<MemSDNode>(*UI) &&
7709 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7710 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7711 Queue.push_back(*UI);
7718 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7719 DAGCombinerInfo &DCI) const {
7720 SelectionDAG &DAG = DCI.DAG;
7723 assert(Subtarget.useCRBits() &&
7724 "Expecting to be tracking CR bits");
7725 // If we're tracking CR bits, we need to be careful that we don't have:
7726 // trunc(binary-ops(zext(x), zext(y)))
7728 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7729 // such that we're unnecessarily moving things into GPRs when it would be
7730 // better to keep them in CR bits.
7732 // Note that trunc here can be an actual i1 trunc, or can be the effective
7733 // truncation that comes from a setcc or select_cc.
7734 if (N->getOpcode() == ISD::TRUNCATE &&
7735 N->getValueType(0) != MVT::i1)
7738 if (N->getOperand(0).getValueType() != MVT::i32 &&
7739 N->getOperand(0).getValueType() != MVT::i64)
7742 if (N->getOpcode() == ISD::SETCC ||
7743 N->getOpcode() == ISD::SELECT_CC) {
7744 // If we're looking at a comparison, then we need to make sure that the
7745 // high bits (all except for the first) don't matter the result.
7747 cast<CondCodeSDNode>(N->getOperand(
7748 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7749 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7751 if (ISD::isSignedIntSetCC(CC)) {
7752 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7753 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7755 } else if (ISD::isUnsignedIntSetCC(CC)) {
7756 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7757 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7758 !DAG.MaskedValueIsZero(N->getOperand(1),
7759 APInt::getHighBitsSet(OpBits, OpBits-1)))
7762 // This is neither a signed nor an unsigned comparison, just make sure
7763 // that the high bits are equal.
7764 APInt Op1Zero, Op1One;
7765 APInt Op2Zero, Op2One;
7766 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7767 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7769 // We don't really care about what is known about the first bit (if
7770 // anything), so clear it in all masks prior to comparing them.
7771 Op1Zero.clearBit(0); Op1One.clearBit(0);
7772 Op2Zero.clearBit(0); Op2One.clearBit(0);
7774 if (Op1Zero != Op2Zero || Op1One != Op2One)
7779 // We now know that the higher-order bits are irrelevant, we just need to
7780 // make sure that all of the intermediate operations are bit operations, and
7781 // all inputs are extensions.
7782 if (N->getOperand(0).getOpcode() != ISD::AND &&
7783 N->getOperand(0).getOpcode() != ISD::OR &&
7784 N->getOperand(0).getOpcode() != ISD::XOR &&
7785 N->getOperand(0).getOpcode() != ISD::SELECT &&
7786 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7787 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7788 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7789 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7790 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7793 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7794 N->getOperand(1).getOpcode() != ISD::AND &&
7795 N->getOperand(1).getOpcode() != ISD::OR &&
7796 N->getOperand(1).getOpcode() != ISD::XOR &&
7797 N->getOperand(1).getOpcode() != ISD::SELECT &&
7798 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7799 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7800 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7801 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7802 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7805 SmallVector<SDValue, 4> Inputs;
7806 SmallVector<SDValue, 8> BinOps, PromOps;
7807 SmallPtrSet<SDNode *, 16> Visited;
7809 for (unsigned i = 0; i < 2; ++i) {
7810 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7811 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7812 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7813 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7814 isa<ConstantSDNode>(N->getOperand(i)))
7815 Inputs.push_back(N->getOperand(i));
7817 BinOps.push_back(N->getOperand(i));
7819 if (N->getOpcode() == ISD::TRUNCATE)
7823 // Visit all inputs, collect all binary operations (and, or, xor and
7824 // select) that are all fed by extensions.
7825 while (!BinOps.empty()) {
7826 SDValue BinOp = BinOps.back();
7829 if (!Visited.insert(BinOp.getNode()))
7832 PromOps.push_back(BinOp);
7834 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7835 // The condition of the select is not promoted.
7836 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7838 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7841 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7842 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7843 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7844 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7845 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7846 Inputs.push_back(BinOp.getOperand(i));
7847 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7848 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7849 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7850 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7851 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7852 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7853 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7854 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7855 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7856 BinOps.push_back(BinOp.getOperand(i));
7858 // We have an input that is not an extension or another binary
7859 // operation; we'll abort this transformation.
7865 // Make sure that this is a self-contained cluster of operations (which
7866 // is not quite the same thing as saying that everything has only one
7868 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7869 if (isa<ConstantSDNode>(Inputs[i]))
7872 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7873 UE = Inputs[i].getNode()->use_end();
7876 if (User != N && !Visited.count(User))
7879 // Make sure that we're not going to promote the non-output-value
7880 // operand(s) or SELECT or SELECT_CC.
7881 // FIXME: Although we could sometimes handle this, and it does occur in
7882 // practice that one of the condition inputs to the select is also one of
7883 // the outputs, we currently can't deal with this.
7884 if (User->getOpcode() == ISD::SELECT) {
7885 if (User->getOperand(0) == Inputs[i])
7887 } else if (User->getOpcode() == ISD::SELECT_CC) {
7888 if (User->getOperand(0) == Inputs[i] ||
7889 User->getOperand(1) == Inputs[i])
7895 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7896 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7897 UE = PromOps[i].getNode()->use_end();
7900 if (User != N && !Visited.count(User))
7903 // Make sure that we're not going to promote the non-output-value
7904 // operand(s) or SELECT or SELECT_CC.
7905 // FIXME: Although we could sometimes handle this, and it does occur in
7906 // practice that one of the condition inputs to the select is also one of
7907 // the outputs, we currently can't deal with this.
7908 if (User->getOpcode() == ISD::SELECT) {
7909 if (User->getOperand(0) == PromOps[i])
7911 } else if (User->getOpcode() == ISD::SELECT_CC) {
7912 if (User->getOperand(0) == PromOps[i] ||
7913 User->getOperand(1) == PromOps[i])
7919 // Replace all inputs with the extension operand.
7920 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7921 // Constants may have users outside the cluster of to-be-promoted nodes,
7922 // and so we need to replace those as we do the promotions.
7923 if (isa<ConstantSDNode>(Inputs[i]))
7926 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7929 // Replace all operations (these are all the same, but have a different
7930 // (i1) return type). DAG.getNode will validate that the types of
7931 // a binary operator match, so go through the list in reverse so that
7932 // we've likely promoted both operands first. Any intermediate truncations or
7933 // extensions disappear.
7934 while (!PromOps.empty()) {
7935 SDValue PromOp = PromOps.back();
7938 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7939 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7940 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7941 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7942 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7943 PromOp.getOperand(0).getValueType() != MVT::i1) {
7944 // The operand is not yet ready (see comment below).
7945 PromOps.insert(PromOps.begin(), PromOp);
7949 SDValue RepValue = PromOp.getOperand(0);
7950 if (isa<ConstantSDNode>(RepValue))
7951 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7953 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7958 switch (PromOp.getOpcode()) {
7959 default: C = 0; break;
7960 case ISD::SELECT: C = 1; break;
7961 case ISD::SELECT_CC: C = 2; break;
7964 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7965 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7966 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7967 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7968 // The to-be-promoted operands of this node have not yet been
7969 // promoted (this should be rare because we're going through the
7970 // list backward, but if one of the operands has several users in
7971 // this cluster of to-be-promoted nodes, it is possible).
7972 PromOps.insert(PromOps.begin(), PromOp);
7976 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7977 PromOp.getNode()->op_end());
7979 // If there are any constant inputs, make sure they're replaced now.
7980 for (unsigned i = 0; i < 2; ++i)
7981 if (isa<ConstantSDNode>(Ops[C+i]))
7982 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7984 DAG.ReplaceAllUsesOfValueWith(PromOp,
7985 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7988 // Now we're left with the initial truncation itself.
7989 if (N->getOpcode() == ISD::TRUNCATE)
7990 return N->getOperand(0);
7992 // Otherwise, this is a comparison. The operands to be compared have just
7993 // changed type (to i1), but everything else is the same.
7994 return SDValue(N, 0);
7997 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7998 DAGCombinerInfo &DCI) const {
7999 SelectionDAG &DAG = DCI.DAG;
8002 // If we're tracking CR bits, we need to be careful that we don't have:
8003 // zext(binary-ops(trunc(x), trunc(y)))
8005 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8006 // such that we're unnecessarily moving things into CR bits that can more
8007 // efficiently stay in GPRs. Note that if we're not certain that the high
8008 // bits are set as required by the final extension, we still may need to do
8009 // some masking to get the proper behavior.
8011 // This same functionality is important on PPC64 when dealing with
8012 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8013 // the return values of functions. Because it is so similar, it is handled
8016 if (N->getValueType(0) != MVT::i32 &&
8017 N->getValueType(0) != MVT::i64)
8020 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8021 Subtarget.useCRBits()) ||
8022 (N->getOperand(0).getValueType() == MVT::i32 &&
8023 Subtarget.isPPC64())))
8026 if (N->getOperand(0).getOpcode() != ISD::AND &&
8027 N->getOperand(0).getOpcode() != ISD::OR &&
8028 N->getOperand(0).getOpcode() != ISD::XOR &&
8029 N->getOperand(0).getOpcode() != ISD::SELECT &&
8030 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8033 SmallVector<SDValue, 4> Inputs;
8034 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8035 SmallPtrSet<SDNode *, 16> Visited;
8037 // Visit all inputs, collect all binary operations (and, or, xor and
8038 // select) that are all fed by truncations.
8039 while (!BinOps.empty()) {
8040 SDValue BinOp = BinOps.back();
8043 if (!Visited.insert(BinOp.getNode()))
8046 PromOps.push_back(BinOp);
8048 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8049 // The condition of the select is not promoted.
8050 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8052 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8055 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8056 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8057 Inputs.push_back(BinOp.getOperand(i));
8058 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8059 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8060 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8061 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8062 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8063 BinOps.push_back(BinOp.getOperand(i));
8065 // We have an input that is not a truncation or another binary
8066 // operation; we'll abort this transformation.
8072 // Make sure that this is a self-contained cluster of operations (which
8073 // is not quite the same thing as saying that everything has only one
8075 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8076 if (isa<ConstantSDNode>(Inputs[i]))
8079 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8080 UE = Inputs[i].getNode()->use_end();
8083 if (User != N && !Visited.count(User))
8086 // Make sure that we're not going to promote the non-output-value
8087 // operand(s) or SELECT or SELECT_CC.
8088 // FIXME: Although we could sometimes handle this, and it does occur in
8089 // practice that one of the condition inputs to the select is also one of
8090 // the outputs, we currently can't deal with this.
8091 if (User->getOpcode() == ISD::SELECT) {
8092 if (User->getOperand(0) == Inputs[i])
8094 } else if (User->getOpcode() == ISD::SELECT_CC) {
8095 if (User->getOperand(0) == Inputs[i] ||
8096 User->getOperand(1) == Inputs[i])
8102 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8103 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8104 UE = PromOps[i].getNode()->use_end();
8107 if (User != N && !Visited.count(User))
8110 // Make sure that we're not going to promote the non-output-value
8111 // operand(s) or SELECT or SELECT_CC.
8112 // FIXME: Although we could sometimes handle this, and it does occur in
8113 // practice that one of the condition inputs to the select is also one of
8114 // the outputs, we currently can't deal with this.
8115 if (User->getOpcode() == ISD::SELECT) {
8116 if (User->getOperand(0) == PromOps[i])
8118 } else if (User->getOpcode() == ISD::SELECT_CC) {
8119 if (User->getOperand(0) == PromOps[i] ||
8120 User->getOperand(1) == PromOps[i])
8126 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8127 bool ReallyNeedsExt = false;
8128 if (N->getOpcode() != ISD::ANY_EXTEND) {
8129 // If all of the inputs are not already sign/zero extended, then
8130 // we'll still need to do that at the end.
8131 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8132 if (isa<ConstantSDNode>(Inputs[i]))
8136 Inputs[i].getOperand(0).getValueSizeInBits();
8137 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8139 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8140 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8141 APInt::getHighBitsSet(OpBits,
8142 OpBits-PromBits))) ||
8143 (N->getOpcode() == ISD::SIGN_EXTEND &&
8144 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8145 (OpBits-(PromBits-1)))) {
8146 ReallyNeedsExt = true;
8152 // Replace all inputs, either with the truncation operand, or a
8153 // truncation or extension to the final output type.
8154 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8155 // Constant inputs need to be replaced with the to-be-promoted nodes that
8156 // use them because they might have users outside of the cluster of
8158 if (isa<ConstantSDNode>(Inputs[i]))
8161 SDValue InSrc = Inputs[i].getOperand(0);
8162 if (Inputs[i].getValueType() == N->getValueType(0))
8163 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8164 else if (N->getOpcode() == ISD::SIGN_EXTEND)
8165 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8166 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8167 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8168 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8169 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8171 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8172 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8175 // Replace all operations (these are all the same, but have a different
8176 // (promoted) return type). DAG.getNode will validate that the types of
8177 // a binary operator match, so go through the list in reverse so that
8178 // we've likely promoted both operands first.
8179 while (!PromOps.empty()) {
8180 SDValue PromOp = PromOps.back();
8184 switch (PromOp.getOpcode()) {
8185 default: C = 0; break;
8186 case ISD::SELECT: C = 1; break;
8187 case ISD::SELECT_CC: C = 2; break;
8190 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8191 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8192 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8193 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8194 // The to-be-promoted operands of this node have not yet been
8195 // promoted (this should be rare because we're going through the
8196 // list backward, but if one of the operands has several users in
8197 // this cluster of to-be-promoted nodes, it is possible).
8198 PromOps.insert(PromOps.begin(), PromOp);
8202 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8203 PromOp.getNode()->op_end());
8205 // If this node has constant inputs, then they'll need to be promoted here.
8206 for (unsigned i = 0; i < 2; ++i) {
8207 if (!isa<ConstantSDNode>(Ops[C+i]))
8209 if (Ops[C+i].getValueType() == N->getValueType(0))
8212 if (N->getOpcode() == ISD::SIGN_EXTEND)
8213 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8214 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8215 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8217 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8220 DAG.ReplaceAllUsesOfValueWith(PromOp,
8221 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8224 // Now we're left with the initial extension itself.
8225 if (!ReallyNeedsExt)
8226 return N->getOperand(0);
8228 // To zero extend, just mask off everything except for the first bit (in the
8230 if (N->getOpcode() == ISD::ZERO_EXTEND)
8231 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8232 DAG.getConstant(APInt::getLowBitsSet(
8233 N->getValueSizeInBits(0), PromBits),
8234 N->getValueType(0)));
8236 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8237 "Invalid extension type");
8238 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8240 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8241 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
8242 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8243 N->getOperand(0), ShiftCst), ShiftCst);
8246 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8247 DAGCombinerInfo &DCI) const {
8248 const TargetMachine &TM = getTargetMachine();
8249 SelectionDAG &DAG = DCI.DAG;
8251 switch (N->getOpcode()) {
8254 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8255 if (C->isNullValue()) // 0 << V -> 0.
8256 return N->getOperand(0);
8260 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8261 if (C->isNullValue()) // 0 >>u V -> 0.
8262 return N->getOperand(0);
8266 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8267 if (C->isNullValue() || // 0 >>s V -> 0.
8268 C->isAllOnesValue()) // -1 >>s V -> -1.
8269 return N->getOperand(0);
8272 case ISD::SIGN_EXTEND:
8273 case ISD::ZERO_EXTEND:
8274 case ISD::ANY_EXTEND:
8275 return DAGCombineExtBoolTrunc(N, DCI);
8278 case ISD::SELECT_CC:
8279 return DAGCombineTruncBoolExt(N, DCI);
8281 assert(TM.Options.UnsafeFPMath &&
8282 "Reciprocal estimates require UnsafeFPMath");
8284 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
8286 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
8288 DCI.AddToWorklist(RV.getNode());
8289 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8290 N->getOperand(0), RV);
8292 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
8293 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8295 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8298 DCI.AddToWorklist(RV.getNode());
8299 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
8300 N->getValueType(0), RV);
8301 DCI.AddToWorklist(RV.getNode());
8302 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8303 N->getOperand(0), RV);
8305 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
8306 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8308 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8311 DCI.AddToWorklist(RV.getNode());
8312 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
8313 N->getValueType(0), RV,
8314 N->getOperand(1).getOperand(1));
8315 DCI.AddToWorklist(RV.getNode());
8316 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8317 N->getOperand(0), RV);
8321 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
8323 DCI.AddToWorklist(RV.getNode());
8324 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8325 N->getOperand(0), RV);
8331 assert(TM.Options.UnsafeFPMath &&
8332 "Reciprocal estimates require UnsafeFPMath");
8334 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
8336 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
8338 DCI.AddToWorklist(RV.getNode());
8339 RV = DAGCombineFastRecip(RV, DCI);
8341 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
8342 // this case and force the answer to 0.
8344 EVT VT = RV.getValueType();
8346 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
8347 if (VT.isVector()) {
8348 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
8349 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
8353 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
8354 N->getOperand(0), Zero, ISD::SETEQ);
8355 DCI.AddToWorklist(ZeroCmp.getNode());
8356 DCI.AddToWorklist(RV.getNode());
8358 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
8366 case ISD::SINT_TO_FP:
8367 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8368 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8369 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8370 // We allow the src/dst to be either f32/f64, but the intermediate
8371 // type must be i64.
8372 if (N->getOperand(0).getValueType() == MVT::i64 &&
8373 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8374 SDValue Val = N->getOperand(0).getOperand(0);
8375 if (Val.getValueType() == MVT::f32) {
8376 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8377 DCI.AddToWorklist(Val.getNode());
8380 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8381 DCI.AddToWorklist(Val.getNode());
8382 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8383 DCI.AddToWorklist(Val.getNode());
8384 if (N->getValueType(0) == MVT::f32) {
8385 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8386 DAG.getIntPtrConstant(0));
8387 DCI.AddToWorklist(Val.getNode());
8390 } else if (N->getOperand(0).getValueType() == MVT::i32) {
8391 // If the intermediate type is i32, we can avoid the load/store here
8398 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8399 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8400 !cast<StoreSDNode>(N)->isTruncatingStore() &&
8401 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8402 N->getOperand(1).getValueType() == MVT::i32 &&
8403 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8404 SDValue Val = N->getOperand(1).getOperand(0);
8405 if (Val.getValueType() == MVT::f32) {
8406 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8407 DCI.AddToWorklist(Val.getNode());
8409 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8410 DCI.AddToWorklist(Val.getNode());
8413 N->getOperand(0), Val, N->getOperand(2),
8414 DAG.getValueType(N->getOperand(1).getValueType())
8417 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8418 DAG.getVTList(MVT::Other), Ops,
8419 cast<StoreSDNode>(N)->getMemoryVT(),
8420 cast<StoreSDNode>(N)->getMemOperand());
8421 DCI.AddToWorklist(Val.getNode());
8425 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8426 if (cast<StoreSDNode>(N)->isUnindexed() &&
8427 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8428 N->getOperand(1).getNode()->hasOneUse() &&
8429 (N->getOperand(1).getValueType() == MVT::i32 ||
8430 N->getOperand(1).getValueType() == MVT::i16 ||
8431 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8432 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8433 N->getOperand(1).getValueType() == MVT::i64))) {
8434 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8435 // Do an any-extend to 32-bits if this is a half-word input.
8436 if (BSwapOp.getValueType() == MVT::i16)
8437 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8440 N->getOperand(0), BSwapOp, N->getOperand(2),
8441 DAG.getValueType(N->getOperand(1).getValueType())
8444 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8445 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8446 cast<StoreSDNode>(N)->getMemOperand());
8450 LoadSDNode *LD = cast<LoadSDNode>(N);
8451 EVT VT = LD->getValueType(0);
8452 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8453 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8454 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8455 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8456 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8457 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8458 LD->getAlignment() < ABIAlignment) {
8459 // This is a type-legal unaligned Altivec load.
8460 SDValue Chain = LD->getChain();
8461 SDValue Ptr = LD->getBasePtr();
8462 bool isLittleEndian = Subtarget.isLittleEndian();
8464 // This implements the loading of unaligned vectors as described in
8465 // the venerable Apple Velocity Engine overview. Specifically:
8466 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8467 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8469 // The general idea is to expand a sequence of one or more unaligned
8470 // loads into an alignment-based permutation-control instruction (lvsl
8471 // or lvsr), a series of regular vector loads (which always truncate
8472 // their input address to an aligned address), and a series of
8473 // permutations. The results of these permutations are the requested
8474 // loaded values. The trick is that the last "extra" load is not taken
8475 // from the address you might suspect (sizeof(vector) bytes after the
8476 // last requested load), but rather sizeof(vector) - 1 bytes after the
8477 // last requested vector. The point of this is to avoid a page fault if
8478 // the base address happened to be aligned. This works because if the
8479 // base address is aligned, then adding less than a full vector length
8480 // will cause the last vector in the sequence to be (re)loaded.
8481 // Otherwise, the next vector will be fetched as you might suspect was
8484 // We might be able to reuse the permutation generation from
8485 // a different base address offset from this one by an aligned amount.
8486 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8487 // optimization later.
8488 Intrinsic::ID Intr = (isLittleEndian ?
8489 Intrinsic::ppc_altivec_lvsr :
8490 Intrinsic::ppc_altivec_lvsl);
8491 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8493 // Create the new MMO for the new base load. It is like the original MMO,
8494 // but represents an area in memory almost twice the vector size centered
8495 // on the original address. If the address is unaligned, we might start
8496 // reading up to (sizeof(vector)-1) bytes below the address of the
8497 // original unaligned load.
8498 MachineFunction &MF = DAG.getMachineFunction();
8499 MachineMemOperand *BaseMMO =
8500 MF.getMachineMemOperand(LD->getMemOperand(),
8501 -LD->getMemoryVT().getStoreSize()+1,
8502 2*LD->getMemoryVT().getStoreSize()-1);
8504 // Create the new base load.
8505 SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8507 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8509 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8510 DAG.getVTList(MVT::v4i32, MVT::Other),
8511 BaseLoadOps, MVT::v4i32, BaseMMO);
8513 // Note that the value of IncOffset (which is provided to the next
8514 // load's pointer info offset value, and thus used to calculate the
8515 // alignment), and the value of IncValue (which is actually used to
8516 // increment the pointer value) are different! This is because we
8517 // require the next load to appear to be aligned, even though it
8518 // is actually offset from the base pointer by a lesser amount.
8519 int IncOffset = VT.getSizeInBits() / 8;
8520 int IncValue = IncOffset;
8522 // Walk (both up and down) the chain looking for another load at the real
8523 // (aligned) offset (the alignment of the other load does not matter in
8524 // this case). If found, then do not use the offset reduction trick, as
8525 // that will prevent the loads from being later combined (as they would
8526 // otherwise be duplicates).
8527 if (!findConsecutiveLoad(LD, DAG))
8530 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8531 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8533 MachineMemOperand *ExtraMMO =
8534 MF.getMachineMemOperand(LD->getMemOperand(),
8535 1, 2*LD->getMemoryVT().getStoreSize()-1);
8536 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8538 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8539 DAG.getVTList(MVT::v4i32, MVT::Other),
8540 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8542 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8543 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8545 // Because vperm has a big-endian bias, we must reverse the order
8546 // of the input vectors and complement the permute control vector
8547 // when generating little endian code. We have already handled the
8548 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8549 // and ExtraLoad here.
8552 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8553 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8555 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8556 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8558 if (VT != MVT::v4i32)
8559 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8561 // The output of the permutation is our loaded result, the TokenFactor is
8563 DCI.CombineTo(N, Perm, TF);
8564 return SDValue(N, 0);
8568 case ISD::INTRINSIC_WO_CHAIN: {
8569 bool isLittleEndian = Subtarget.isLittleEndian();
8570 Intrinsic::ID Intr = (isLittleEndian ?
8571 Intrinsic::ppc_altivec_lvsr :
8572 Intrinsic::ppc_altivec_lvsl);
8573 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8574 N->getOperand(1)->getOpcode() == ISD::ADD) {
8575 SDValue Add = N->getOperand(1);
8577 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8578 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8579 Add.getValueType().getScalarType().getSizeInBits()))) {
8580 SDNode *BasePtr = Add->getOperand(0).getNode();
8581 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8582 UE = BasePtr->use_end(); UI != UE; ++UI) {
8583 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8584 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8586 // We've found another LVSL/LVSR, and this address is an aligned
8587 // multiple of that one. The results will be the same, so use the
8588 // one we've just found instead.
8590 return SDValue(*UI, 0);
8599 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8600 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8601 N->getOperand(0).hasOneUse() &&
8602 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8603 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8604 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8605 N->getValueType(0) == MVT::i64))) {
8606 SDValue Load = N->getOperand(0);
8607 LoadSDNode *LD = cast<LoadSDNode>(Load);
8608 // Create the byte-swapping load.
8610 LD->getChain(), // Chain
8611 LD->getBasePtr(), // Ptr
8612 DAG.getValueType(N->getValueType(0)) // VT
8615 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8616 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8617 MVT::i64 : MVT::i32, MVT::Other),
8618 Ops, LD->getMemoryVT(), LD->getMemOperand());
8620 // If this is an i16 load, insert the truncate.
8621 SDValue ResVal = BSLoad;
8622 if (N->getValueType(0) == MVT::i16)
8623 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8625 // First, combine the bswap away. This makes the value produced by the
8627 DCI.CombineTo(N, ResVal);
8629 // Next, combine the load away, we give it a bogus result value but a real
8630 // chain result. The result value is dead because the bswap is dead.
8631 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8633 // Return N so it doesn't get rechecked!
8634 return SDValue(N, 0);
8638 case PPCISD::VCMP: {
8639 // If a VCMPo node already exists with exactly the same operands as this
8640 // node, use its result instead of this node (VCMPo computes both a CR6 and
8641 // a normal output).
8643 if (!N->getOperand(0).hasOneUse() &&
8644 !N->getOperand(1).hasOneUse() &&
8645 !N->getOperand(2).hasOneUse()) {
8647 // Scan all of the users of the LHS, looking for VCMPo's that match.
8648 SDNode *VCMPoNode = nullptr;
8650 SDNode *LHSN = N->getOperand(0).getNode();
8651 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8653 if (UI->getOpcode() == PPCISD::VCMPo &&
8654 UI->getOperand(1) == N->getOperand(1) &&
8655 UI->getOperand(2) == N->getOperand(2) &&
8656 UI->getOperand(0) == N->getOperand(0)) {
8661 // If there is no VCMPo node, or if the flag value has a single use, don't
8663 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8666 // Look at the (necessarily single) use of the flag value. If it has a
8667 // chain, this transformation is more complex. Note that multiple things
8668 // could use the value result, which we should ignore.
8669 SDNode *FlagUser = nullptr;
8670 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8671 FlagUser == nullptr; ++UI) {
8672 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8674 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8675 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8682 // If the user is a MFOCRF instruction, we know this is safe.
8683 // Otherwise we give up for right now.
8684 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8685 return SDValue(VCMPoNode, 0);
8690 SDValue Cond = N->getOperand(1);
8691 SDValue Target = N->getOperand(2);
8693 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8694 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8695 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8697 // We now need to make the intrinsic dead (it cannot be instruction
8699 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8700 assert(Cond.getNode()->hasOneUse() &&
8701 "Counter decrement has more than one use");
8703 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8704 N->getOperand(0), Target);
8709 // If this is a branch on an altivec predicate comparison, lower this so
8710 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8711 // lowering is done pre-legalize, because the legalizer lowers the predicate
8712 // compare down to code that is difficult to reassemble.
8713 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8714 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8716 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8717 // value. If so, pass-through the AND to get to the intrinsic.
8718 if (LHS.getOpcode() == ISD::AND &&
8719 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8720 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8721 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8722 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8723 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8725 LHS = LHS.getOperand(0);
8727 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8728 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8729 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8730 isa<ConstantSDNode>(RHS)) {
8731 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8732 "Counter decrement comparison is not EQ or NE");
8734 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8735 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8736 (CC == ISD::SETNE && !Val);
8738 // We now need to make the intrinsic dead (it cannot be instruction
8740 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8741 assert(LHS.getNode()->hasOneUse() &&
8742 "Counter decrement has more than one use");
8744 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8745 N->getOperand(0), N->getOperand(4));
8751 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8752 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8753 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8754 assert(isDot && "Can't compare against a vector result!");
8756 // If this is a comparison against something other than 0/1, then we know
8757 // that the condition is never/always true.
8758 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8759 if (Val != 0 && Val != 1) {
8760 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8761 return N->getOperand(0);
8762 // Always !=, turn it into an unconditional branch.
8763 return DAG.getNode(ISD::BR, dl, MVT::Other,
8764 N->getOperand(0), N->getOperand(4));
8767 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8769 // Create the PPCISD altivec 'dot' comparison node.
8771 LHS.getOperand(2), // LHS of compare
8772 LHS.getOperand(3), // RHS of compare
8773 DAG.getConstant(CompareOpc, MVT::i32)
8775 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8776 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8778 // Unpack the result based on how the target uses it.
8779 PPC::Predicate CompOpc;
8780 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8781 default: // Can't happen, don't crash on invalid number though.
8782 case 0: // Branch on the value of the EQ bit of CR6.
8783 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8785 case 1: // Branch on the inverted value of the EQ bit of CR6.
8786 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8788 case 2: // Branch on the value of the LT bit of CR6.
8789 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8791 case 3: // Branch on the inverted value of the LT bit of CR6.
8792 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8796 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8797 DAG.getConstant(CompOpc, MVT::i32),
8798 DAG.getRegister(PPC::CR6, MVT::i32),
8799 N->getOperand(4), CompNode.getValue(1));
8808 //===----------------------------------------------------------------------===//
8809 // Inline Assembly Support
8810 //===----------------------------------------------------------------------===//
8812 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8815 const SelectionDAG &DAG,
8816 unsigned Depth) const {
8817 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8818 switch (Op.getOpcode()) {
8820 case PPCISD::LBRX: {
8821 // lhbrx is known to have the top bits cleared out.
8822 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8823 KnownZero = 0xFFFF0000;
8826 case ISD::INTRINSIC_WO_CHAIN: {
8827 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8829 case Intrinsic::ppc_altivec_vcmpbfp_p:
8830 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8831 case Intrinsic::ppc_altivec_vcmpequb_p:
8832 case Intrinsic::ppc_altivec_vcmpequh_p:
8833 case Intrinsic::ppc_altivec_vcmpequw_p:
8834 case Intrinsic::ppc_altivec_vcmpgefp_p:
8835 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8836 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8837 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8838 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8839 case Intrinsic::ppc_altivec_vcmpgtub_p:
8840 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8841 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8842 KnownZero = ~1U; // All bits but the low one are known to be zero.
8850 /// getConstraintType - Given a constraint, return the type of
8851 /// constraint it is for this target.
8852 PPCTargetLowering::ConstraintType
8853 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8854 if (Constraint.size() == 1) {
8855 switch (Constraint[0]) {
8862 return C_RegisterClass;
8864 // FIXME: While Z does indicate a memory constraint, it specifically
8865 // indicates an r+r address (used in conjunction with the 'y' modifier
8866 // in the replacement string). Currently, we're forcing the base
8867 // register to be r0 in the asm printer (which is interpreted as zero)
8868 // and forming the complete address in the second register. This is
8872 } else if (Constraint == "wc") { // individual CR bits.
8873 return C_RegisterClass;
8874 } else if (Constraint == "wa" || Constraint == "wd" ||
8875 Constraint == "wf" || Constraint == "ws") {
8876 return C_RegisterClass; // VSX registers.
8878 return TargetLowering::getConstraintType(Constraint);
8881 /// Examine constraint type and operand type and determine a weight value.
8882 /// This object must already have been set up with the operand type
8883 /// and the current alternative constraint selected.
8884 TargetLowering::ConstraintWeight
8885 PPCTargetLowering::getSingleConstraintMatchWeight(
8886 AsmOperandInfo &info, const char *constraint) const {
8887 ConstraintWeight weight = CW_Invalid;
8888 Value *CallOperandVal = info.CallOperandVal;
8889 // If we don't have a value, we can't do a match,
8890 // but allow it at the lowest weight.
8891 if (!CallOperandVal)
8893 Type *type = CallOperandVal->getType();
8895 // Look at the constraint type.
8896 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8897 return CW_Register; // an individual CR bit.
8898 else if ((StringRef(constraint) == "wa" ||
8899 StringRef(constraint) == "wd" ||
8900 StringRef(constraint) == "wf") &&
8903 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8906 switch (*constraint) {
8908 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8911 if (type->isIntegerTy())
8912 weight = CW_Register;
8915 if (type->isFloatTy())
8916 weight = CW_Register;
8919 if (type->isDoubleTy())
8920 weight = CW_Register;
8923 if (type->isVectorTy())
8924 weight = CW_Register;
8927 weight = CW_Register;
8936 std::pair<unsigned, const TargetRegisterClass*>
8937 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8939 if (Constraint.size() == 1) {
8940 // GCC RS6000 Constraint Letters
8941 switch (Constraint[0]) {
8943 if (VT == MVT::i64 && Subtarget.isPPC64())
8944 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8945 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8947 if (VT == MVT::i64 && Subtarget.isPPC64())
8948 return std::make_pair(0U, &PPC::G8RCRegClass);
8949 return std::make_pair(0U, &PPC::GPRCRegClass);
8951 if (VT == MVT::f32 || VT == MVT::i32)
8952 return std::make_pair(0U, &PPC::F4RCRegClass);
8953 if (VT == MVT::f64 || VT == MVT::i64)
8954 return std::make_pair(0U, &PPC::F8RCRegClass);
8957 return std::make_pair(0U, &PPC::VRRCRegClass);
8959 return std::make_pair(0U, &PPC::CRRCRegClass);
8961 } else if (Constraint == "wc") { // an individual CR bit.
8962 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8963 } else if (Constraint == "wa" || Constraint == "wd" ||
8964 Constraint == "wf") {
8965 return std::make_pair(0U, &PPC::VSRCRegClass);
8966 } else if (Constraint == "ws") {
8967 return std::make_pair(0U, &PPC::VSFRCRegClass);
8970 std::pair<unsigned, const TargetRegisterClass*> R =
8971 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8973 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8974 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8975 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8977 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8978 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8979 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
8980 PPC::GPRCRegClass.contains(R.first)) {
8981 const TargetRegisterInfo *TRI =
8982 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8983 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8984 PPC::sub_32, &PPC::G8RCRegClass),
8985 &PPC::G8RCRegClass);
8992 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8993 /// vector. If it is invalid, don't add anything to Ops.
8994 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8995 std::string &Constraint,
8996 std::vector<SDValue>&Ops,
8997 SelectionDAG &DAG) const {
9000 // Only support length 1 constraints.
9001 if (Constraint.length() > 1) return;
9003 char Letter = Constraint[0];
9014 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9015 if (!CST) return; // Must be an immediate to match.
9016 unsigned Value = CST->getZExtValue();
9018 default: llvm_unreachable("Unknown constraint letter!");
9019 case 'I': // "I" is a signed 16-bit constant.
9020 if ((short)Value == (int)Value)
9021 Result = DAG.getTargetConstant(Value, Op.getValueType());
9023 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
9024 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
9025 if ((short)Value == 0)
9026 Result = DAG.getTargetConstant(Value, Op.getValueType());
9028 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
9029 if ((Value >> 16) == 0)
9030 Result = DAG.getTargetConstant(Value, Op.getValueType());
9032 case 'M': // "M" is a constant that is greater than 31.
9034 Result = DAG.getTargetConstant(Value, Op.getValueType());
9036 case 'N': // "N" is a positive constant that is an exact power of two.
9037 if ((int)Value > 0 && isPowerOf2_32(Value))
9038 Result = DAG.getTargetConstant(Value, Op.getValueType());
9040 case 'O': // "O" is the constant zero.
9042 Result = DAG.getTargetConstant(Value, Op.getValueType());
9044 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
9045 if ((short)-Value == (int)-Value)
9046 Result = DAG.getTargetConstant(Value, Op.getValueType());
9053 if (Result.getNode()) {
9054 Ops.push_back(Result);
9058 // Handle standard constraint letters.
9059 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9062 // isLegalAddressingMode - Return true if the addressing mode represented
9063 // by AM is legal for this target, for a load/store of the specified type.
9064 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9066 // FIXME: PPC does not allow r+i addressing modes for vectors!
9068 // PPC allows a sign-extended 16-bit immediate field.
9069 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9072 // No global is ever allowed as a base.
9076 // PPC only support r+r,
9078 case 0: // "r+i" or just "i", depending on HasBaseReg.
9081 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
9083 // Otherwise we have r+r or r+i.
9086 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
9088 // Allow 2*r as r+r.
9091 // No other scales are supported.
9098 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9099 SelectionDAG &DAG) const {
9100 MachineFunction &MF = DAG.getMachineFunction();
9101 MachineFrameInfo *MFI = MF.getFrameInfo();
9102 MFI->setReturnAddressIsTaken(true);
9104 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9108 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9110 // Make sure the function does not optimize away the store of the RA to
9112 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9113 FuncInfo->setLRStoreRequired();
9114 bool isPPC64 = Subtarget.isPPC64();
9115 bool isDarwinABI = Subtarget.isDarwinABI();
9118 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9121 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9122 isPPC64? MVT::i64 : MVT::i32);
9123 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9124 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9126 MachinePointerInfo(), false, false, false, 0);
9129 // Just load the return address off the stack.
9130 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9131 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9132 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9135 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9136 SelectionDAG &DAG) const {
9138 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9140 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9141 bool isPPC64 = PtrVT == MVT::i64;
9143 MachineFunction &MF = DAG.getMachineFunction();
9144 MachineFrameInfo *MFI = MF.getFrameInfo();
9145 MFI->setFrameAddressIsTaken(true);
9147 // Naked functions never have a frame pointer, and so we use r1. For all
9148 // other functions, this decision must be delayed until during PEI.
9150 if (MF.getFunction()->getAttributes().hasAttribute(
9151 AttributeSet::FunctionIndex, Attribute::Naked))
9152 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9154 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9156 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9159 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9160 FrameAddr, MachinePointerInfo(), false, false,
9165 // FIXME? Maybe this could be a TableGen attribute on some registers and
9166 // this table could be generated automatically from RegInfo.
9167 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9169 bool isPPC64 = Subtarget.isPPC64();
9170 bool isDarwinABI = Subtarget.isDarwinABI();
9172 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9173 (!isPPC64 && VT != MVT::i32))
9174 report_fatal_error("Invalid register global variable type");
9176 bool is64Bit = isPPC64 && VT == MVT::i64;
9177 unsigned Reg = StringSwitch<unsigned>(RegName)
9178 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9179 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9180 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9181 (is64Bit ? PPC::X13 : PPC::R13))
9186 report_fatal_error("Invalid register name global variable");
9190 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9191 // The PowerPC target isn't yet aware of offsets.
9195 /// getOptimalMemOpType - Returns the target specific optimal type for load
9196 /// and store operations as a result of memset, memcpy, and memmove
9197 /// lowering. If DstAlign is zero that means it's safe to destination
9198 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9199 /// means there isn't a need to check it against alignment requirement,
9200 /// probably because the source does not need to be loaded. If 'IsMemset' is
9201 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9202 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9203 /// source is constant so it does not need to be loaded.
9204 /// It returns EVT::Other if the type should be determined using generic
9205 /// target-independent logic.
9206 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9207 unsigned DstAlign, unsigned SrcAlign,
9208 bool IsMemset, bool ZeroMemset,
9210 MachineFunction &MF) const {
9211 if (Subtarget.isPPC64()) {
9218 /// \brief Returns true if it is beneficial to convert a load of a constant
9219 /// to just the constant itself.
9220 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9222 assert(Ty->isIntegerTy());
9224 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9225 if (BitSize == 0 || BitSize > 64)
9230 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9231 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9233 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9234 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9235 return NumBits1 == 64 && NumBits2 == 32;
9238 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9239 if (!VT1.isInteger() || !VT2.isInteger())
9241 unsigned NumBits1 = VT1.getSizeInBits();
9242 unsigned NumBits2 = VT2.getSizeInBits();
9243 return NumBits1 == 64 && NumBits2 == 32;
9246 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9247 return isInt<16>(Imm) || isUInt<16>(Imm);
9250 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9251 return isInt<16>(Imm) || isUInt<16>(Imm);
9254 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9258 if (DisablePPCUnaligned)
9261 // PowerPC supports unaligned memory access for simple non-vector types.
9262 // Although accessing unaligned addresses is not as efficient as accessing
9263 // aligned addresses, it is generally more efficient than manual expansion,
9264 // and generally only traps for software emulation when crossing page
9270 if (VT.getSimpleVT().isVector()) {
9271 if (Subtarget.hasVSX()) {
9272 if (VT != MVT::v2f64 && VT != MVT::v2i64)
9279 if (VT == MVT::ppcf128)
9288 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9289 VT = VT.getScalarType();
9294 switch (VT.getSimpleVT().SimpleTy) {
9306 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9307 EVT VT , unsigned DefinedValues) const {
9308 if (VT == MVT::v2i64)
9311 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9314 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9315 if (DisableILPPref || Subtarget.enableMachineScheduler())
9316 return TargetLowering::getSchedulingPreference(N);
9321 // Create a fast isel object.
9323 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9324 const TargetLibraryInfo *LibInfo) const {
9325 return PPC::createFastISel(FuncInfo, LibInfo);