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::UMUL_LOHI, VT, Expand);
457 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
458 setOperationAction(ISD::UDIVREM, VT, Expand);
459 setOperationAction(ISD::SDIVREM, VT, Expand);
460 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
461 setOperationAction(ISD::FPOW, VT, Expand);
462 setOperationAction(ISD::BSWAP, VT, Expand);
463 setOperationAction(ISD::CTPOP, VT, Expand);
464 setOperationAction(ISD::CTLZ, VT, Expand);
465 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
466 setOperationAction(ISD::CTTZ, VT, Expand);
467 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
468 setOperationAction(ISD::VSELECT, VT, Expand);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
471 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
472 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
473 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
474 setTruncStoreAction(VT, InnerVT, Expand);
476 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
477 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
478 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
481 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
482 // with merges, splats, etc.
483 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
485 setOperationAction(ISD::AND , MVT::v4i32, Legal);
486 setOperationAction(ISD::OR , MVT::v4i32, Legal);
487 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
488 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
489 setOperationAction(ISD::SELECT, MVT::v4i32,
490 Subtarget.useCRBits() ? Legal : Expand);
491 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
492 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
493 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
494 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
495 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
496 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
497 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
498 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
499 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
501 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
502 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
503 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
504 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
506 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
507 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
509 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
510 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
511 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
514 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
518 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
519 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
521 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
522 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
523 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
524 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
526 // Altivec does not contain unordered floating-point compare instructions
527 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
528 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
529 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
530 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
531 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
532 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
534 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
535 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
537 if (Subtarget.hasVSX()) {
538 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
539 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
541 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
542 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
543 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
544 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
545 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
547 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
549 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
550 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
552 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
553 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
555 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
558 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
559 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
561 // Share the Altivec comparison restrictions.
562 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
563 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
564 setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
566 setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
567 setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
569 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
570 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
572 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
573 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
575 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
577 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
579 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
580 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
582 // VSX v2i64 only supports non-arithmetic operations.
583 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
584 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
586 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
587 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
588 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
590 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
592 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
593 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
594 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
595 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
597 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
599 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
600 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
601 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
602 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
604 // Vector operation legalization checks the result type of
605 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
606 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
607 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
608 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
609 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
611 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
615 if (Subtarget.has64BitSupport()) {
616 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
617 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
620 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
621 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
622 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
623 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
625 setBooleanContents(ZeroOrOneBooleanContent);
626 // Altivec instructions set fields to all zeros or all ones.
627 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
630 setStackPointerRegisterToSaveRestore(PPC::X1);
631 setExceptionPointerRegister(PPC::X3);
632 setExceptionSelectorRegister(PPC::X4);
634 setStackPointerRegisterToSaveRestore(PPC::R1);
635 setExceptionPointerRegister(PPC::R3);
636 setExceptionSelectorRegister(PPC::R4);
639 // We have target-specific dag combine patterns for the following nodes:
640 setTargetDAGCombine(ISD::SINT_TO_FP);
641 setTargetDAGCombine(ISD::LOAD);
642 setTargetDAGCombine(ISD::STORE);
643 setTargetDAGCombine(ISD::BR_CC);
644 if (Subtarget.useCRBits())
645 setTargetDAGCombine(ISD::BRCOND);
646 setTargetDAGCombine(ISD::BSWAP);
647 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
649 setTargetDAGCombine(ISD::SIGN_EXTEND);
650 setTargetDAGCombine(ISD::ZERO_EXTEND);
651 setTargetDAGCombine(ISD::ANY_EXTEND);
653 if (Subtarget.useCRBits()) {
654 setTargetDAGCombine(ISD::TRUNCATE);
655 setTargetDAGCombine(ISD::SETCC);
656 setTargetDAGCombine(ISD::SELECT_CC);
659 // Use reciprocal estimates.
660 if (TM.Options.UnsafeFPMath) {
661 setTargetDAGCombine(ISD::FDIV);
662 setTargetDAGCombine(ISD::FSQRT);
665 // Darwin long double math library functions have $LDBL128 appended.
666 if (Subtarget.isDarwin()) {
667 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
668 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
669 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
670 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
671 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
672 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
673 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
674 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
675 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
676 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
679 // With 32 condition bits, we don't need to sink (and duplicate) compares
680 // aggressively in CodeGenPrep.
681 if (Subtarget.useCRBits())
682 setHasMultipleConditionRegisters();
684 setMinFunctionAlignment(2);
685 if (Subtarget.isDarwin())
686 setPrefFunctionAlignment(4);
688 if (isPPC64 && Subtarget.isJITCodeModel())
689 // Temporary workaround for the inability of PPC64 JIT to handle jump
691 setSupportJumpTables(false);
693 setInsertFencesForAtomic(true);
695 if (Subtarget.enableMachineScheduler())
696 setSchedulingPreference(Sched::Source);
698 setSchedulingPreference(Sched::Hybrid);
700 computeRegisterProperties();
702 // The Freescale cores does better with aggressive inlining of memcpy and
703 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
704 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
705 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
706 MaxStoresPerMemset = 32;
707 MaxStoresPerMemsetOptSize = 16;
708 MaxStoresPerMemcpy = 32;
709 MaxStoresPerMemcpyOptSize = 8;
710 MaxStoresPerMemmove = 32;
711 MaxStoresPerMemmoveOptSize = 8;
713 setPrefFunctionAlignment(4);
717 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
718 /// the desired ByVal argument alignment.
719 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
720 unsigned MaxMaxAlign) {
721 if (MaxAlign == MaxMaxAlign)
723 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
724 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
726 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
728 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
729 unsigned EltAlign = 0;
730 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
731 if (EltAlign > MaxAlign)
733 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
734 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
735 unsigned EltAlign = 0;
736 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
737 if (EltAlign > MaxAlign)
739 if (MaxAlign == MaxMaxAlign)
745 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
746 /// function arguments in the caller parameter area.
747 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
748 // Darwin passes everything on 4 byte boundary.
749 if (Subtarget.isDarwin())
752 // 16byte and wider vectors are passed on 16byte boundary.
753 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
754 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
755 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
756 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
760 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
762 default: return nullptr;
763 case PPCISD::FSEL: return "PPCISD::FSEL";
764 case PPCISD::FCFID: return "PPCISD::FCFID";
765 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
766 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
767 case PPCISD::FRE: return "PPCISD::FRE";
768 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
769 case PPCISD::STFIWX: return "PPCISD::STFIWX";
770 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
771 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
772 case PPCISD::VPERM: return "PPCISD::VPERM";
773 case PPCISD::Hi: return "PPCISD::Hi";
774 case PPCISD::Lo: return "PPCISD::Lo";
775 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
776 case PPCISD::LOAD: return "PPCISD::LOAD";
777 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
778 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
779 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
780 case PPCISD::SRL: return "PPCISD::SRL";
781 case PPCISD::SRA: return "PPCISD::SRA";
782 case PPCISD::SHL: return "PPCISD::SHL";
783 case PPCISD::CALL: return "PPCISD::CALL";
784 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
785 case PPCISD::MTCTR: return "PPCISD::MTCTR";
786 case PPCISD::BCTRL: return "PPCISD::BCTRL";
787 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
788 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
789 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
790 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
791 case PPCISD::VCMP: return "PPCISD::VCMP";
792 case PPCISD::VCMPo: return "PPCISD::VCMPo";
793 case PPCISD::LBRX: return "PPCISD::LBRX";
794 case PPCISD::STBRX: return "PPCISD::STBRX";
795 case PPCISD::LARX: return "PPCISD::LARX";
796 case PPCISD::STCX: return "PPCISD::STCX";
797 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
798 case PPCISD::BDNZ: return "PPCISD::BDNZ";
799 case PPCISD::BDZ: return "PPCISD::BDZ";
800 case PPCISD::MFFS: return "PPCISD::MFFS";
801 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
802 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
803 case PPCISD::CR6SET: return "PPCISD::CR6SET";
804 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
805 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
806 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
807 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
808 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
809 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
810 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
811 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
812 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
813 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
814 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
815 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
816 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
817 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
818 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
819 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
820 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
821 case PPCISD::SC: return "PPCISD::SC";
825 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
827 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
828 return VT.changeVectorElementTypeToInteger();
831 //===----------------------------------------------------------------------===//
832 // Node matching predicates, for use by the tblgen matching code.
833 //===----------------------------------------------------------------------===//
835 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
836 static bool isFloatingPointZero(SDValue Op) {
837 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
838 return CFP->getValueAPF().isZero();
839 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
840 // Maybe this has already been legalized into the constant pool?
841 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
842 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
843 return CFP->getValueAPF().isZero();
848 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
849 /// true if Op is undef or if it matches the specified value.
850 static bool isConstantOrUndef(int Op, int Val) {
851 return Op < 0 || Op == Val;
854 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
855 /// VPKUHUM instruction.
856 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
858 unsigned j = DAG.getTarget().getDataLayout()->isLittleEndian() ? 0 : 1;
860 for (unsigned i = 0; i != 16; ++i)
861 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j))
864 for (unsigned i = 0; i != 8; ++i)
865 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
866 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
872 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
873 /// VPKUWUM instruction.
874 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
877 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
885 for (unsigned i = 0; i != 16; i += 2)
886 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
887 !isConstantOrUndef(N->getMaskElt(i+1), i*2+k))
890 for (unsigned i = 0; i != 8; i += 2)
891 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
892 !isConstantOrUndef(N->getMaskElt(i+1), i*2+k) ||
893 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
894 !isConstantOrUndef(N->getMaskElt(i+9), i*2+k))
900 /// isVMerge - Common function, used to match vmrg* shuffles.
902 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
903 unsigned LHSStart, unsigned RHSStart) {
904 if (N->getValueType(0) != MVT::v16i8)
906 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
907 "Unsupported merge size!");
909 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
910 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
911 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
912 LHSStart+j+i*UnitSize) ||
913 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
914 RHSStart+j+i*UnitSize))
920 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
921 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
922 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
923 bool isUnary, SelectionDAG &DAG) {
924 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
926 return isVMerge(N, UnitSize, 0, 16);
927 return isVMerge(N, UnitSize, 0, 0);
930 return isVMerge(N, UnitSize, 8, 24);
931 return isVMerge(N, UnitSize, 8, 8);
935 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
936 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
937 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
938 bool isUnary, SelectionDAG &DAG) {
939 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
941 return isVMerge(N, UnitSize, 8, 24);
942 return isVMerge(N, UnitSize, 8, 8);
945 return isVMerge(N, UnitSize, 0, 16);
946 return isVMerge(N, UnitSize, 0, 0);
951 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
952 /// amount, otherwise return -1.
953 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary, SelectionDAG &DAG) {
954 if (N->getValueType(0) != MVT::v16i8)
957 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
959 // Find the first non-undef value in the shuffle mask.
961 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
964 if (i == 16) return -1; // all undef.
966 // Otherwise, check to see if the rest of the elements are consecutively
967 // numbered from this value.
968 unsigned ShiftAmt = SVOp->getMaskElt(i);
969 if (ShiftAmt < i) return -1;
971 if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
976 // Check the rest of the elements to see if they are consecutive.
977 for (++i; i != 16; ++i)
978 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt - i))
981 // Check the rest of the elements to see if they are consecutive.
982 for (++i; i != 16; ++i)
983 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt - i) & 15))
987 } else { // Big Endian
992 // Check the rest of the elements to see if they are consecutive.
993 for (++i; i != 16; ++i)
994 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
997 // Check the rest of the elements to see if they are consecutive.
998 for (++i; i != 16; ++i)
999 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1006 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1007 /// specifies a splat of a single element that is suitable for input to
1008 /// VSPLTB/VSPLTH/VSPLTW.
1009 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1010 assert(N->getValueType(0) == MVT::v16i8 &&
1011 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1013 // This is a splat operation if each element of the permute is the same, and
1014 // if the value doesn't reference the second vector.
1015 unsigned ElementBase = N->getMaskElt(0);
1017 // FIXME: Handle UNDEF elements too!
1018 if (ElementBase >= 16)
1021 // Check that the indices are consecutive, in the case of a multi-byte element
1022 // splatted with a v16i8 mask.
1023 for (unsigned i = 1; i != EltSize; ++i)
1024 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1027 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1028 if (N->getMaskElt(i) < 0) continue;
1029 for (unsigned j = 0; j != EltSize; ++j)
1030 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1036 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1038 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1039 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1041 APInt APVal, APUndef;
1045 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1046 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1047 return CFP->getValueAPF().isNegZero();
1052 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1053 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1054 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1055 SelectionDAG &DAG) {
1056 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1057 assert(isSplatShuffleMask(SVOp, EltSize));
1058 if (DAG.getTarget().getDataLayout()->isLittleEndian())
1059 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1061 return SVOp->getMaskElt(0) / EltSize;
1064 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1065 /// by using a vspltis[bhw] instruction of the specified element size, return
1066 /// the constant being splatted. The ByteSize field indicates the number of
1067 /// bytes of each element [124] -> [bhw].
1068 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1069 SDValue OpVal(nullptr, 0);
1071 // If ByteSize of the splat is bigger than the element size of the
1072 // build_vector, then we have a case where we are checking for a splat where
1073 // multiple elements of the buildvector are folded together into a single
1074 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1075 unsigned EltSize = 16/N->getNumOperands();
1076 if (EltSize < ByteSize) {
1077 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1078 SDValue UniquedVals[4];
1079 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1081 // See if all of the elements in the buildvector agree across.
1082 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1083 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1084 // If the element isn't a constant, bail fully out.
1085 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1088 if (!UniquedVals[i&(Multiple-1)].getNode())
1089 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1090 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1091 return SDValue(); // no match.
1094 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1095 // either constant or undef values that are identical for each chunk. See
1096 // if these chunks can form into a larger vspltis*.
1098 // Check to see if all of the leading entries are either 0 or -1. If
1099 // neither, then this won't fit into the immediate field.
1100 bool LeadingZero = true;
1101 bool LeadingOnes = true;
1102 for (unsigned i = 0; i != Multiple-1; ++i) {
1103 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1105 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1106 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1108 // Finally, check the least significant entry.
1110 if (!UniquedVals[Multiple-1].getNode())
1111 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1112 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1114 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1117 if (!UniquedVals[Multiple-1].getNode())
1118 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1119 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1120 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1121 return DAG.getTargetConstant(Val, MVT::i32);
1127 // Check to see if this buildvec has a single non-undef value in its elements.
1128 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1129 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1130 if (!OpVal.getNode())
1131 OpVal = N->getOperand(i);
1132 else if (OpVal != N->getOperand(i))
1136 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1138 unsigned ValSizeInBytes = EltSize;
1140 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1141 Value = CN->getZExtValue();
1142 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1143 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1144 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1147 // If the splat value is larger than the element value, then we can never do
1148 // this splat. The only case that we could fit the replicated bits into our
1149 // immediate field for would be zero, and we prefer to use vxor for it.
1150 if (ValSizeInBytes < ByteSize) return SDValue();
1152 // If the element value is larger than the splat value, cut it in half and
1153 // check to see if the two halves are equal. Continue doing this until we
1154 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1155 while (ValSizeInBytes > ByteSize) {
1156 ValSizeInBytes >>= 1;
1158 // If the top half equals the bottom half, we're still ok.
1159 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1160 (Value & ((1 << (8*ValSizeInBytes))-1)))
1164 // Properly sign extend the value.
1165 int MaskVal = SignExtend32(Value, ByteSize * 8);
1167 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1168 if (MaskVal == 0) return SDValue();
1170 // Finally, if this value fits in a 5 bit sext field, return it
1171 if (SignExtend32<5>(MaskVal) == MaskVal)
1172 return DAG.getTargetConstant(MaskVal, MVT::i32);
1176 //===----------------------------------------------------------------------===//
1177 // Addressing Mode Selection
1178 //===----------------------------------------------------------------------===//
1180 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1181 /// or 64-bit immediate, and if the value can be accurately represented as a
1182 /// sign extension from a 16-bit value. If so, this returns true and the
1184 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1185 if (!isa<ConstantSDNode>(N))
1188 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1189 if (N->getValueType(0) == MVT::i32)
1190 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1192 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1194 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1195 return isIntS16Immediate(Op.getNode(), Imm);
1199 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1200 /// can be represented as an indexed [r+r] operation. Returns false if it
1201 /// can be more efficiently represented with [r+imm].
1202 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1204 SelectionDAG &DAG) const {
1206 if (N.getOpcode() == ISD::ADD) {
1207 if (isIntS16Immediate(N.getOperand(1), imm))
1208 return false; // r+i
1209 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1210 return false; // r+i
1212 Base = N.getOperand(0);
1213 Index = N.getOperand(1);
1215 } else if (N.getOpcode() == ISD::OR) {
1216 if (isIntS16Immediate(N.getOperand(1), imm))
1217 return false; // r+i can fold it if we can.
1219 // If this is an or of disjoint bitfields, we can codegen this as an add
1220 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1222 APInt LHSKnownZero, LHSKnownOne;
1223 APInt RHSKnownZero, RHSKnownOne;
1224 DAG.computeKnownBits(N.getOperand(0),
1225 LHSKnownZero, LHSKnownOne);
1227 if (LHSKnownZero.getBoolValue()) {
1228 DAG.computeKnownBits(N.getOperand(1),
1229 RHSKnownZero, RHSKnownOne);
1230 // If all of the bits are known zero on the LHS or RHS, the add won't
1232 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1233 Base = N.getOperand(0);
1234 Index = N.getOperand(1);
1243 // If we happen to be doing an i64 load or store into a stack slot that has
1244 // less than a 4-byte alignment, then the frame-index elimination may need to
1245 // use an indexed load or store instruction (because the offset may not be a
1246 // multiple of 4). The extra register needed to hold the offset comes from the
1247 // register scavenger, and it is possible that the scavenger will need to use
1248 // an emergency spill slot. As a result, we need to make sure that a spill slot
1249 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1251 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1252 // FIXME: This does not handle the LWA case.
1256 // NOTE: We'll exclude negative FIs here, which come from argument
1257 // lowering, because there are no known test cases triggering this problem
1258 // using packed structures (or similar). We can remove this exclusion if
1259 // we find such a test case. The reason why this is so test-case driven is
1260 // because this entire 'fixup' is only to prevent crashes (from the
1261 // register scavenger) on not-really-valid inputs. For example, if we have:
1263 // %b = bitcast i1* %a to i64*
1264 // store i64* a, i64 b
1265 // then the store should really be marked as 'align 1', but is not. If it
1266 // were marked as 'align 1' then the indexed form would have been
1267 // instruction-selected initially, and the problem this 'fixup' is preventing
1268 // won't happen regardless.
1272 MachineFunction &MF = DAG.getMachineFunction();
1273 MachineFrameInfo *MFI = MF.getFrameInfo();
1275 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1279 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1280 FuncInfo->setHasNonRISpills();
1283 /// Returns true if the address N can be represented by a base register plus
1284 /// a signed 16-bit displacement [r+imm], and if it is not better
1285 /// represented as reg+reg. If Aligned is true, only accept displacements
1286 /// suitable for STD and friends, i.e. multiples of 4.
1287 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1290 bool Aligned) const {
1291 // FIXME dl should come from parent load or store, not from address
1293 // If this can be more profitably realized as r+r, fail.
1294 if (SelectAddressRegReg(N, Disp, Base, DAG))
1297 if (N.getOpcode() == ISD::ADD) {
1299 if (isIntS16Immediate(N.getOperand(1), imm) &&
1300 (!Aligned || (imm & 3) == 0)) {
1301 Disp = DAG.getTargetConstant(imm, N.getValueType());
1302 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1303 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1304 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1306 Base = N.getOperand(0);
1308 return true; // [r+i]
1309 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1310 // Match LOAD (ADD (X, Lo(G))).
1311 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1312 && "Cannot handle constant offsets yet!");
1313 Disp = N.getOperand(1).getOperand(0); // The global address.
1314 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1315 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1316 Disp.getOpcode() == ISD::TargetConstantPool ||
1317 Disp.getOpcode() == ISD::TargetJumpTable);
1318 Base = N.getOperand(0);
1319 return true; // [&g+r]
1321 } else if (N.getOpcode() == ISD::OR) {
1323 if (isIntS16Immediate(N.getOperand(1), imm) &&
1324 (!Aligned || (imm & 3) == 0)) {
1325 // If this is an or of disjoint bitfields, we can codegen this as an add
1326 // (for better address arithmetic) if the LHS and RHS of the OR are
1327 // provably disjoint.
1328 APInt LHSKnownZero, LHSKnownOne;
1329 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1331 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1332 // If all of the bits are known zero on the LHS or RHS, the add won't
1334 if (FrameIndexSDNode *FI =
1335 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1336 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1337 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1339 Base = N.getOperand(0);
1341 Disp = DAG.getTargetConstant(imm, N.getValueType());
1345 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1346 // Loading from a constant address.
1348 // If this address fits entirely in a 16-bit sext immediate field, codegen
1351 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1352 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1353 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1354 CN->getValueType(0));
1358 // Handle 32-bit sext immediates with LIS + addr mode.
1359 if ((CN->getValueType(0) == MVT::i32 ||
1360 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1361 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1362 int Addr = (int)CN->getZExtValue();
1364 // Otherwise, break this down into an LIS + disp.
1365 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1367 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1368 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1369 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1374 Disp = DAG.getTargetConstant(0, getPointerTy());
1375 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1376 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1377 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1380 return true; // [r+0]
1383 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1384 /// represented as an indexed [r+r] operation.
1385 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1387 SelectionDAG &DAG) const {
1388 // Check to see if we can easily represent this as an [r+r] address. This
1389 // will fail if it thinks that the address is more profitably represented as
1390 // reg+imm, e.g. where imm = 0.
1391 if (SelectAddressRegReg(N, Base, Index, DAG))
1394 // If the operand is an addition, always emit this as [r+r], since this is
1395 // better (for code size, and execution, as the memop does the add for free)
1396 // than emitting an explicit add.
1397 if (N.getOpcode() == ISD::ADD) {
1398 Base = N.getOperand(0);
1399 Index = N.getOperand(1);
1403 // Otherwise, do it the hard way, using R0 as the base register.
1404 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1410 /// getPreIndexedAddressParts - returns true by value, base pointer and
1411 /// offset pointer and addressing mode by reference if the node's address
1412 /// can be legally represented as pre-indexed load / store address.
1413 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1415 ISD::MemIndexedMode &AM,
1416 SelectionDAG &DAG) const {
1417 if (DisablePPCPreinc) return false;
1423 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1424 Ptr = LD->getBasePtr();
1425 VT = LD->getMemoryVT();
1426 Alignment = LD->getAlignment();
1427 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1428 Ptr = ST->getBasePtr();
1429 VT = ST->getMemoryVT();
1430 Alignment = ST->getAlignment();
1435 // PowerPC doesn't have preinc load/store instructions for vectors.
1439 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1441 // Common code will reject creating a pre-inc form if the base pointer
1442 // is a frame index, or if N is a store and the base pointer is either
1443 // the same as or a predecessor of the value being stored. Check for
1444 // those situations here, and try with swapped Base/Offset instead.
1447 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1450 SDValue Val = cast<StoreSDNode>(N)->getValue();
1451 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1456 std::swap(Base, Offset);
1462 // LDU/STU can only handle immediates that are a multiple of 4.
1463 if (VT != MVT::i64) {
1464 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1467 // LDU/STU need an address with at least 4-byte alignment.
1471 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1475 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1476 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1477 // sext i32 to i64 when addr mode is r+i.
1478 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1479 LD->getExtensionType() == ISD::SEXTLOAD &&
1480 isa<ConstantSDNode>(Offset))
1488 //===----------------------------------------------------------------------===//
1489 // LowerOperation implementation
1490 //===----------------------------------------------------------------------===//
1492 /// GetLabelAccessInfo - Return true if we should reference labels using a
1493 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1494 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1495 unsigned &LoOpFlags,
1496 const GlobalValue *GV = nullptr) {
1497 HiOpFlags = PPCII::MO_HA;
1498 LoOpFlags = PPCII::MO_LO;
1500 // Don't use the pic base if not in PIC relocation model.
1501 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1504 HiOpFlags |= PPCII::MO_PIC_FLAG;
1505 LoOpFlags |= PPCII::MO_PIC_FLAG;
1508 // If this is a reference to a global value that requires a non-lazy-ptr, make
1509 // sure that instruction lowering adds it.
1510 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1511 HiOpFlags |= PPCII::MO_NLP_FLAG;
1512 LoOpFlags |= PPCII::MO_NLP_FLAG;
1514 if (GV->hasHiddenVisibility()) {
1515 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1516 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1523 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1524 SelectionDAG &DAG) {
1525 EVT PtrVT = HiPart.getValueType();
1526 SDValue Zero = DAG.getConstant(0, PtrVT);
1529 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1530 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1532 // With PIC, the first instruction is actually "GR+hi(&G)".
1534 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1535 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1537 // Generate non-pic code that has direct accesses to the constant pool.
1538 // The address of the global is just (hi(&g)+lo(&g)).
1539 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1542 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1543 SelectionDAG &DAG) const {
1544 EVT PtrVT = Op.getValueType();
1545 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1546 const Constant *C = CP->getConstVal();
1548 // 64-bit SVR4 ABI code is always position-independent.
1549 // The actual address of the GlobalValue is stored in the TOC.
1550 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1551 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1552 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1553 DAG.getRegister(PPC::X2, MVT::i64));
1556 unsigned MOHiFlag, MOLoFlag;
1557 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1559 if (isPIC && Subtarget.isSVR4ABI()) {
1560 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1561 PPCII::MO_PIC_FLAG);
1563 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1564 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1568 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1570 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1571 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1574 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1575 EVT PtrVT = Op.getValueType();
1576 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1578 // 64-bit SVR4 ABI code is always position-independent.
1579 // The actual address of the GlobalValue is stored in the TOC.
1580 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1581 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1582 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1583 DAG.getRegister(PPC::X2, MVT::i64));
1586 unsigned MOHiFlag, MOLoFlag;
1587 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1589 if (isPIC && Subtarget.isSVR4ABI()) {
1590 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1591 PPCII::MO_PIC_FLAG);
1593 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1594 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1597 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1598 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1599 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1602 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1603 SelectionDAG &DAG) const {
1604 EVT PtrVT = Op.getValueType();
1606 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1608 unsigned MOHiFlag, MOLoFlag;
1609 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1610 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1611 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1612 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1615 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1616 SelectionDAG &DAG) const {
1618 // FIXME: TLS addresses currently use medium model code sequences,
1619 // which is the most useful form. Eventually support for small and
1620 // large models could be added if users need it, at the cost of
1621 // additional complexity.
1622 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1624 const GlobalValue *GV = GA->getGlobal();
1625 EVT PtrVT = getPointerTy();
1626 bool is64bit = Subtarget.isPPC64();
1628 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1630 if (Model == TLSModel::LocalExec) {
1631 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1632 PPCII::MO_TPREL_HA);
1633 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1634 PPCII::MO_TPREL_LO);
1635 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1636 is64bit ? MVT::i64 : MVT::i32);
1637 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1638 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1641 if (Model == TLSModel::InitialExec) {
1642 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1643 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1647 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1648 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1649 PtrVT, GOTReg, TGA);
1651 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1652 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1653 PtrVT, TGA, GOTPtr);
1654 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1657 if (Model == TLSModel::GeneralDynamic) {
1658 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1659 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1660 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1662 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1665 // We need a chain node, and don't have one handy. The underlying
1666 // call has no side effects, so using the function entry node
1668 SDValue Chain = DAG.getEntryNode();
1669 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1670 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1671 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1672 PtrVT, ParmReg, TGA);
1673 // The return value from GET_TLS_ADDR really is in X3 already, but
1674 // some hacks are needed here to tie everything together. The extra
1675 // copies dissolve during subsequent transforms.
1676 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1677 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1680 if (Model == TLSModel::LocalDynamic) {
1681 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1682 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1683 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1685 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1688 // We need a chain node, and don't have one handy. The underlying
1689 // call has no side effects, so using the function entry node
1691 SDValue Chain = DAG.getEntryNode();
1692 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1693 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1694 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1695 PtrVT, ParmReg, TGA);
1696 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1697 // some hacks are needed here to tie everything together. The extra
1698 // copies dissolve during subsequent transforms.
1699 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1700 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1701 Chain, ParmReg, TGA);
1702 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1705 llvm_unreachable("Unknown TLS model!");
1708 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1709 SelectionDAG &DAG) const {
1710 EVT PtrVT = Op.getValueType();
1711 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1713 const GlobalValue *GV = GSDN->getGlobal();
1715 // 64-bit SVR4 ABI code is always position-independent.
1716 // The actual address of the GlobalValue is stored in the TOC.
1717 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1718 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1719 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1720 DAG.getRegister(PPC::X2, MVT::i64));
1723 unsigned MOHiFlag, MOLoFlag;
1724 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1726 if (isPIC && Subtarget.isSVR4ABI()) {
1727 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1729 PPCII::MO_PIC_FLAG);
1730 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1731 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1735 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1737 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1739 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1741 // If the global reference is actually to a non-lazy-pointer, we have to do an
1742 // extra load to get the address of the global.
1743 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1744 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1745 false, false, false, 0);
1749 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1750 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1753 if (Op.getValueType() == MVT::v2i64) {
1754 // When the operands themselves are v2i64 values, we need to do something
1755 // special because VSX has no underlying comparison operations for these.
1756 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1757 // Equality can be handled by casting to the legal type for Altivec
1758 // comparisons, everything else needs to be expanded.
1759 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1760 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1761 DAG.getSetCC(dl, MVT::v4i32,
1762 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1763 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1770 // We handle most of these in the usual way.
1774 // If we're comparing for equality to zero, expose the fact that this is
1775 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1776 // fold the new nodes.
1777 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1778 if (C->isNullValue() && CC == ISD::SETEQ) {
1779 EVT VT = Op.getOperand(0).getValueType();
1780 SDValue Zext = Op.getOperand(0);
1781 if (VT.bitsLT(MVT::i32)) {
1783 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1785 unsigned Log2b = Log2_32(VT.getSizeInBits());
1786 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1787 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1788 DAG.getConstant(Log2b, MVT::i32));
1789 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1791 // Leave comparisons against 0 and -1 alone for now, since they're usually
1792 // optimized. FIXME: revisit this when we can custom lower all setcc
1794 if (C->isAllOnesValue() || C->isNullValue())
1798 // If we have an integer seteq/setne, turn it into a compare against zero
1799 // by xor'ing the rhs with the lhs, which is faster than setting a
1800 // condition register, reading it back out, and masking the correct bit. The
1801 // normal approach here uses sub to do this instead of xor. Using xor exposes
1802 // the result to other bit-twiddling opportunities.
1803 EVT LHSVT = Op.getOperand(0).getValueType();
1804 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1805 EVT VT = Op.getValueType();
1806 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1808 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1813 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1814 const PPCSubtarget &Subtarget) const {
1815 SDNode *Node = Op.getNode();
1816 EVT VT = Node->getValueType(0);
1817 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1818 SDValue InChain = Node->getOperand(0);
1819 SDValue VAListPtr = Node->getOperand(1);
1820 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1823 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1826 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1827 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1829 InChain = GprIndex.getValue(1);
1831 if (VT == MVT::i64) {
1832 // Check if GprIndex is even
1833 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1834 DAG.getConstant(1, MVT::i32));
1835 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1836 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1837 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1838 DAG.getConstant(1, MVT::i32));
1839 // Align GprIndex to be even if it isn't
1840 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1844 // fpr index is 1 byte after gpr
1845 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1846 DAG.getConstant(1, MVT::i32));
1849 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1850 FprPtr, MachinePointerInfo(SV), MVT::i8,
1852 InChain = FprIndex.getValue(1);
1854 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1855 DAG.getConstant(8, MVT::i32));
1857 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1858 DAG.getConstant(4, MVT::i32));
1861 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1862 MachinePointerInfo(), false, false,
1864 InChain = OverflowArea.getValue(1);
1866 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1867 MachinePointerInfo(), false, false,
1869 InChain = RegSaveArea.getValue(1);
1871 // select overflow_area if index > 8
1872 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1873 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1875 // adjustment constant gpr_index * 4/8
1876 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1877 VT.isInteger() ? GprIndex : FprIndex,
1878 DAG.getConstant(VT.isInteger() ? 4 : 8,
1881 // OurReg = RegSaveArea + RegConstant
1882 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1885 // Floating types are 32 bytes into RegSaveArea
1886 if (VT.isFloatingPoint())
1887 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1888 DAG.getConstant(32, MVT::i32));
1890 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1891 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1892 VT.isInteger() ? GprIndex : FprIndex,
1893 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1896 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1897 VT.isInteger() ? VAListPtr : FprPtr,
1898 MachinePointerInfo(SV),
1899 MVT::i8, false, false, 0);
1901 // determine if we should load from reg_save_area or overflow_area
1902 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1904 // increase overflow_area by 4/8 if gpr/fpr > 8
1905 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1906 DAG.getConstant(VT.isInteger() ? 4 : 8,
1909 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1912 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1914 MachinePointerInfo(),
1915 MVT::i32, false, false, 0);
1917 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1918 false, false, false, 0);
1921 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1922 const PPCSubtarget &Subtarget) const {
1923 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1925 // We have to copy the entire va_list struct:
1926 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1927 return DAG.getMemcpy(Op.getOperand(0), Op,
1928 Op.getOperand(1), Op.getOperand(2),
1929 DAG.getConstant(12, MVT::i32), 8, false, true,
1930 MachinePointerInfo(), MachinePointerInfo());
1933 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1934 SelectionDAG &DAG) const {
1935 return Op.getOperand(0);
1938 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1939 SelectionDAG &DAG) const {
1940 SDValue Chain = Op.getOperand(0);
1941 SDValue Trmp = Op.getOperand(1); // trampoline
1942 SDValue FPtr = Op.getOperand(2); // nested function
1943 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1946 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1947 bool isPPC64 = (PtrVT == MVT::i64);
1949 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1952 TargetLowering::ArgListTy Args;
1953 TargetLowering::ArgListEntry Entry;
1955 Entry.Ty = IntPtrTy;
1956 Entry.Node = Trmp; Args.push_back(Entry);
1958 // TrampSize == (isPPC64 ? 48 : 40);
1959 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1960 isPPC64 ? MVT::i64 : MVT::i32);
1961 Args.push_back(Entry);
1963 Entry.Node = FPtr; Args.push_back(Entry);
1964 Entry.Node = Nest; Args.push_back(Entry);
1966 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1967 TargetLowering::CallLoweringInfo CLI(DAG);
1968 CLI.setDebugLoc(dl).setChain(Chain)
1969 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
1970 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1971 std::move(Args), 0);
1973 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1974 return CallResult.second;
1977 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1978 const PPCSubtarget &Subtarget) const {
1979 MachineFunction &MF = DAG.getMachineFunction();
1980 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1984 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1985 // vastart just stores the address of the VarArgsFrameIndex slot into the
1986 // memory location argument.
1987 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1988 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1989 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1990 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1991 MachinePointerInfo(SV),
1995 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1996 // We suppose the given va_list is already allocated.
1999 // char gpr; /* index into the array of 8 GPRs
2000 // * stored in the register save area
2001 // * gpr=0 corresponds to r3,
2002 // * gpr=1 to r4, etc.
2004 // char fpr; /* index into the array of 8 FPRs
2005 // * stored in the register save area
2006 // * fpr=0 corresponds to f1,
2007 // * fpr=1 to f2, etc.
2009 // char *overflow_arg_area;
2010 // /* location on stack that holds
2011 // * the next overflow argument
2013 // char *reg_save_area;
2014 // /* where r3:r10 and f1:f8 (if saved)
2020 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2021 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2024 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2026 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2028 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2031 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2032 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2034 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2035 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2037 uint64_t FPROffset = 1;
2038 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2040 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2042 // Store first byte : number of int regs
2043 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2045 MachinePointerInfo(SV),
2046 MVT::i8, false, false, 0);
2047 uint64_t nextOffset = FPROffset;
2048 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2051 // Store second byte : number of float regs
2052 SDValue secondStore =
2053 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2054 MachinePointerInfo(SV, nextOffset), MVT::i8,
2056 nextOffset += StackOffset;
2057 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2059 // Store second word : arguments given on stack
2060 SDValue thirdStore =
2061 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2062 MachinePointerInfo(SV, nextOffset),
2064 nextOffset += FrameOffset;
2065 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2067 // Store third word : arguments given in registers
2068 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2069 MachinePointerInfo(SV, nextOffset),
2074 #include "PPCGenCallingConv.inc"
2076 // Function whose sole purpose is to kill compiler warnings
2077 // stemming from unused functions included from PPCGenCallingConv.inc.
2078 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2079 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2082 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2083 CCValAssign::LocInfo &LocInfo,
2084 ISD::ArgFlagsTy &ArgFlags,
2089 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2091 CCValAssign::LocInfo &LocInfo,
2092 ISD::ArgFlagsTy &ArgFlags,
2094 static const MCPhysReg ArgRegs[] = {
2095 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2096 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2098 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2100 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2102 // Skip one register if the first unallocated register has an even register
2103 // number and there are still argument registers available which have not been
2104 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2105 // need to skip a register if RegNum is odd.
2106 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2107 State.AllocateReg(ArgRegs[RegNum]);
2110 // Always return false here, as this function only makes sure that the first
2111 // unallocated register has an odd register number and does not actually
2112 // allocate a register for the current argument.
2116 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2118 CCValAssign::LocInfo &LocInfo,
2119 ISD::ArgFlagsTy &ArgFlags,
2121 static const MCPhysReg ArgRegs[] = {
2122 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2126 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2128 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2130 // If there is only one Floating-point register left we need to put both f64
2131 // values of a split ppc_fp128 value on the stack.
2132 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2133 State.AllocateReg(ArgRegs[RegNum]);
2136 // Always return false here, as this function only makes sure that the two f64
2137 // values a ppc_fp128 value is split into are both passed in registers or both
2138 // passed on the stack and does not actually allocate a register for the
2139 // current argument.
2143 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2145 static const MCPhysReg *GetFPR() {
2146 static const MCPhysReg FPR[] = {
2147 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2148 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2154 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2156 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2157 unsigned PtrByteSize) {
2158 unsigned ArgSize = ArgVT.getStoreSize();
2159 if (Flags.isByVal())
2160 ArgSize = Flags.getByValSize();
2161 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2166 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2168 static unsigned CalculateStackSlotAlignment(EVT ArgVT, ISD::ArgFlagsTy Flags,
2169 unsigned PtrByteSize) {
2170 unsigned Align = PtrByteSize;
2172 // Altivec parameters are padded to a 16 byte boundary.
2173 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2174 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2175 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2178 // ByVal parameters are aligned as requested.
2179 if (Flags.isByVal()) {
2180 unsigned BVAlign = Flags.getByValAlign();
2181 if (BVAlign > PtrByteSize) {
2182 if (BVAlign % PtrByteSize != 0)
2184 "ByVal alignment is not a multiple of the pointer size");
2193 /// CalculateStackSlotUsed - Return whether this argument will use its
2194 /// stack slot (instead of being passed in registers). ArgOffset,
2195 /// AvailableFPRs, and AvailableVRs must hold the current argument
2196 /// position, and will be updated to account for this argument.
2197 static bool CalculateStackSlotUsed(EVT ArgVT, ISD::ArgFlagsTy Flags,
2198 unsigned PtrByteSize,
2199 unsigned LinkageSize,
2200 unsigned ParamAreaSize,
2201 unsigned &ArgOffset,
2202 unsigned &AvailableFPRs,
2203 unsigned &AvailableVRs) {
2204 bool UseMemory = false;
2206 // Respect alignment of argument on the stack.
2207 unsigned Align = CalculateStackSlotAlignment(ArgVT, Flags, PtrByteSize);
2208 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2209 // If there's no space left in the argument save area, we must
2210 // use memory (this check also catches zero-sized arguments).
2211 if (ArgOffset >= LinkageSize + ParamAreaSize)
2214 // Allocate argument on the stack.
2215 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2216 // If we overran the argument save area, we must use memory
2217 // (this check catches arguments passed partially in memory)
2218 if (ArgOffset > LinkageSize + ParamAreaSize)
2221 // However, if the argument is actually passed in an FPR or a VR,
2222 // we don't use memory after all.
2223 if (!Flags.isByVal()) {
2224 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2225 if (AvailableFPRs > 0) {
2229 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2230 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2231 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2232 if (AvailableVRs > 0) {
2241 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2242 /// ensure minimum alignment required for target.
2243 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2244 unsigned NumBytes) {
2245 unsigned TargetAlign = Target.getFrameLowering()->getStackAlignment();
2246 unsigned AlignMask = TargetAlign - 1;
2247 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2252 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2253 CallingConv::ID CallConv, bool isVarArg,
2254 const SmallVectorImpl<ISD::InputArg>
2256 SDLoc dl, SelectionDAG &DAG,
2257 SmallVectorImpl<SDValue> &InVals)
2259 if (Subtarget.isSVR4ABI()) {
2260 if (Subtarget.isPPC64())
2261 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2264 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2267 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2273 PPCTargetLowering::LowerFormalArguments_32SVR4(
2275 CallingConv::ID CallConv, bool isVarArg,
2276 const SmallVectorImpl<ISD::InputArg>
2278 SDLoc dl, SelectionDAG &DAG,
2279 SmallVectorImpl<SDValue> &InVals) const {
2281 // 32-bit SVR4 ABI Stack Frame Layout:
2282 // +-----------------------------------+
2283 // +--> | Back chain |
2284 // | +-----------------------------------+
2285 // | | Floating-point register save area |
2286 // | +-----------------------------------+
2287 // | | General register save area |
2288 // | +-----------------------------------+
2289 // | | CR save word |
2290 // | +-----------------------------------+
2291 // | | VRSAVE save word |
2292 // | +-----------------------------------+
2293 // | | Alignment padding |
2294 // | +-----------------------------------+
2295 // | | Vector register save area |
2296 // | +-----------------------------------+
2297 // | | Local variable space |
2298 // | +-----------------------------------+
2299 // | | Parameter list area |
2300 // | +-----------------------------------+
2301 // | | LR save word |
2302 // | +-----------------------------------+
2303 // SP--> +--- | Back chain |
2304 // +-----------------------------------+
2307 // System V Application Binary Interface PowerPC Processor Supplement
2308 // AltiVec Technology Programming Interface Manual
2310 MachineFunction &MF = DAG.getMachineFunction();
2311 MachineFrameInfo *MFI = MF.getFrameInfo();
2312 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2314 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2315 // Potential tail calls could cause overwriting of argument stack slots.
2316 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2317 (CallConv == CallingConv::Fast));
2318 unsigned PtrByteSize = 4;
2320 // Assign locations to all of the incoming arguments.
2321 SmallVector<CCValAssign, 16> ArgLocs;
2322 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2323 getTargetMachine(), ArgLocs, *DAG.getContext());
2325 // Reserve space for the linkage area on the stack.
2326 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2327 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2329 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2331 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2332 CCValAssign &VA = ArgLocs[i];
2334 // Arguments stored in registers.
2335 if (VA.isRegLoc()) {
2336 const TargetRegisterClass *RC;
2337 EVT ValVT = VA.getValVT();
2339 switch (ValVT.getSimpleVT().SimpleTy) {
2341 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2344 RC = &PPC::GPRCRegClass;
2347 RC = &PPC::F4RCRegClass;
2350 if (Subtarget.hasVSX())
2351 RC = &PPC::VSFRCRegClass;
2353 RC = &PPC::F8RCRegClass;
2359 RC = &PPC::VRRCRegClass;
2363 RC = &PPC::VSHRCRegClass;
2367 // Transform the arguments stored in physical registers into virtual ones.
2368 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2369 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2370 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2372 if (ValVT == MVT::i1)
2373 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2375 InVals.push_back(ArgValue);
2377 // Argument stored in memory.
2378 assert(VA.isMemLoc());
2380 unsigned ArgSize = VA.getLocVT().getStoreSize();
2381 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2384 // Create load nodes to retrieve arguments from the stack.
2385 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2386 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2387 MachinePointerInfo(),
2388 false, false, false, 0));
2392 // Assign locations to all of the incoming aggregate by value arguments.
2393 // Aggregates passed by value are stored in the local variable space of the
2394 // caller's stack frame, right above the parameter list area.
2395 SmallVector<CCValAssign, 16> ByValArgLocs;
2396 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2397 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2399 // Reserve stack space for the allocations in CCInfo.
2400 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2402 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2404 // Area that is at least reserved in the caller of this function.
2405 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2406 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2408 // Set the size that is at least reserved in caller of this function. Tail
2409 // call optimized function's reserved stack space needs to be aligned so that
2410 // taking the difference between two stack areas will result in an aligned
2412 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2413 FuncInfo->setMinReservedArea(MinReservedArea);
2415 SmallVector<SDValue, 8> MemOps;
2417 // If the function takes variable number of arguments, make a frame index for
2418 // the start of the first vararg value... for expansion of llvm.va_start.
2420 static const MCPhysReg GPArgRegs[] = {
2421 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2422 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2424 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2426 static const MCPhysReg FPArgRegs[] = {
2427 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2430 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2432 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2434 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2437 // Make room for NumGPArgRegs and NumFPArgRegs.
2438 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2439 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2441 FuncInfo->setVarArgsStackOffset(
2442 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2443 CCInfo.getNextStackOffset(), true));
2445 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2446 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2448 // The fixed integer arguments of a variadic function are stored to the
2449 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2450 // the result of va_next.
2451 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2452 // Get an existing live-in vreg, or add a new one.
2453 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2455 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2457 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2458 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2459 MachinePointerInfo(), false, false, 0);
2460 MemOps.push_back(Store);
2461 // Increment the address by four for the next argument to store
2462 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2463 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2466 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2468 // The double arguments are stored to the VarArgsFrameIndex
2470 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2471 // Get an existing live-in vreg, or add a new one.
2472 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2474 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2476 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2477 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2478 MachinePointerInfo(), false, false, 0);
2479 MemOps.push_back(Store);
2480 // Increment the address by eight for the next argument to store
2481 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2483 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2487 if (!MemOps.empty())
2488 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2493 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2494 // value to MVT::i64 and then truncate to the correct register size.
2496 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2497 SelectionDAG &DAG, SDValue ArgVal,
2500 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2501 DAG.getValueType(ObjectVT));
2502 else if (Flags.isZExt())
2503 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2504 DAG.getValueType(ObjectVT));
2506 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2510 PPCTargetLowering::LowerFormalArguments_64SVR4(
2512 CallingConv::ID CallConv, bool isVarArg,
2513 const SmallVectorImpl<ISD::InputArg>
2515 SDLoc dl, SelectionDAG &DAG,
2516 SmallVectorImpl<SDValue> &InVals) const {
2517 // TODO: add description of PPC stack frame format, or at least some docs.
2519 bool isELFv2ABI = Subtarget.isELFv2ABI();
2520 bool isLittleEndian = Subtarget.isLittleEndian();
2521 MachineFunction &MF = DAG.getMachineFunction();
2522 MachineFrameInfo *MFI = MF.getFrameInfo();
2523 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2525 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2526 // Potential tail calls could cause overwriting of argument stack slots.
2527 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2528 (CallConv == CallingConv::Fast));
2529 unsigned PtrByteSize = 8;
2531 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2534 static const MCPhysReg GPR[] = {
2535 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2536 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2539 static const MCPhysReg *FPR = GetFPR();
2541 static const MCPhysReg VR[] = {
2542 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2543 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2545 static const MCPhysReg VSRH[] = {
2546 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2547 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2550 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2551 const unsigned Num_FPR_Regs = 13;
2552 const unsigned Num_VR_Regs = array_lengthof(VR);
2554 // Do a first pass over the arguments to determine whether the ABI
2555 // guarantees that our caller has allocated the parameter save area
2556 // on its stack frame. In the ELFv1 ABI, this is always the case;
2557 // in the ELFv2 ABI, it is true if this is a vararg function or if
2558 // any parameter is located in a stack slot.
2560 bool HasParameterArea = !isELFv2ABI || isVarArg;
2561 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2562 unsigned NumBytes = LinkageSize;
2563 unsigned AvailableFPRs = Num_FPR_Regs;
2564 unsigned AvailableVRs = Num_VR_Regs;
2565 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2566 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].Flags,
2567 PtrByteSize, LinkageSize, ParamAreaSize,
2568 NumBytes, AvailableFPRs, AvailableVRs))
2569 HasParameterArea = true;
2571 // Add DAG nodes to load the arguments or copy them out of registers. On
2572 // entry to a function on PPC, the arguments start after the linkage area,
2573 // although the first ones are often in registers.
2575 unsigned ArgOffset = LinkageSize;
2576 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2577 SmallVector<SDValue, 8> MemOps;
2578 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2579 unsigned CurArgIdx = 0;
2580 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2582 bool needsLoad = false;
2583 EVT ObjectVT = Ins[ArgNo].VT;
2584 unsigned ObjSize = ObjectVT.getStoreSize();
2585 unsigned ArgSize = ObjSize;
2586 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2587 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2588 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2590 /* Respect alignment of argument on the stack. */
2592 CalculateStackSlotAlignment(ObjectVT, Flags, PtrByteSize);
2593 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2594 unsigned CurArgOffset = ArgOffset;
2596 /* Compute GPR index associated with argument offset. */
2597 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2598 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2600 // FIXME the codegen can be much improved in some cases.
2601 // We do not have to keep everything in memory.
2602 if (Flags.isByVal()) {
2603 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2604 ObjSize = Flags.getByValSize();
2605 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2606 // Empty aggregate parameters do not take up registers. Examples:
2610 // etc. However, we have to provide a place-holder in InVals, so
2611 // pretend we have an 8-byte item at the current address for that
2614 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2615 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2616 InVals.push_back(FIN);
2620 // Create a stack object covering all stack doublewords occupied
2621 // by the argument. If the argument is (fully or partially) on
2622 // the stack, or if the argument is fully in registers but the
2623 // caller has allocated the parameter save anyway, we can refer
2624 // directly to the caller's stack frame. Otherwise, create a
2625 // local copy in our own frame.
2627 if (HasParameterArea ||
2628 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2629 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
2631 FI = MFI->CreateStackObject(ArgSize, Align, false);
2632 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2634 // Handle aggregates smaller than 8 bytes.
2635 if (ObjSize < PtrByteSize) {
2636 // The value of the object is its address, which differs from the
2637 // address of the enclosing doubleword on big-endian systems.
2639 if (!isLittleEndian) {
2640 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2641 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2643 InVals.push_back(Arg);
2645 if (GPR_idx != Num_GPR_Regs) {
2646 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2647 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2650 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2651 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2652 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2653 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2654 MachinePointerInfo(FuncArg),
2655 ObjType, false, false, 0);
2657 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2658 // store the whole register as-is to the parameter save area
2660 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2661 MachinePointerInfo(FuncArg),
2665 MemOps.push_back(Store);
2667 // Whether we copied from a register or not, advance the offset
2668 // into the parameter save area by a full doubleword.
2669 ArgOffset += PtrByteSize;
2673 // The value of the object is its address, which is the address of
2674 // its first stack doubleword.
2675 InVals.push_back(FIN);
2677 // Store whatever pieces of the object are in registers to memory.
2678 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2679 if (GPR_idx == Num_GPR_Regs)
2682 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2683 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2686 SDValue Off = DAG.getConstant(j, PtrVT);
2687 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2689 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2690 MachinePointerInfo(FuncArg, j),
2692 MemOps.push_back(Store);
2695 ArgOffset += ArgSize;
2699 switch (ObjectVT.getSimpleVT().SimpleTy) {
2700 default: llvm_unreachable("Unhandled argument type!");
2704 if (GPR_idx != Num_GPR_Regs) {
2705 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2706 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2708 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2709 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2710 // value to MVT::i64 and then truncate to the correct register size.
2711 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2714 ArgSize = PtrByteSize;
2721 if (FPR_idx != Num_FPR_Regs) {
2724 if (ObjectVT == MVT::f32)
2725 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2727 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2728 &PPC::VSFRCRegClass :
2729 &PPC::F8RCRegClass);
2731 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2735 ArgSize = PtrByteSize;
2746 if (VR_idx != Num_VR_Regs) {
2747 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2748 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2749 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2750 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2759 // We need to load the argument to a virtual register if we determined
2760 // above that we ran out of physical registers of the appropriate type.
2762 if (ObjSize < ArgSize && !isLittleEndian)
2763 CurArgOffset += ArgSize - ObjSize;
2764 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2765 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2766 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2767 false, false, false, 0);
2770 InVals.push_back(ArgVal);
2773 // Area that is at least reserved in the caller of this function.
2774 unsigned MinReservedArea;
2775 if (HasParameterArea)
2776 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2778 MinReservedArea = LinkageSize;
2780 // Set the size that is at least reserved in caller of this function. Tail
2781 // call optimized functions' reserved stack space needs to be aligned so that
2782 // taking the difference between two stack areas will result in an aligned
2784 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2785 FuncInfo->setMinReservedArea(MinReservedArea);
2787 // If the function takes variable number of arguments, make a frame index for
2788 // the start of the first vararg value... for expansion of llvm.va_start.
2790 int Depth = ArgOffset;
2792 FuncInfo->setVarArgsFrameIndex(
2793 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2794 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2796 // If this function is vararg, store any remaining integer argument regs
2797 // to their spots on the stack so that they may be loaded by deferencing the
2798 // result of va_next.
2799 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2800 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2801 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2802 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2803 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2804 MachinePointerInfo(), false, false, 0);
2805 MemOps.push_back(Store);
2806 // Increment the address by four for the next argument to store
2807 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2808 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2812 if (!MemOps.empty())
2813 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2819 PPCTargetLowering::LowerFormalArguments_Darwin(
2821 CallingConv::ID CallConv, bool isVarArg,
2822 const SmallVectorImpl<ISD::InputArg>
2824 SDLoc dl, SelectionDAG &DAG,
2825 SmallVectorImpl<SDValue> &InVals) const {
2826 // TODO: add description of PPC stack frame format, or at least some docs.
2828 MachineFunction &MF = DAG.getMachineFunction();
2829 MachineFrameInfo *MFI = MF.getFrameInfo();
2830 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2832 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2833 bool isPPC64 = PtrVT == MVT::i64;
2834 // Potential tail calls could cause overwriting of argument stack slots.
2835 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2836 (CallConv == CallingConv::Fast));
2837 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2839 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2841 unsigned ArgOffset = LinkageSize;
2842 // Area that is at least reserved in caller of this function.
2843 unsigned MinReservedArea = ArgOffset;
2845 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2846 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2847 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2849 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2850 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2851 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2854 static const MCPhysReg *FPR = GetFPR();
2856 static const MCPhysReg VR[] = {
2857 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2858 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2861 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2862 const unsigned Num_FPR_Regs = 13;
2863 const unsigned Num_VR_Regs = array_lengthof( VR);
2865 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2867 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2869 // In 32-bit non-varargs functions, the stack space for vectors is after the
2870 // stack space for non-vectors. We do not use this space unless we have
2871 // too many vectors to fit in registers, something that only occurs in
2872 // constructed examples:), but we have to walk the arglist to figure
2873 // that out...for the pathological case, compute VecArgOffset as the
2874 // start of the vector parameter area. Computing VecArgOffset is the
2875 // entire point of the following loop.
2876 unsigned VecArgOffset = ArgOffset;
2877 if (!isVarArg && !isPPC64) {
2878 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2880 EVT ObjectVT = Ins[ArgNo].VT;
2881 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2883 if (Flags.isByVal()) {
2884 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2885 unsigned ObjSize = Flags.getByValSize();
2887 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2888 VecArgOffset += ArgSize;
2892 switch(ObjectVT.getSimpleVT().SimpleTy) {
2893 default: llvm_unreachable("Unhandled argument type!");
2899 case MVT::i64: // PPC64
2901 // FIXME: We are guaranteed to be !isPPC64 at this point.
2902 // Does MVT::i64 apply?
2909 // Nothing to do, we're only looking at Nonvector args here.
2914 // We've found where the vector parameter area in memory is. Skip the
2915 // first 12 parameters; these don't use that memory.
2916 VecArgOffset = ((VecArgOffset+15)/16)*16;
2917 VecArgOffset += 12*16;
2919 // Add DAG nodes to load the arguments or copy them out of registers. On
2920 // entry to a function on PPC, the arguments start after the linkage area,
2921 // although the first ones are often in registers.
2923 SmallVector<SDValue, 8> MemOps;
2924 unsigned nAltivecParamsAtEnd = 0;
2925 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2926 unsigned CurArgIdx = 0;
2927 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2929 bool needsLoad = false;
2930 EVT ObjectVT = Ins[ArgNo].VT;
2931 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2932 unsigned ArgSize = ObjSize;
2933 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2934 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2935 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2937 unsigned CurArgOffset = ArgOffset;
2939 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2940 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2941 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2942 if (isVarArg || isPPC64) {
2943 MinReservedArea = ((MinReservedArea+15)/16)*16;
2944 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2947 } else nAltivecParamsAtEnd++;
2949 // Calculate min reserved area.
2950 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2954 // FIXME the codegen can be much improved in some cases.
2955 // We do not have to keep everything in memory.
2956 if (Flags.isByVal()) {
2957 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2958 ObjSize = Flags.getByValSize();
2959 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2960 // Objects of size 1 and 2 are right justified, everything else is
2961 // left justified. This means the memory address is adjusted forwards.
2962 if (ObjSize==1 || ObjSize==2) {
2963 CurArgOffset = CurArgOffset + (4 - ObjSize);
2965 // The value of the object is its address.
2966 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2967 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2968 InVals.push_back(FIN);
2969 if (ObjSize==1 || ObjSize==2) {
2970 if (GPR_idx != Num_GPR_Regs) {
2973 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2975 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2976 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2977 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2978 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2979 MachinePointerInfo(FuncArg),
2980 ObjType, false, false, 0);
2981 MemOps.push_back(Store);
2985 ArgOffset += PtrByteSize;
2989 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2990 // Store whatever pieces of the object are in registers
2991 // to memory. ArgOffset will be the address of the beginning
2993 if (GPR_idx != Num_GPR_Regs) {
2996 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2998 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2999 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3000 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3001 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3002 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3003 MachinePointerInfo(FuncArg, j),
3005 MemOps.push_back(Store);
3007 ArgOffset += PtrByteSize;
3009 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3016 switch (ObjectVT.getSimpleVT().SimpleTy) {
3017 default: llvm_unreachable("Unhandled argument type!");
3021 if (GPR_idx != Num_GPR_Regs) {
3022 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3023 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3025 if (ObjectVT == MVT::i1)
3026 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3031 ArgSize = PtrByteSize;
3033 // All int arguments reserve stack space in the Darwin ABI.
3034 ArgOffset += PtrByteSize;
3038 case MVT::i64: // PPC64
3039 if (GPR_idx != Num_GPR_Regs) {
3040 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3041 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3043 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3044 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3045 // value to MVT::i64 and then truncate to the correct register size.
3046 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3051 ArgSize = PtrByteSize;
3053 // All int arguments reserve stack space in the Darwin ABI.
3059 // Every 4 bytes of argument space consumes one of the GPRs available for
3060 // argument passing.
3061 if (GPR_idx != Num_GPR_Regs) {
3063 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3066 if (FPR_idx != Num_FPR_Regs) {
3069 if (ObjectVT == MVT::f32)
3070 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3072 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3074 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3080 // All FP arguments reserve stack space in the Darwin ABI.
3081 ArgOffset += isPPC64 ? 8 : ObjSize;
3087 // Note that vector arguments in registers don't reserve stack space,
3088 // except in varargs functions.
3089 if (VR_idx != Num_VR_Regs) {
3090 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3091 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3093 while ((ArgOffset % 16) != 0) {
3094 ArgOffset += PtrByteSize;
3095 if (GPR_idx != Num_GPR_Regs)
3099 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3103 if (!isVarArg && !isPPC64) {
3104 // Vectors go after all the nonvectors.
3105 CurArgOffset = VecArgOffset;
3108 // Vectors are aligned.
3109 ArgOffset = ((ArgOffset+15)/16)*16;
3110 CurArgOffset = ArgOffset;
3118 // We need to load the argument to a virtual register if we determined above
3119 // that we ran out of physical registers of the appropriate type.
3121 int FI = MFI->CreateFixedObject(ObjSize,
3122 CurArgOffset + (ArgSize - ObjSize),
3124 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3125 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3126 false, false, false, 0);
3129 InVals.push_back(ArgVal);
3132 // Allow for Altivec parameters at the end, if needed.
3133 if (nAltivecParamsAtEnd) {
3134 MinReservedArea = ((MinReservedArea+15)/16)*16;
3135 MinReservedArea += 16*nAltivecParamsAtEnd;
3138 // Area that is at least reserved in the caller of this function.
3139 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3141 // Set the size that is at least reserved in caller of this function. Tail
3142 // call optimized functions' reserved stack space needs to be aligned so that
3143 // taking the difference between two stack areas will result in an aligned
3145 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3146 FuncInfo->setMinReservedArea(MinReservedArea);
3148 // If the function takes variable number of arguments, make a frame index for
3149 // the start of the first vararg value... for expansion of llvm.va_start.
3151 int Depth = ArgOffset;
3153 FuncInfo->setVarArgsFrameIndex(
3154 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3156 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3158 // If this function is vararg, store any remaining integer argument regs
3159 // to their spots on the stack so that they may be loaded by deferencing the
3160 // result of va_next.
3161 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3165 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3167 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3169 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3170 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3171 MachinePointerInfo(), false, false, 0);
3172 MemOps.push_back(Store);
3173 // Increment the address by four for the next argument to store
3174 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3175 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3179 if (!MemOps.empty())
3180 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3185 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3186 /// adjusted to accommodate the arguments for the tailcall.
3187 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3188 unsigned ParamSize) {
3190 if (!isTailCall) return 0;
3192 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3193 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3194 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3195 // Remember only if the new adjustement is bigger.
3196 if (SPDiff < FI->getTailCallSPDelta())
3197 FI->setTailCallSPDelta(SPDiff);
3202 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3203 /// for tail call optimization. Targets which want to do tail call
3204 /// optimization should implement this function.
3206 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3207 CallingConv::ID CalleeCC,
3209 const SmallVectorImpl<ISD::InputArg> &Ins,
3210 SelectionDAG& DAG) const {
3211 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3214 // Variable argument functions are not supported.
3218 MachineFunction &MF = DAG.getMachineFunction();
3219 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3220 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3221 // Functions containing by val parameters are not supported.
3222 for (unsigned i = 0; i != Ins.size(); i++) {
3223 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3224 if (Flags.isByVal()) return false;
3227 // Non-PIC/GOT tail calls are supported.
3228 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3231 // At the moment we can only do local tail calls (in same module, hidden
3232 // or protected) if we are generating PIC.
3233 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3234 return G->getGlobal()->hasHiddenVisibility()
3235 || G->getGlobal()->hasProtectedVisibility();
3241 /// isCallCompatibleAddress - Return the immediate to use if the specified
3242 /// 32-bit value is representable in the immediate field of a BxA instruction.
3243 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3244 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3245 if (!C) return nullptr;
3247 int Addr = C->getZExtValue();
3248 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3249 SignExtend32<26>(Addr) != Addr)
3250 return nullptr; // Top 6 bits have to be sext of immediate.
3252 return DAG.getConstant((int)C->getZExtValue() >> 2,
3253 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3258 struct TailCallArgumentInfo {
3263 TailCallArgumentInfo() : FrameIdx(0) {}
3268 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3270 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3272 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3273 SmallVectorImpl<SDValue> &MemOpChains,
3275 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3276 SDValue Arg = TailCallArgs[i].Arg;
3277 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3278 int FI = TailCallArgs[i].FrameIdx;
3279 // Store relative to framepointer.
3280 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3281 MachinePointerInfo::getFixedStack(FI),
3286 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3287 /// the appropriate stack slot for the tail call optimized function call.
3288 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3289 MachineFunction &MF,
3298 // Calculate the new stack slot for the return address.
3299 int SlotSize = isPPC64 ? 8 : 4;
3300 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3302 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3303 NewRetAddrLoc, true);
3304 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3305 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3306 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3307 MachinePointerInfo::getFixedStack(NewRetAddr),
3310 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3311 // slot as the FP is never overwritten.
3314 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3315 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3317 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3318 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3319 MachinePointerInfo::getFixedStack(NewFPIdx),
3326 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3327 /// the position of the argument.
3329 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3330 SDValue Arg, int SPDiff, unsigned ArgOffset,
3331 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3332 int Offset = ArgOffset + SPDiff;
3333 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3334 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3335 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3336 SDValue FIN = DAG.getFrameIndex(FI, VT);
3337 TailCallArgumentInfo Info;
3339 Info.FrameIdxOp = FIN;
3341 TailCallArguments.push_back(Info);
3344 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3345 /// stack slot. Returns the chain as result and the loaded frame pointers in
3346 /// LROpOut/FPOpout. Used when tail calling.
3347 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3355 // Load the LR and FP stack slot for later adjusting.
3356 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3357 LROpOut = getReturnAddrFrameIndex(DAG);
3358 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3359 false, false, false, 0);
3360 Chain = SDValue(LROpOut.getNode(), 1);
3362 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3363 // slot as the FP is never overwritten.
3365 FPOpOut = getFramePointerFrameIndex(DAG);
3366 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3367 false, false, false, 0);
3368 Chain = SDValue(FPOpOut.getNode(), 1);
3374 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3375 /// by "Src" to address "Dst" of size "Size". Alignment information is
3376 /// specified by the specific parameter attribute. The copy will be passed as
3377 /// a byval function parameter.
3378 /// Sometimes what we are copying is the end of a larger object, the part that
3379 /// does not fit in registers.
3381 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3382 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3384 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3385 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3386 false, false, MachinePointerInfo(),
3387 MachinePointerInfo());
3390 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3393 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3394 SDValue Arg, SDValue PtrOff, int SPDiff,
3395 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3396 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3397 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3399 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3404 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3406 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3407 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3408 DAG.getConstant(ArgOffset, PtrVT));
3410 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3411 MachinePointerInfo(), false, false, 0));
3412 // Calculate and remember argument location.
3413 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3418 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3419 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3420 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3421 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3422 MachineFunction &MF = DAG.getMachineFunction();
3424 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3425 // might overwrite each other in case of tail call optimization.
3426 SmallVector<SDValue, 8> MemOpChains2;
3427 // Do not flag preceding copytoreg stuff together with the following stuff.
3429 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3431 if (!MemOpChains2.empty())
3432 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3434 // Store the return address to the appropriate stack slot.
3435 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3436 isPPC64, isDarwinABI, dl);
3438 // Emit callseq_end just before tailcall node.
3439 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3440 DAG.getIntPtrConstant(0, true), InFlag, dl);
3441 InFlag = Chain.getValue(1);
3445 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3446 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3447 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3448 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3449 const PPCSubtarget &Subtarget) {
3451 bool isPPC64 = Subtarget.isPPC64();
3452 bool isSVR4ABI = Subtarget.isSVR4ABI();
3453 bool isELFv2ABI = Subtarget.isELFv2ABI();
3455 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3456 NodeTys.push_back(MVT::Other); // Returns a chain
3457 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3459 unsigned CallOpc = PPCISD::CALL;
3461 bool needIndirectCall = true;
3462 if (!isSVR4ABI || !isPPC64)
3463 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3464 // If this is an absolute destination address, use the munged value.
3465 Callee = SDValue(Dest, 0);
3466 needIndirectCall = false;
3469 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3470 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3471 // Use indirect calls for ALL functions calls in JIT mode, since the
3472 // far-call stubs may be outside relocation limits for a BL instruction.
3473 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3474 unsigned OpFlags = 0;
3475 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3476 (Subtarget.getTargetTriple().isMacOSX() &&
3477 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3478 (G->getGlobal()->isDeclaration() ||
3479 G->getGlobal()->isWeakForLinker())) ||
3480 (Subtarget.isTargetELF() && !isPPC64 &&
3481 !G->getGlobal()->hasLocalLinkage() &&
3482 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3483 // PC-relative references to external symbols should go through $stub,
3484 // unless we're building with the leopard linker or later, which
3485 // automatically synthesizes these stubs.
3486 OpFlags = PPCII::MO_PLT_OR_STUB;
3489 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3490 // every direct call is) turn it into a TargetGlobalAddress /
3491 // TargetExternalSymbol node so that legalize doesn't hack it.
3492 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3493 Callee.getValueType(),
3495 needIndirectCall = false;
3499 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3500 unsigned char OpFlags = 0;
3502 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3503 (Subtarget.getTargetTriple().isMacOSX() &&
3504 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3505 (Subtarget.isTargetELF() && !isPPC64 &&
3506 DAG.getTarget().getRelocationModel() == Reloc::PIC_) ) {
3507 // PC-relative references to external symbols should go through $stub,
3508 // unless we're building with the leopard linker or later, which
3509 // automatically synthesizes these stubs.
3510 OpFlags = PPCII::MO_PLT_OR_STUB;
3513 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3515 needIndirectCall = false;
3518 if (needIndirectCall) {
3519 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3520 // to do the call, we can't use PPCISD::CALL.
3521 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3523 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3524 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3525 // entry point, but to the function descriptor (the function entry point
3526 // address is part of the function descriptor though).
3527 // The function descriptor is a three doubleword structure with the
3528 // following fields: function entry point, TOC base address and
3529 // environment pointer.
3530 // Thus for a call through a function pointer, the following actions need
3532 // 1. Save the TOC of the caller in the TOC save area of its stack
3533 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3534 // 2. Load the address of the function entry point from the function
3536 // 3. Load the TOC of the callee from the function descriptor into r2.
3537 // 4. Load the environment pointer from the function descriptor into
3539 // 5. Branch to the function entry point address.
3540 // 6. On return of the callee, the TOC of the caller needs to be
3541 // restored (this is done in FinishCall()).
3543 // All those operations are flagged together to ensure that no other
3544 // operations can be scheduled in between. E.g. without flagging the
3545 // operations together, a TOC access in the caller could be scheduled
3546 // between the load of the callee TOC and the branch to the callee, which
3547 // results in the TOC access going through the TOC of the callee instead
3548 // of going through the TOC of the caller, which leads to incorrect code.
3550 // Load the address of the function entry point from the function
3552 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3553 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3554 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3555 Chain = LoadFuncPtr.getValue(1);
3556 InFlag = LoadFuncPtr.getValue(2);
3558 // Load environment pointer into r11.
3559 // Offset of the environment pointer within the function descriptor.
3560 SDValue PtrOff = DAG.getIntPtrConstant(16);
3562 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3563 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3565 Chain = LoadEnvPtr.getValue(1);
3566 InFlag = LoadEnvPtr.getValue(2);
3568 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3570 Chain = EnvVal.getValue(0);
3571 InFlag = EnvVal.getValue(1);
3573 // Load TOC of the callee into r2. We are using a target-specific load
3574 // with r2 hard coded, because the result of a target-independent load
3575 // would never go directly into r2, since r2 is a reserved register (which
3576 // prevents the register allocator from allocating it), resulting in an
3577 // additional register being allocated and an unnecessary move instruction
3579 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3580 SDValue TOCOff = DAG.getIntPtrConstant(8);
3581 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3582 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3584 Chain = LoadTOCPtr.getValue(0);
3585 InFlag = LoadTOCPtr.getValue(1);
3587 MTCTROps[0] = Chain;
3588 MTCTROps[1] = LoadFuncPtr;
3589 MTCTROps[2] = InFlag;
3592 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3593 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3594 InFlag = Chain.getValue(1);
3597 NodeTys.push_back(MVT::Other);
3598 NodeTys.push_back(MVT::Glue);
3599 Ops.push_back(Chain);
3600 CallOpc = PPCISD::BCTRL;
3601 Callee.setNode(nullptr);
3602 // Add use of X11 (holding environment pointer)
3603 if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3604 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3605 // Add CTR register as callee so a bctr can be emitted later.
3607 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3610 // If this is a direct call, pass the chain and the callee.
3611 if (Callee.getNode()) {
3612 Ops.push_back(Chain);
3613 Ops.push_back(Callee);
3615 // If this is a tail call add stack pointer delta.
3617 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3619 // Add argument registers to the end of the list so that they are known live
3621 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3622 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3623 RegsToPass[i].second.getValueType()));
3625 // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3626 if (Callee.getNode() && isELFv2ABI)
3627 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3633 bool isLocalCall(const SDValue &Callee)
3635 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3636 return !G->getGlobal()->isDeclaration() &&
3637 !G->getGlobal()->isWeakForLinker();
3642 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3643 CallingConv::ID CallConv, bool isVarArg,
3644 const SmallVectorImpl<ISD::InputArg> &Ins,
3645 SDLoc dl, SelectionDAG &DAG,
3646 SmallVectorImpl<SDValue> &InVals) const {
3648 SmallVector<CCValAssign, 16> RVLocs;
3649 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3650 getTargetMachine(), RVLocs, *DAG.getContext());
3651 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3653 // Copy all of the result registers out of their specified physreg.
3654 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3655 CCValAssign &VA = RVLocs[i];
3656 assert(VA.isRegLoc() && "Can only return in registers!");
3658 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3659 VA.getLocReg(), VA.getLocVT(), InFlag);
3660 Chain = Val.getValue(1);
3661 InFlag = Val.getValue(2);
3663 switch (VA.getLocInfo()) {
3664 default: llvm_unreachable("Unknown loc info!");
3665 case CCValAssign::Full: break;
3666 case CCValAssign::AExt:
3667 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3669 case CCValAssign::ZExt:
3670 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3671 DAG.getValueType(VA.getValVT()));
3672 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3674 case CCValAssign::SExt:
3675 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3676 DAG.getValueType(VA.getValVT()));
3677 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3681 InVals.push_back(Val);
3688 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3689 bool isTailCall, bool isVarArg,
3691 SmallVector<std::pair<unsigned, SDValue>, 8>
3693 SDValue InFlag, SDValue Chain,
3695 int SPDiff, unsigned NumBytes,
3696 const SmallVectorImpl<ISD::InputArg> &Ins,
3697 SmallVectorImpl<SDValue> &InVals) const {
3699 bool isELFv2ABI = Subtarget.isELFv2ABI();
3700 std::vector<EVT> NodeTys;
3701 SmallVector<SDValue, 8> Ops;
3702 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3703 isTailCall, RegsToPass, Ops, NodeTys,
3706 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3707 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3708 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3710 // When performing tail call optimization the callee pops its arguments off
3711 // the stack. Account for this here so these bytes can be pushed back on in
3712 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3713 int BytesCalleePops =
3714 (CallConv == CallingConv::Fast &&
3715 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3717 // Add a register mask operand representing the call-preserved registers.
3718 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3719 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3720 assert(Mask && "Missing call preserved mask for calling convention");
3721 Ops.push_back(DAG.getRegisterMask(Mask));
3723 if (InFlag.getNode())
3724 Ops.push_back(InFlag);
3728 assert(((Callee.getOpcode() == ISD::Register &&
3729 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3730 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3731 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3732 isa<ConstantSDNode>(Callee)) &&
3733 "Expecting an global address, external symbol, absolute value or register");
3735 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3738 // Add a NOP immediately after the branch instruction when using the 64-bit
3739 // SVR4 ABI. At link time, if caller and callee are in a different module and
3740 // thus have a different TOC, the call will be replaced with a call to a stub
3741 // function which saves the current TOC, loads the TOC of the callee and
3742 // branches to the callee. The NOP will be replaced with a load instruction
3743 // which restores the TOC of the caller from the TOC save slot of the current
3744 // stack frame. If caller and callee belong to the same module (and have the
3745 // same TOC), the NOP will remain unchanged.
3747 bool needsTOCRestore = false;
3748 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3749 if (CallOpc == PPCISD::BCTRL) {
3750 // This is a call through a function pointer.
3751 // Restore the caller TOC from the save area into R2.
3752 // See PrepareCall() for more information about calls through function
3753 // pointers in the 64-bit SVR4 ABI.
3754 // We are using a target-specific load with r2 hard coded, because the
3755 // result of a target-independent load would never go directly into r2,
3756 // since r2 is a reserved register (which prevents the register allocator
3757 // from allocating it), resulting in an additional register being
3758 // allocated and an unnecessary move instruction being generated.
3759 needsTOCRestore = true;
3760 } else if ((CallOpc == PPCISD::CALL) &&
3761 (!isLocalCall(Callee) ||
3762 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3763 // Otherwise insert NOP for non-local calls.
3764 CallOpc = PPCISD::CALL_NOP;
3768 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3769 InFlag = Chain.getValue(1);
3771 if (needsTOCRestore) {
3772 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3773 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3774 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3775 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3776 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3777 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3778 Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
3779 InFlag = Chain.getValue(1);
3782 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3783 DAG.getIntPtrConstant(BytesCalleePops, true),
3786 InFlag = Chain.getValue(1);
3788 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3789 Ins, dl, DAG, InVals);
3793 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3794 SmallVectorImpl<SDValue> &InVals) const {
3795 SelectionDAG &DAG = CLI.DAG;
3797 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3798 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3799 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3800 SDValue Chain = CLI.Chain;
3801 SDValue Callee = CLI.Callee;
3802 bool &isTailCall = CLI.IsTailCall;
3803 CallingConv::ID CallConv = CLI.CallConv;
3804 bool isVarArg = CLI.IsVarArg;
3807 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3810 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3811 report_fatal_error("failed to perform tail call elimination on a call "
3812 "site marked musttail");
3814 if (Subtarget.isSVR4ABI()) {
3815 if (Subtarget.isPPC64())
3816 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3817 isTailCall, Outs, OutVals, Ins,
3820 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3821 isTailCall, Outs, OutVals, Ins,
3825 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3826 isTailCall, Outs, OutVals, Ins,
3831 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3832 CallingConv::ID CallConv, bool isVarArg,
3834 const SmallVectorImpl<ISD::OutputArg> &Outs,
3835 const SmallVectorImpl<SDValue> &OutVals,
3836 const SmallVectorImpl<ISD::InputArg> &Ins,
3837 SDLoc dl, SelectionDAG &DAG,
3838 SmallVectorImpl<SDValue> &InVals) const {
3839 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3840 // of the 32-bit SVR4 ABI stack frame layout.
3842 assert((CallConv == CallingConv::C ||
3843 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3845 unsigned PtrByteSize = 4;
3847 MachineFunction &MF = DAG.getMachineFunction();
3849 // Mark this function as potentially containing a function that contains a
3850 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3851 // and restoring the callers stack pointer in this functions epilog. This is
3852 // done because by tail calling the called function might overwrite the value
3853 // in this function's (MF) stack pointer stack slot 0(SP).
3854 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3855 CallConv == CallingConv::Fast)
3856 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3858 // Count how many bytes are to be pushed on the stack, including the linkage
3859 // area, parameter list area and the part of the local variable space which
3860 // contains copies of aggregates which are passed by value.
3862 // Assign locations to all of the outgoing arguments.
3863 SmallVector<CCValAssign, 16> ArgLocs;
3864 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3865 getTargetMachine(), ArgLocs, *DAG.getContext());
3867 // Reserve space for the linkage area on the stack.
3868 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
3872 // Handle fixed and variable vector arguments differently.
3873 // Fixed vector arguments go into registers as long as registers are
3874 // available. Variable vector arguments always go into memory.
3875 unsigned NumArgs = Outs.size();
3877 for (unsigned i = 0; i != NumArgs; ++i) {
3878 MVT ArgVT = Outs[i].VT;
3879 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3882 if (Outs[i].IsFixed) {
3883 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3886 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3892 errs() << "Call operand #" << i << " has unhandled type "
3893 << EVT(ArgVT).getEVTString() << "\n";
3895 llvm_unreachable(nullptr);
3899 // All arguments are treated the same.
3900 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3903 // Assign locations to all of the outgoing aggregate by value arguments.
3904 SmallVector<CCValAssign, 16> ByValArgLocs;
3905 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3906 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3908 // Reserve stack space for the allocations in CCInfo.
3909 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3911 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3913 // Size of the linkage area, parameter list area and the part of the local
3914 // space variable where copies of aggregates which are passed by value are
3916 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3918 // Calculate by how many bytes the stack has to be adjusted in case of tail
3919 // call optimization.
3920 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3922 // Adjust the stack pointer for the new arguments...
3923 // These operations are automatically eliminated by the prolog/epilog pass
3924 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3926 SDValue CallSeqStart = Chain;
3928 // Load the return address and frame pointer so it can be moved somewhere else
3931 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3934 // Set up a copy of the stack pointer for use loading and storing any
3935 // arguments that may not fit in the registers available for argument
3937 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3939 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3940 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3941 SmallVector<SDValue, 8> MemOpChains;
3943 bool seenFloatArg = false;
3944 // Walk the register/memloc assignments, inserting copies/loads.
3945 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3948 CCValAssign &VA = ArgLocs[i];
3949 SDValue Arg = OutVals[i];
3950 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3952 if (Flags.isByVal()) {
3953 // Argument is an aggregate which is passed by value, thus we need to
3954 // create a copy of it in the local variable space of the current stack
3955 // frame (which is the stack frame of the caller) and pass the address of
3956 // this copy to the callee.
3957 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3958 CCValAssign &ByValVA = ByValArgLocs[j++];
3959 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3961 // Memory reserved in the local variable space of the callers stack frame.
3962 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3964 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3965 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3967 // Create a copy of the argument in the local area of the current
3969 SDValue MemcpyCall =
3970 CreateCopyOfByValArgument(Arg, PtrOff,
3971 CallSeqStart.getNode()->getOperand(0),
3974 // This must go outside the CALLSEQ_START..END.
3975 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3976 CallSeqStart.getNode()->getOperand(1),
3978 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3979 NewCallSeqStart.getNode());
3980 Chain = CallSeqStart = NewCallSeqStart;
3982 // Pass the address of the aggregate copy on the stack either in a
3983 // physical register or in the parameter list area of the current stack
3984 // frame to the callee.
3988 if (VA.isRegLoc()) {
3989 if (Arg.getValueType() == MVT::i1)
3990 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3992 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3993 // Put argument in a physical register.
3994 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3996 // Put argument in the parameter list area of the current stack frame.
3997 assert(VA.isMemLoc());
3998 unsigned LocMemOffset = VA.getLocMemOffset();
4001 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4002 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4004 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4005 MachinePointerInfo(),
4008 // Calculate and remember argument location.
4009 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4015 if (!MemOpChains.empty())
4016 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4018 // Build a sequence of copy-to-reg nodes chained together with token chain
4019 // and flag operands which copy the outgoing args into the appropriate regs.
4021 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4022 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4023 RegsToPass[i].second, InFlag);
4024 InFlag = Chain.getValue(1);
4027 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4030 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4031 SDValue Ops[] = { Chain, InFlag };
4033 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4034 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4036 InFlag = Chain.getValue(1);
4040 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4041 false, TailCallArguments);
4043 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4044 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4048 // Copy an argument into memory, being careful to do this outside the
4049 // call sequence for the call to which the argument belongs.
4051 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4052 SDValue CallSeqStart,
4053 ISD::ArgFlagsTy Flags,
4056 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4057 CallSeqStart.getNode()->getOperand(0),
4059 // The MEMCPY must go outside the CALLSEQ_START..END.
4060 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4061 CallSeqStart.getNode()->getOperand(1),
4063 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4064 NewCallSeqStart.getNode());
4065 return NewCallSeqStart;
4069 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4070 CallingConv::ID CallConv, bool isVarArg,
4072 const SmallVectorImpl<ISD::OutputArg> &Outs,
4073 const SmallVectorImpl<SDValue> &OutVals,
4074 const SmallVectorImpl<ISD::InputArg> &Ins,
4075 SDLoc dl, SelectionDAG &DAG,
4076 SmallVectorImpl<SDValue> &InVals) const {
4078 bool isELFv2ABI = Subtarget.isELFv2ABI();
4079 bool isLittleEndian = Subtarget.isLittleEndian();
4080 unsigned NumOps = Outs.size();
4082 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4083 unsigned PtrByteSize = 8;
4085 MachineFunction &MF = DAG.getMachineFunction();
4087 // Mark this function as potentially containing a function that contains a
4088 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4089 // and restoring the callers stack pointer in this functions epilog. This is
4090 // done because by tail calling the called function might overwrite the value
4091 // in this function's (MF) stack pointer stack slot 0(SP).
4092 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4093 CallConv == CallingConv::Fast)
4094 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4096 // Count how many bytes are to be pushed on the stack, including the linkage
4097 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4098 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4099 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4100 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4102 unsigned NumBytes = LinkageSize;
4104 // Add up all the space actually used.
4105 for (unsigned i = 0; i != NumOps; ++i) {
4106 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4107 EVT ArgVT = Outs[i].VT;
4109 /* Respect alignment of argument on the stack. */
4110 unsigned Align = CalculateStackSlotAlignment(ArgVT, Flags, PtrByteSize);
4111 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4113 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4116 unsigned NumBytesActuallyUsed = NumBytes;
4118 // The prolog code of the callee may store up to 8 GPR argument registers to
4119 // the stack, allowing va_start to index over them in memory if its varargs.
4120 // Because we cannot tell if this is needed on the caller side, we have to
4121 // conservatively assume that it is needed. As such, make sure we have at
4122 // least enough stack space for the caller to store the 8 GPRs.
4123 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4124 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4126 // Tail call needs the stack to be aligned.
4127 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4128 CallConv == CallingConv::Fast)
4129 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4131 // Calculate by how many bytes the stack has to be adjusted in case of tail
4132 // call optimization.
4133 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4135 // To protect arguments on the stack from being clobbered in a tail call,
4136 // force all the loads to happen before doing any other lowering.
4138 Chain = DAG.getStackArgumentTokenFactor(Chain);
4140 // Adjust the stack pointer for the new arguments...
4141 // These operations are automatically eliminated by the prolog/epilog pass
4142 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4144 SDValue CallSeqStart = Chain;
4146 // Load the return address and frame pointer so it can be move somewhere else
4149 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4152 // Set up a copy of the stack pointer for use loading and storing any
4153 // arguments that may not fit in the registers available for argument
4155 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4157 // Figure out which arguments are going to go in registers, and which in
4158 // memory. Also, if this is a vararg function, floating point operations
4159 // must be stored to our stack, and loaded into integer regs as well, if
4160 // any integer regs are available for argument passing.
4161 unsigned ArgOffset = LinkageSize;
4162 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4164 static const MCPhysReg GPR[] = {
4165 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4166 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4168 static const MCPhysReg *FPR = GetFPR();
4170 static const MCPhysReg VR[] = {
4171 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4172 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4174 static const MCPhysReg VSRH[] = {
4175 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4176 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4179 const unsigned NumGPRs = array_lengthof(GPR);
4180 const unsigned NumFPRs = 13;
4181 const unsigned NumVRs = array_lengthof(VR);
4183 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4184 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4186 SmallVector<SDValue, 8> MemOpChains;
4187 for (unsigned i = 0; i != NumOps; ++i) {
4188 SDValue Arg = OutVals[i];
4189 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4191 /* Respect alignment of argument on the stack. */
4193 CalculateStackSlotAlignment(Outs[i].VT, Flags, PtrByteSize);
4194 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4196 /* Compute GPR index associated with argument offset. */
4197 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4198 GPR_idx = std::min(GPR_idx, NumGPRs);
4200 // PtrOff will be used to store the current argument to the stack if a
4201 // register cannot be found for it.
4204 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4206 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4208 // Promote integers to 64-bit values.
4209 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4210 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4211 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4212 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4215 // FIXME memcpy is used way more than necessary. Correctness first.
4216 // Note: "by value" is code for passing a structure by value, not
4218 if (Flags.isByVal()) {
4219 // Note: Size includes alignment padding, so
4220 // struct x { short a; char b; }
4221 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4222 // These are the proper values we need for right-justifying the
4223 // aggregate in a parameter register.
4224 unsigned Size = Flags.getByValSize();
4226 // An empty aggregate parameter takes up no storage and no
4231 // All aggregates smaller than 8 bytes must be passed right-justified.
4232 if (Size==1 || Size==2 || Size==4) {
4233 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4234 if (GPR_idx != NumGPRs) {
4235 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4236 MachinePointerInfo(), VT,
4238 MemOpChains.push_back(Load.getValue(1));
4239 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4241 ArgOffset += PtrByteSize;
4246 if (GPR_idx == NumGPRs && Size < 8) {
4247 SDValue AddPtr = PtrOff;
4248 if (!isLittleEndian) {
4249 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4250 PtrOff.getValueType());
4251 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4253 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4256 ArgOffset += PtrByteSize;
4259 // Copy entire object into memory. There are cases where gcc-generated
4260 // code assumes it is there, even if it could be put entirely into
4261 // registers. (This is not what the doc says.)
4263 // FIXME: The above statement is likely due to a misunderstanding of the
4264 // documents. All arguments must be copied into the parameter area BY
4265 // THE CALLEE in the event that the callee takes the address of any
4266 // formal argument. That has not yet been implemented. However, it is
4267 // reasonable to use the stack area as a staging area for the register
4270 // Skip this for small aggregates, as we will use the same slot for a
4271 // right-justified copy, below.
4273 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4277 // When a register is available, pass a small aggregate right-justified.
4278 if (Size < 8 && GPR_idx != NumGPRs) {
4279 // The easiest way to get this right-justified in a register
4280 // is to copy the structure into the rightmost portion of a
4281 // local variable slot, then load the whole slot into the
4283 // FIXME: The memcpy seems to produce pretty awful code for
4284 // small aggregates, particularly for packed ones.
4285 // FIXME: It would be preferable to use the slot in the
4286 // parameter save area instead of a new local variable.
4287 SDValue AddPtr = PtrOff;
4288 if (!isLittleEndian) {
4289 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4290 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4292 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4296 // Load the slot into the register.
4297 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4298 MachinePointerInfo(),
4299 false, false, false, 0);
4300 MemOpChains.push_back(Load.getValue(1));
4301 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4303 // Done with this argument.
4304 ArgOffset += PtrByteSize;
4308 // For aggregates larger than PtrByteSize, copy the pieces of the
4309 // object that fit into registers from the parameter save area.
4310 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4311 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4312 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4313 if (GPR_idx != NumGPRs) {
4314 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4315 MachinePointerInfo(),
4316 false, false, false, 0);
4317 MemOpChains.push_back(Load.getValue(1));
4318 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4319 ArgOffset += PtrByteSize;
4321 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4328 switch (Arg.getSimpleValueType().SimpleTy) {
4329 default: llvm_unreachable("Unexpected ValueType for argument!");
4333 if (GPR_idx != NumGPRs) {
4334 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4336 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4337 true, isTailCall, false, MemOpChains,
4338 TailCallArguments, dl);
4340 ArgOffset += PtrByteSize;
4344 if (FPR_idx != NumFPRs) {
4345 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4348 // A single float or an aggregate containing only a single float
4349 // must be passed right-justified in the stack doubleword, and
4350 // in the GPR, if one is available.
4352 if (Arg.getSimpleValueType().SimpleTy == MVT::f32 &&
4354 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4355 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4359 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4360 MachinePointerInfo(), false, false, 0);
4361 MemOpChains.push_back(Store);
4363 // Float varargs are always shadowed in available integer registers
4364 if (GPR_idx != NumGPRs) {
4365 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4366 MachinePointerInfo(), false, false,
4368 MemOpChains.push_back(Load.getValue(1));
4369 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4373 // Single-precision floating-point values are mapped to the
4374 // second (rightmost) word of the stack doubleword.
4375 if (Arg.getValueType() == MVT::f32 && !isLittleEndian) {
4376 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4377 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4380 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4381 true, isTailCall, false, MemOpChains,
4382 TailCallArguments, dl);
4392 // For a varargs call, named arguments go into VRs or on the stack as
4393 // usual; unnamed arguments always go to the stack or the corresponding
4394 // GPRs when within range. For now, we always put the value in both
4395 // locations (or even all three).
4397 // We could elide this store in the case where the object fits
4398 // entirely in R registers. Maybe later.
4399 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4400 MachinePointerInfo(), false, false, 0);
4401 MemOpChains.push_back(Store);
4402 if (VR_idx != NumVRs) {
4403 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4404 MachinePointerInfo(),
4405 false, false, false, 0);
4406 MemOpChains.push_back(Load.getValue(1));
4408 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4409 Arg.getSimpleValueType() == MVT::v2i64) ?
4410 VSRH[VR_idx] : VR[VR_idx];
4413 RegsToPass.push_back(std::make_pair(VReg, Load));
4416 for (unsigned i=0; i<16; i+=PtrByteSize) {
4417 if (GPR_idx == NumGPRs)
4419 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4420 DAG.getConstant(i, PtrVT));
4421 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4422 false, false, false, 0);
4423 MemOpChains.push_back(Load.getValue(1));
4424 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4429 // Non-varargs Altivec params go into VRs or on the stack.
4430 if (VR_idx != NumVRs) {
4431 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4432 Arg.getSimpleValueType() == MVT::v2i64) ?
4433 VSRH[VR_idx] : VR[VR_idx];
4436 RegsToPass.push_back(std::make_pair(VReg, Arg));
4438 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4439 true, isTailCall, true, MemOpChains,
4440 TailCallArguments, dl);
4447 assert(NumBytesActuallyUsed == ArgOffset);
4448 (void)NumBytesActuallyUsed;
4450 if (!MemOpChains.empty())
4451 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4453 // Check if this is an indirect call (MTCTR/BCTRL).
4454 // See PrepareCall() for more information about calls through function
4455 // pointers in the 64-bit SVR4 ABI.
4457 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4458 !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4459 // Load r2 into a virtual register and store it to the TOC save area.
4460 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4461 // TOC save area offset.
4462 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4463 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4464 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4465 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4467 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4468 // This does not mean the MTCTR instruction must use R12; it's easier
4469 // to model this as an extra parameter, so do that.
4471 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4474 // Build a sequence of copy-to-reg nodes chained together with token chain
4475 // and flag operands which copy the outgoing args into the appropriate regs.
4477 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4478 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4479 RegsToPass[i].second, InFlag);
4480 InFlag = Chain.getValue(1);
4484 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4485 FPOp, true, TailCallArguments);
4487 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4488 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4493 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4494 CallingConv::ID CallConv, bool isVarArg,
4496 const SmallVectorImpl<ISD::OutputArg> &Outs,
4497 const SmallVectorImpl<SDValue> &OutVals,
4498 const SmallVectorImpl<ISD::InputArg> &Ins,
4499 SDLoc dl, SelectionDAG &DAG,
4500 SmallVectorImpl<SDValue> &InVals) const {
4502 unsigned NumOps = Outs.size();
4504 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4505 bool isPPC64 = PtrVT == MVT::i64;
4506 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4508 MachineFunction &MF = DAG.getMachineFunction();
4510 // Mark this function as potentially containing a function that contains a
4511 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4512 // and restoring the callers stack pointer in this functions epilog. This is
4513 // done because by tail calling the called function might overwrite the value
4514 // in this function's (MF) stack pointer stack slot 0(SP).
4515 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4516 CallConv == CallingConv::Fast)
4517 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4519 // Count how many bytes are to be pushed on the stack, including the linkage
4520 // area, and parameter passing area. We start with 24/48 bytes, which is
4521 // prereserved space for [SP][CR][LR][3 x unused].
4522 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4524 unsigned NumBytes = LinkageSize;
4526 // Add up all the space actually used.
4527 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4528 // they all go in registers, but we must reserve stack space for them for
4529 // possible use by the caller. In varargs or 64-bit calls, parameters are
4530 // assigned stack space in order, with padding so Altivec parameters are
4532 unsigned nAltivecParamsAtEnd = 0;
4533 for (unsigned i = 0; i != NumOps; ++i) {
4534 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4535 EVT ArgVT = Outs[i].VT;
4536 // Varargs Altivec parameters are padded to a 16 byte boundary.
4537 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4538 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4539 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4540 if (!isVarArg && !isPPC64) {
4541 // Non-varargs Altivec parameters go after all the non-Altivec
4542 // parameters; handle those later so we know how much padding we need.
4543 nAltivecParamsAtEnd++;
4546 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4547 NumBytes = ((NumBytes+15)/16)*16;
4549 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4552 // Allow for Altivec parameters at the end, if needed.
4553 if (nAltivecParamsAtEnd) {
4554 NumBytes = ((NumBytes+15)/16)*16;
4555 NumBytes += 16*nAltivecParamsAtEnd;
4558 // The prolog code of the callee may store up to 8 GPR argument registers to
4559 // the stack, allowing va_start to index over them in memory if its varargs.
4560 // Because we cannot tell if this is needed on the caller side, we have to
4561 // conservatively assume that it is needed. As such, make sure we have at
4562 // least enough stack space for the caller to store the 8 GPRs.
4563 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4565 // Tail call needs the stack to be aligned.
4566 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4567 CallConv == CallingConv::Fast)
4568 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4570 // Calculate by how many bytes the stack has to be adjusted in case of tail
4571 // call optimization.
4572 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4574 // To protect arguments on the stack from being clobbered in a tail call,
4575 // force all the loads to happen before doing any other lowering.
4577 Chain = DAG.getStackArgumentTokenFactor(Chain);
4579 // Adjust the stack pointer for the new arguments...
4580 // These operations are automatically eliminated by the prolog/epilog pass
4581 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4583 SDValue CallSeqStart = Chain;
4585 // Load the return address and frame pointer so it can be move somewhere else
4588 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4591 // Set up a copy of the stack pointer for use loading and storing any
4592 // arguments that may not fit in the registers available for argument
4596 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4598 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4600 // Figure out which arguments are going to go in registers, and which in
4601 // memory. Also, if this is a vararg function, floating point operations
4602 // must be stored to our stack, and loaded into integer regs as well, if
4603 // any integer regs are available for argument passing.
4604 unsigned ArgOffset = LinkageSize;
4605 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4607 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4608 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4609 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4611 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4612 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4613 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4615 static const MCPhysReg *FPR = GetFPR();
4617 static const MCPhysReg VR[] = {
4618 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4619 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4621 const unsigned NumGPRs = array_lengthof(GPR_32);
4622 const unsigned NumFPRs = 13;
4623 const unsigned NumVRs = array_lengthof(VR);
4625 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4627 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4628 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4630 SmallVector<SDValue, 8> MemOpChains;
4631 for (unsigned i = 0; i != NumOps; ++i) {
4632 SDValue Arg = OutVals[i];
4633 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4635 // PtrOff will be used to store the current argument to the stack if a
4636 // register cannot be found for it.
4639 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4641 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4643 // On PPC64, promote integers to 64-bit values.
4644 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4645 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4646 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4647 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4650 // FIXME memcpy is used way more than necessary. Correctness first.
4651 // Note: "by value" is code for passing a structure by value, not
4653 if (Flags.isByVal()) {
4654 unsigned Size = Flags.getByValSize();
4655 // Very small objects are passed right-justified. Everything else is
4656 // passed left-justified.
4657 if (Size==1 || Size==2) {
4658 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4659 if (GPR_idx != NumGPRs) {
4660 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4661 MachinePointerInfo(), VT,
4663 MemOpChains.push_back(Load.getValue(1));
4664 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4666 ArgOffset += PtrByteSize;
4668 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4669 PtrOff.getValueType());
4670 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4671 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4674 ArgOffset += PtrByteSize;
4678 // Copy entire object into memory. There are cases where gcc-generated
4679 // code assumes it is there, even if it could be put entirely into
4680 // registers. (This is not what the doc says.)
4681 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4685 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4686 // copy the pieces of the object that fit into registers from the
4687 // parameter save area.
4688 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4689 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4690 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4691 if (GPR_idx != NumGPRs) {
4692 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4693 MachinePointerInfo(),
4694 false, false, false, 0);
4695 MemOpChains.push_back(Load.getValue(1));
4696 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4697 ArgOffset += PtrByteSize;
4699 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4706 switch (Arg.getSimpleValueType().SimpleTy) {
4707 default: llvm_unreachable("Unexpected ValueType for argument!");
4711 if (GPR_idx != NumGPRs) {
4712 if (Arg.getValueType() == MVT::i1)
4713 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4715 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4717 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4718 isPPC64, isTailCall, false, MemOpChains,
4719 TailCallArguments, dl);
4721 ArgOffset += PtrByteSize;
4725 if (FPR_idx != NumFPRs) {
4726 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4729 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4730 MachinePointerInfo(), false, false, 0);
4731 MemOpChains.push_back(Store);
4733 // Float varargs are always shadowed in available integer registers
4734 if (GPR_idx != NumGPRs) {
4735 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4736 MachinePointerInfo(), false, false,
4738 MemOpChains.push_back(Load.getValue(1));
4739 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4741 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4742 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4743 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4744 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4745 MachinePointerInfo(),
4746 false, false, false, 0);
4747 MemOpChains.push_back(Load.getValue(1));
4748 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4751 // If we have any FPRs remaining, we may also have GPRs remaining.
4752 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4754 if (GPR_idx != NumGPRs)
4756 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4757 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4761 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4762 isPPC64, isTailCall, false, MemOpChains,
4763 TailCallArguments, dl);
4767 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4774 // These go aligned on the stack, or in the corresponding R registers
4775 // when within range. The Darwin PPC ABI doc claims they also go in
4776 // V registers; in fact gcc does this only for arguments that are
4777 // prototyped, not for those that match the ... We do it for all
4778 // arguments, seems to work.
4779 while (ArgOffset % 16 !=0) {
4780 ArgOffset += PtrByteSize;
4781 if (GPR_idx != NumGPRs)
4784 // We could elide this store in the case where the object fits
4785 // entirely in R registers. Maybe later.
4786 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4787 DAG.getConstant(ArgOffset, PtrVT));
4788 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4789 MachinePointerInfo(), false, false, 0);
4790 MemOpChains.push_back(Store);
4791 if (VR_idx != NumVRs) {
4792 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4793 MachinePointerInfo(),
4794 false, false, false, 0);
4795 MemOpChains.push_back(Load.getValue(1));
4796 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4799 for (unsigned i=0; i<16; i+=PtrByteSize) {
4800 if (GPR_idx == NumGPRs)
4802 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4803 DAG.getConstant(i, PtrVT));
4804 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4805 false, false, false, 0);
4806 MemOpChains.push_back(Load.getValue(1));
4807 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4812 // Non-varargs Altivec params generally go in registers, but have
4813 // stack space allocated at the end.
4814 if (VR_idx != NumVRs) {
4815 // Doesn't have GPR space allocated.
4816 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4817 } else if (nAltivecParamsAtEnd==0) {
4818 // We are emitting Altivec params in order.
4819 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4820 isPPC64, isTailCall, true, MemOpChains,
4821 TailCallArguments, dl);
4827 // If all Altivec parameters fit in registers, as they usually do,
4828 // they get stack space following the non-Altivec parameters. We
4829 // don't track this here because nobody below needs it.
4830 // If there are more Altivec parameters than fit in registers emit
4832 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4834 // Offset is aligned; skip 1st 12 params which go in V registers.
4835 ArgOffset = ((ArgOffset+15)/16)*16;
4837 for (unsigned i = 0; i != NumOps; ++i) {
4838 SDValue Arg = OutVals[i];
4839 EVT ArgType = Outs[i].VT;
4840 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4841 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4844 // We are emitting Altivec params in order.
4845 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4846 isPPC64, isTailCall, true, MemOpChains,
4847 TailCallArguments, dl);
4854 if (!MemOpChains.empty())
4855 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4857 // On Darwin, R12 must contain the address of an indirect callee. This does
4858 // not mean the MTCTR instruction must use R12; it's easier to model this as
4859 // an extra parameter, so do that.
4861 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4862 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4863 !isBLACompatibleAddress(Callee, DAG))
4864 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4865 PPC::R12), Callee));
4867 // Build a sequence of copy-to-reg nodes chained together with token chain
4868 // and flag operands which copy the outgoing args into the appropriate regs.
4870 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4871 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4872 RegsToPass[i].second, InFlag);
4873 InFlag = Chain.getValue(1);
4877 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4878 FPOp, true, TailCallArguments);
4880 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4881 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4886 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4887 MachineFunction &MF, bool isVarArg,
4888 const SmallVectorImpl<ISD::OutputArg> &Outs,
4889 LLVMContext &Context) const {
4890 SmallVector<CCValAssign, 16> RVLocs;
4891 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4893 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4897 PPCTargetLowering::LowerReturn(SDValue Chain,
4898 CallingConv::ID CallConv, bool isVarArg,
4899 const SmallVectorImpl<ISD::OutputArg> &Outs,
4900 const SmallVectorImpl<SDValue> &OutVals,
4901 SDLoc dl, SelectionDAG &DAG) const {
4903 SmallVector<CCValAssign, 16> RVLocs;
4904 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4905 getTargetMachine(), RVLocs, *DAG.getContext());
4906 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4909 SmallVector<SDValue, 4> RetOps(1, Chain);
4911 // Copy the result values into the output registers.
4912 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4913 CCValAssign &VA = RVLocs[i];
4914 assert(VA.isRegLoc() && "Can only return in registers!");
4916 SDValue Arg = OutVals[i];
4918 switch (VA.getLocInfo()) {
4919 default: llvm_unreachable("Unknown loc info!");
4920 case CCValAssign::Full: break;
4921 case CCValAssign::AExt:
4922 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4924 case CCValAssign::ZExt:
4925 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4927 case CCValAssign::SExt:
4928 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4932 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4933 Flag = Chain.getValue(1);
4934 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4937 RetOps[0] = Chain; // Update chain.
4939 // Add the flag if we have it.
4941 RetOps.push_back(Flag);
4943 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
4946 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4947 const PPCSubtarget &Subtarget) const {
4948 // When we pop the dynamic allocation we need to restore the SP link.
4951 // Get the corect type for pointers.
4952 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4954 // Construct the stack pointer operand.
4955 bool isPPC64 = Subtarget.isPPC64();
4956 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4957 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4959 // Get the operands for the STACKRESTORE.
4960 SDValue Chain = Op.getOperand(0);
4961 SDValue SaveSP = Op.getOperand(1);
4963 // Load the old link SP.
4964 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4965 MachinePointerInfo(),
4966 false, false, false, 0);
4968 // Restore the stack pointer.
4969 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4971 // Store the old link SP.
4972 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4979 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4980 MachineFunction &MF = DAG.getMachineFunction();
4981 bool isPPC64 = Subtarget.isPPC64();
4982 bool isDarwinABI = Subtarget.isDarwinABI();
4983 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4985 // Get current frame pointer save index. The users of this index will be
4986 // primarily DYNALLOC instructions.
4987 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4988 int RASI = FI->getReturnAddrSaveIndex();
4990 // If the frame pointer save index hasn't been defined yet.
4992 // Find out what the fix offset of the frame pointer save area.
4993 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4994 // Allocate the frame index for frame pointer save area.
4995 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4997 FI->setReturnAddrSaveIndex(RASI);
4999 return DAG.getFrameIndex(RASI, PtrVT);
5003 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5004 MachineFunction &MF = DAG.getMachineFunction();
5005 bool isPPC64 = Subtarget.isPPC64();
5006 bool isDarwinABI = Subtarget.isDarwinABI();
5007 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5009 // Get current frame pointer save index. The users of this index will be
5010 // primarily DYNALLOC instructions.
5011 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5012 int FPSI = FI->getFramePointerSaveIndex();
5014 // If the frame pointer save index hasn't been defined yet.
5016 // Find out what the fix offset of the frame pointer save area.
5017 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5020 // Allocate the frame index for frame pointer save area.
5021 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5023 FI->setFramePointerSaveIndex(FPSI);
5025 return DAG.getFrameIndex(FPSI, PtrVT);
5028 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5030 const PPCSubtarget &Subtarget) const {
5032 SDValue Chain = Op.getOperand(0);
5033 SDValue Size = Op.getOperand(1);
5036 // Get the corect type for pointers.
5037 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5039 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5040 DAG.getConstant(0, PtrVT), Size);
5041 // Construct a node for the frame pointer save index.
5042 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5043 // Build a DYNALLOC node.
5044 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5045 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5046 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5049 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5050 SelectionDAG &DAG) const {
5052 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5053 DAG.getVTList(MVT::i32, MVT::Other),
5054 Op.getOperand(0), Op.getOperand(1));
5057 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5058 SelectionDAG &DAG) const {
5060 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5061 Op.getOperand(0), Op.getOperand(1));
5064 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5065 assert(Op.getValueType() == MVT::i1 &&
5066 "Custom lowering only for i1 loads");
5068 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5071 LoadSDNode *LD = cast<LoadSDNode>(Op);
5073 SDValue Chain = LD->getChain();
5074 SDValue BasePtr = LD->getBasePtr();
5075 MachineMemOperand *MMO = LD->getMemOperand();
5077 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5078 BasePtr, MVT::i8, MMO);
5079 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5081 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5082 return DAG.getMergeValues(Ops, dl);
5085 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5086 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5087 "Custom lowering only for i1 stores");
5089 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5092 StoreSDNode *ST = cast<StoreSDNode>(Op);
5094 SDValue Chain = ST->getChain();
5095 SDValue BasePtr = ST->getBasePtr();
5096 SDValue Value = ST->getValue();
5097 MachineMemOperand *MMO = ST->getMemOperand();
5099 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5100 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5103 // FIXME: Remove this once the ANDI glue bug is fixed:
5104 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5105 assert(Op.getValueType() == MVT::i1 &&
5106 "Custom lowering only for i1 results");
5109 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5113 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5115 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5116 // Not FP? Not a fsel.
5117 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5118 !Op.getOperand(2).getValueType().isFloatingPoint())
5121 // We might be able to do better than this under some circumstances, but in
5122 // general, fsel-based lowering of select is a finite-math-only optimization.
5123 // For more information, see section F.3 of the 2.06 ISA specification.
5124 if (!DAG.getTarget().Options.NoInfsFPMath ||
5125 !DAG.getTarget().Options.NoNaNsFPMath)
5128 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5130 EVT ResVT = Op.getValueType();
5131 EVT CmpVT = Op.getOperand(0).getValueType();
5132 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5133 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5136 // If the RHS of the comparison is a 0.0, we don't need to do the
5137 // subtraction at all.
5139 if (isFloatingPointZero(RHS))
5141 default: break; // SETUO etc aren't handled by fsel.
5145 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5146 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5147 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5148 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5149 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5150 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5151 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5154 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5157 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5158 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5159 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5162 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5165 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5166 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5167 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5168 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5173 default: break; // SETUO etc aren't handled by fsel.
5177 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5178 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5179 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5180 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5181 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5182 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5183 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5184 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5187 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5188 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5189 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5190 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5193 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5194 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5195 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5196 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5199 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5200 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5201 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5202 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5205 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5206 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5207 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5208 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5213 // FIXME: Split this code up when LegalizeDAGTypes lands.
5214 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5216 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5217 SDValue Src = Op.getOperand(0);
5218 if (Src.getValueType() == MVT::f32)
5219 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5222 switch (Op.getSimpleValueType().SimpleTy) {
5223 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5225 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5226 (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5231 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5232 "i64 FP_TO_UINT is supported only with FPCVT");
5233 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5239 // Convert the FP value to an int value through memory.
5240 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5241 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5242 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5243 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5244 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5246 // Emit a store to the stack slot.
5249 MachineFunction &MF = DAG.getMachineFunction();
5250 MachineMemOperand *MMO =
5251 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5252 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5253 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5254 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5256 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5257 MPI, false, false, 0);
5259 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5261 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5262 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5263 DAG.getConstant(4, FIPtr.getValueType()));
5264 MPI = MachinePointerInfo();
5267 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5268 false, false, false, 0);
5271 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5272 SelectionDAG &DAG) const {
5274 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5275 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5278 if (Op.getOperand(0).getValueType() == MVT::i1)
5279 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5280 DAG.getConstantFP(1.0, Op.getValueType()),
5281 DAG.getConstantFP(0.0, Op.getValueType()));
5283 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5284 "UINT_TO_FP is supported only with FPCVT");
5286 // If we have FCFIDS, then use it when converting to single-precision.
5287 // Otherwise, convert to double-precision and then round.
5288 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5289 (Op.getOpcode() == ISD::UINT_TO_FP ?
5290 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5291 (Op.getOpcode() == ISD::UINT_TO_FP ?
5292 PPCISD::FCFIDU : PPCISD::FCFID);
5293 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5294 MVT::f32 : MVT::f64;
5296 if (Op.getOperand(0).getValueType() == MVT::i64) {
5297 SDValue SINT = Op.getOperand(0);
5298 // When converting to single-precision, we actually need to convert
5299 // to double-precision first and then round to single-precision.
5300 // To avoid double-rounding effects during that operation, we have
5301 // to prepare the input operand. Bits that might be truncated when
5302 // converting to double-precision are replaced by a bit that won't
5303 // be lost at this stage, but is below the single-precision rounding
5306 // However, if -enable-unsafe-fp-math is in effect, accept double
5307 // rounding to avoid the extra overhead.
5308 if (Op.getValueType() == MVT::f32 &&
5309 !Subtarget.hasFPCVT() &&
5310 !DAG.getTarget().Options.UnsafeFPMath) {
5312 // Twiddle input to make sure the low 11 bits are zero. (If this
5313 // is the case, we are guaranteed the value will fit into the 53 bit
5314 // mantissa of an IEEE double-precision value without rounding.)
5315 // If any of those low 11 bits were not zero originally, make sure
5316 // bit 12 (value 2048) is set instead, so that the final rounding
5317 // to single-precision gets the correct result.
5318 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5319 SINT, DAG.getConstant(2047, MVT::i64));
5320 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5321 Round, DAG.getConstant(2047, MVT::i64));
5322 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5323 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5324 Round, DAG.getConstant(-2048, MVT::i64));
5326 // However, we cannot use that value unconditionally: if the magnitude
5327 // of the input value is small, the bit-twiddling we did above might
5328 // end up visibly changing the output. Fortunately, in that case, we
5329 // don't need to twiddle bits since the original input will convert
5330 // exactly to double-precision floating-point already. Therefore,
5331 // construct a conditional to use the original value if the top 11
5332 // bits are all sign-bit copies, and use the rounded value computed
5334 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5335 SINT, DAG.getConstant(53, MVT::i32));
5336 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5337 Cond, DAG.getConstant(1, MVT::i64));
5338 Cond = DAG.getSetCC(dl, MVT::i32,
5339 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5341 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5344 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5345 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5347 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5348 FP = DAG.getNode(ISD::FP_ROUND, dl,
5349 MVT::f32, FP, DAG.getIntPtrConstant(0));
5353 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5354 "Unhandled INT_TO_FP type in custom expander!");
5355 // Since we only generate this in 64-bit mode, we can take advantage of
5356 // 64-bit registers. In particular, sign extend the input value into the
5357 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5358 // then lfd it and fcfid it.
5359 MachineFunction &MF = DAG.getMachineFunction();
5360 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5361 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5364 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5365 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5366 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5368 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5369 MachinePointerInfo::getFixedStack(FrameIdx),
5372 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5373 "Expected an i32 store");
5374 MachineMemOperand *MMO =
5375 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5376 MachineMemOperand::MOLoad, 4, 4);
5377 SDValue Ops[] = { Store, FIdx };
5378 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5379 PPCISD::LFIWZX : PPCISD::LFIWAX,
5380 dl, DAG.getVTList(MVT::f64, MVT::Other),
5381 Ops, MVT::i32, MMO);
5383 assert(Subtarget.isPPC64() &&
5384 "i32->FP without LFIWAX supported only on PPC64");
5386 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5387 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5389 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5392 // STD the extended value into the stack slot.
5393 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5394 MachinePointerInfo::getFixedStack(FrameIdx),
5397 // Load the value as a double.
5398 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5399 MachinePointerInfo::getFixedStack(FrameIdx),
5400 false, false, false, 0);
5403 // FCFID it and return it.
5404 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5405 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5406 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5410 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5411 SelectionDAG &DAG) const {
5414 The rounding mode is in bits 30:31 of FPSR, and has the following
5421 FLT_ROUNDS, on the other hand, expects the following:
5428 To perform the conversion, we do:
5429 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5432 MachineFunction &MF = DAG.getMachineFunction();
5433 EVT VT = Op.getValueType();
5434 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5436 // Save FP Control Word to register
5438 MVT::f64, // return register
5439 MVT::Glue // unused in this context
5441 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5443 // Save FP register to stack slot
5444 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5445 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5446 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5447 StackSlot, MachinePointerInfo(), false, false,0);
5449 // Load FP Control Word from low 32 bits of stack slot.
5450 SDValue Four = DAG.getConstant(4, PtrVT);
5451 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5452 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5453 false, false, false, 0);
5455 // Transform as necessary
5457 DAG.getNode(ISD::AND, dl, MVT::i32,
5458 CWD, DAG.getConstant(3, MVT::i32));
5460 DAG.getNode(ISD::SRL, dl, MVT::i32,
5461 DAG.getNode(ISD::AND, dl, MVT::i32,
5462 DAG.getNode(ISD::XOR, dl, MVT::i32,
5463 CWD, DAG.getConstant(3, MVT::i32)),
5464 DAG.getConstant(3, MVT::i32)),
5465 DAG.getConstant(1, MVT::i32));
5468 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5470 return DAG.getNode((VT.getSizeInBits() < 16 ?
5471 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5474 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5475 EVT VT = Op.getValueType();
5476 unsigned BitWidth = VT.getSizeInBits();
5478 assert(Op.getNumOperands() == 3 &&
5479 VT == Op.getOperand(1).getValueType() &&
5482 // Expand into a bunch of logical ops. Note that these ops
5483 // depend on the PPC behavior for oversized shift amounts.
5484 SDValue Lo = Op.getOperand(0);
5485 SDValue Hi = Op.getOperand(1);
5486 SDValue Amt = Op.getOperand(2);
5487 EVT AmtVT = Amt.getValueType();
5489 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5490 DAG.getConstant(BitWidth, AmtVT), Amt);
5491 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5492 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5493 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5494 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5495 DAG.getConstant(-BitWidth, AmtVT));
5496 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5497 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5498 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5499 SDValue OutOps[] = { OutLo, OutHi };
5500 return DAG.getMergeValues(OutOps, dl);
5503 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5504 EVT VT = Op.getValueType();
5506 unsigned BitWidth = VT.getSizeInBits();
5507 assert(Op.getNumOperands() == 3 &&
5508 VT == Op.getOperand(1).getValueType() &&
5511 // Expand into a bunch of logical ops. Note that these ops
5512 // depend on the PPC behavior for oversized shift amounts.
5513 SDValue Lo = Op.getOperand(0);
5514 SDValue Hi = Op.getOperand(1);
5515 SDValue Amt = Op.getOperand(2);
5516 EVT AmtVT = Amt.getValueType();
5518 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5519 DAG.getConstant(BitWidth, AmtVT), Amt);
5520 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5521 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5522 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5523 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5524 DAG.getConstant(-BitWidth, AmtVT));
5525 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5526 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5527 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5528 SDValue OutOps[] = { OutLo, OutHi };
5529 return DAG.getMergeValues(OutOps, dl);
5532 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5534 EVT VT = Op.getValueType();
5535 unsigned BitWidth = VT.getSizeInBits();
5536 assert(Op.getNumOperands() == 3 &&
5537 VT == Op.getOperand(1).getValueType() &&
5540 // Expand into a bunch of logical ops, followed by a select_cc.
5541 SDValue Lo = Op.getOperand(0);
5542 SDValue Hi = Op.getOperand(1);
5543 SDValue Amt = Op.getOperand(2);
5544 EVT AmtVT = Amt.getValueType();
5546 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5547 DAG.getConstant(BitWidth, AmtVT), Amt);
5548 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5549 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5550 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5551 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5552 DAG.getConstant(-BitWidth, AmtVT));
5553 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5554 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5555 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5556 Tmp4, Tmp6, ISD::SETLE);
5557 SDValue OutOps[] = { OutLo, OutHi };
5558 return DAG.getMergeValues(OutOps, dl);
5561 //===----------------------------------------------------------------------===//
5562 // Vector related lowering.
5565 /// BuildSplatI - Build a canonical splati of Val with an element size of
5566 /// SplatSize. Cast the result to VT.
5567 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5568 SelectionDAG &DAG, SDLoc dl) {
5569 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5571 static const EVT VTys[] = { // canonical VT to use for each size.
5572 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5575 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5577 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5581 EVT CanonicalVT = VTys[SplatSize-1];
5583 // Build a canonical splat for this value.
5584 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5585 SmallVector<SDValue, 8> Ops;
5586 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5587 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5588 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5591 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5592 /// specified intrinsic ID.
5593 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5594 SelectionDAG &DAG, SDLoc dl,
5595 EVT DestVT = MVT::Other) {
5596 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5597 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5598 DAG.getConstant(IID, MVT::i32), Op);
5601 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5602 /// specified intrinsic ID.
5603 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5604 SelectionDAG &DAG, SDLoc dl,
5605 EVT DestVT = MVT::Other) {
5606 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5607 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5608 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5611 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5612 /// specified intrinsic ID.
5613 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5614 SDValue Op2, SelectionDAG &DAG,
5615 SDLoc dl, EVT DestVT = MVT::Other) {
5616 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5617 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5618 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5622 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5623 /// amount. The result has the specified value type.
5624 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5625 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5626 // Force LHS/RHS to be the right type.
5627 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5628 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5631 for (unsigned i = 0; i != 16; ++i)
5633 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5634 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5637 // If this is a case we can't handle, return null and let the default
5638 // expansion code take care of it. If we CAN select this case, and if it
5639 // selects to a single instruction, return Op. Otherwise, if we can codegen
5640 // this case more efficiently than a constant pool load, lower it to the
5641 // sequence of ops that should be used.
5642 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5643 SelectionDAG &DAG) const {
5645 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5646 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5648 // Check if this is a splat of a constant value.
5649 APInt APSplatBits, APSplatUndef;
5650 unsigned SplatBitSize;
5652 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5653 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5656 unsigned SplatBits = APSplatBits.getZExtValue();
5657 unsigned SplatUndef = APSplatUndef.getZExtValue();
5658 unsigned SplatSize = SplatBitSize / 8;
5660 // First, handle single instruction cases.
5663 if (SplatBits == 0) {
5664 // Canonicalize all zero vectors to be v4i32.
5665 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5666 SDValue Z = DAG.getConstant(0, MVT::i32);
5667 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5668 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5673 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5674 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5676 if (SextVal >= -16 && SextVal <= 15)
5677 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5680 // Two instruction sequences.
5682 // If this value is in the range [-32,30] and is even, use:
5683 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5684 // If this value is in the range [17,31] and is odd, use:
5685 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5686 // If this value is in the range [-31,-17] and is odd, use:
5687 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5688 // Note the last two are three-instruction sequences.
5689 if (SextVal >= -32 && SextVal <= 31) {
5690 // To avoid having these optimizations undone by constant folding,
5691 // we convert to a pseudo that will be expanded later into one of
5693 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5694 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5695 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5696 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5697 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5698 if (VT == Op.getValueType())
5701 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5704 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5705 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5707 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5708 // Make -1 and vspltisw -1:
5709 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5711 // Make the VSLW intrinsic, computing 0x8000_0000.
5712 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5715 // xor by OnesV to invert it.
5716 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5717 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5720 // The remaining cases assume either big endian element order or
5721 // a splat-size that equates to the element size of the vector
5722 // to be built. An example that doesn't work for little endian is
5723 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5724 // and a vector element size of 16 bits. The code below will
5725 // produce the vector in big endian element order, which for little
5726 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5728 // For now, just avoid these optimizations in that case.
5729 // FIXME: Develop correct optimizations for LE with mismatched
5730 // splat and element sizes.
5732 if (Subtarget.isLittleEndian() &&
5733 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5736 // Check to see if this is a wide variety of vsplti*, binop self cases.
5737 static const signed char SplatCsts[] = {
5738 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5739 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5742 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5743 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5744 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5745 int i = SplatCsts[idx];
5747 // Figure out what shift amount will be used by altivec if shifted by i in
5749 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5751 // vsplti + shl self.
5752 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5753 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5754 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5755 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5756 Intrinsic::ppc_altivec_vslw
5758 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5759 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5762 // vsplti + srl self.
5763 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5764 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5765 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5766 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5767 Intrinsic::ppc_altivec_vsrw
5769 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5770 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5773 // vsplti + sra self.
5774 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5775 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5776 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5777 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5778 Intrinsic::ppc_altivec_vsraw
5780 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5781 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5784 // vsplti + rol self.
5785 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5786 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5787 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5788 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5789 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5790 Intrinsic::ppc_altivec_vrlw
5792 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5793 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5796 // t = vsplti c, result = vsldoi t, t, 1
5797 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5798 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5799 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5801 // t = vsplti c, result = vsldoi t, t, 2
5802 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5803 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5804 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5806 // t = vsplti c, result = vsldoi t, t, 3
5807 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5808 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5809 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5816 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5817 /// the specified operations to build the shuffle.
5818 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5819 SDValue RHS, SelectionDAG &DAG,
5821 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5822 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5823 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5826 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5838 if (OpNum == OP_COPY) {
5839 if (LHSID == (1*9+2)*9+3) return LHS;
5840 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5844 SDValue OpLHS, OpRHS;
5845 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5846 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5850 default: llvm_unreachable("Unknown i32 permute!");
5852 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5853 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5854 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5855 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5858 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5859 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5860 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5861 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5864 for (unsigned i = 0; i != 16; ++i)
5865 ShufIdxs[i] = (i&3)+0;
5868 for (unsigned i = 0; i != 16; ++i)
5869 ShufIdxs[i] = (i&3)+4;
5872 for (unsigned i = 0; i != 16; ++i)
5873 ShufIdxs[i] = (i&3)+8;
5876 for (unsigned i = 0; i != 16; ++i)
5877 ShufIdxs[i] = (i&3)+12;
5880 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5882 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5884 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5886 EVT VT = OpLHS.getValueType();
5887 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5888 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5889 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5890 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5893 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5894 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5895 /// return the code it can be lowered into. Worst case, it can always be
5896 /// lowered into a vperm.
5897 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5898 SelectionDAG &DAG) const {
5900 SDValue V1 = Op.getOperand(0);
5901 SDValue V2 = Op.getOperand(1);
5902 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5903 EVT VT = Op.getValueType();
5904 bool isLittleEndian = Subtarget.isLittleEndian();
5906 // Cases that are handled by instructions that take permute immediates
5907 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5908 // selected by the instruction selector.
5909 if (V2.getOpcode() == ISD::UNDEF) {
5910 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5911 PPC::isSplatShuffleMask(SVOp, 2) ||
5912 PPC::isSplatShuffleMask(SVOp, 4) ||
5913 PPC::isVPKUWUMShuffleMask(SVOp, true, DAG) ||
5914 PPC::isVPKUHUMShuffleMask(SVOp, true, DAG) ||
5915 PPC::isVSLDOIShuffleMask(SVOp, true, DAG) != -1 ||
5916 PPC::isVMRGLShuffleMask(SVOp, 1, true, DAG) ||
5917 PPC::isVMRGLShuffleMask(SVOp, 2, true, DAG) ||
5918 PPC::isVMRGLShuffleMask(SVOp, 4, true, DAG) ||
5919 PPC::isVMRGHShuffleMask(SVOp, 1, true, DAG) ||
5920 PPC::isVMRGHShuffleMask(SVOp, 2, true, DAG) ||
5921 PPC::isVMRGHShuffleMask(SVOp, 4, true, DAG)) {
5926 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5927 // and produce a fixed permutation. If any of these match, do not lower to
5929 if (PPC::isVPKUWUMShuffleMask(SVOp, false, DAG) ||
5930 PPC::isVPKUHUMShuffleMask(SVOp, false, DAG) ||
5931 PPC::isVSLDOIShuffleMask(SVOp, false, DAG) != -1 ||
5932 PPC::isVMRGLShuffleMask(SVOp, 1, false, DAG) ||
5933 PPC::isVMRGLShuffleMask(SVOp, 2, false, DAG) ||
5934 PPC::isVMRGLShuffleMask(SVOp, 4, false, DAG) ||
5935 PPC::isVMRGHShuffleMask(SVOp, 1, false, DAG) ||
5936 PPC::isVMRGHShuffleMask(SVOp, 2, false, DAG) ||
5937 PPC::isVMRGHShuffleMask(SVOp, 4, false, DAG))
5940 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5941 // perfect shuffle table to emit an optimal matching sequence.
5942 ArrayRef<int> PermMask = SVOp->getMask();
5944 unsigned PFIndexes[4];
5945 bool isFourElementShuffle = true;
5946 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5947 unsigned EltNo = 8; // Start out undef.
5948 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5949 if (PermMask[i*4+j] < 0)
5950 continue; // Undef, ignore it.
5952 unsigned ByteSource = PermMask[i*4+j];
5953 if ((ByteSource & 3) != j) {
5954 isFourElementShuffle = false;
5959 EltNo = ByteSource/4;
5960 } else if (EltNo != ByteSource/4) {
5961 isFourElementShuffle = false;
5965 PFIndexes[i] = EltNo;
5968 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5969 // perfect shuffle vector to determine if it is cost effective to do this as
5970 // discrete instructions, or whether we should use a vperm.
5971 // For now, we skip this for little endian until such time as we have a
5972 // little-endian perfect shuffle table.
5973 if (isFourElementShuffle && !isLittleEndian) {
5974 // Compute the index in the perfect shuffle table.
5975 unsigned PFTableIndex =
5976 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5978 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5979 unsigned Cost = (PFEntry >> 30);
5981 // Determining when to avoid vperm is tricky. Many things affect the cost
5982 // of vperm, particularly how many times the perm mask needs to be computed.
5983 // For example, if the perm mask can be hoisted out of a loop or is already
5984 // used (perhaps because there are multiple permutes with the same shuffle
5985 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5986 // the loop requires an extra register.
5988 // As a compromise, we only emit discrete instructions if the shuffle can be
5989 // generated in 3 or fewer operations. When we have loop information
5990 // available, if this block is within a loop, we should avoid using vperm
5991 // for 3-operation perms and use a constant pool load instead.
5993 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5996 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5997 // vector that will get spilled to the constant pool.
5998 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6000 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6001 // that it is in input element units, not in bytes. Convert now.
6003 // For little endian, the order of the input vectors is reversed, and
6004 // the permutation mask is complemented with respect to 31. This is
6005 // necessary to produce proper semantics with the big-endian-biased vperm
6007 EVT EltVT = V1.getValueType().getVectorElementType();
6008 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6010 SmallVector<SDValue, 16> ResultMask;
6011 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6012 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6014 for (unsigned j = 0; j != BytesPerElement; ++j)
6016 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6019 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6023 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6026 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6029 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6033 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6034 /// altivec comparison. If it is, return true and fill in Opc/isDot with
6035 /// information about the intrinsic.
6036 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6038 unsigned IntrinsicID =
6039 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6042 switch (IntrinsicID) {
6043 default: return false;
6044 // Comparison predicates.
6045 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
6046 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6047 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
6048 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
6049 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6050 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6051 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6052 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6053 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6054 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6055 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6056 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6057 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6059 // Normal Comparisons.
6060 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
6061 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
6062 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
6063 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
6064 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
6065 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
6066 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
6067 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
6068 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
6069 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
6070 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
6071 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
6072 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
6077 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6078 /// lower, do it, otherwise return null.
6079 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6080 SelectionDAG &DAG) const {
6081 // If this is a lowered altivec predicate compare, CompareOpc is set to the
6082 // opcode number of the comparison.
6086 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6087 return SDValue(); // Don't custom lower most intrinsics.
6089 // If this is a non-dot comparison, make the VCMP node and we are done.
6091 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6092 Op.getOperand(1), Op.getOperand(2),
6093 DAG.getConstant(CompareOpc, MVT::i32));
6094 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6097 // Create the PPCISD altivec 'dot' comparison node.
6099 Op.getOperand(2), // LHS
6100 Op.getOperand(3), // RHS
6101 DAG.getConstant(CompareOpc, MVT::i32)
6103 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6104 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6106 // Now that we have the comparison, emit a copy from the CR to a GPR.
6107 // This is flagged to the above dot comparison.
6108 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6109 DAG.getRegister(PPC::CR6, MVT::i32),
6110 CompNode.getValue(1));
6112 // Unpack the result based on how the target uses it.
6113 unsigned BitNo; // Bit # of CR6.
6114 bool InvertBit; // Invert result?
6115 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6116 default: // Can't happen, don't crash on invalid number though.
6117 case 0: // Return the value of the EQ bit of CR6.
6118 BitNo = 0; InvertBit = false;
6120 case 1: // Return the inverted value of the EQ bit of CR6.
6121 BitNo = 0; InvertBit = true;
6123 case 2: // Return the value of the LT bit of CR6.
6124 BitNo = 2; InvertBit = false;
6126 case 3: // Return the inverted value of the LT bit of CR6.
6127 BitNo = 2; InvertBit = true;
6131 // Shift the bit into the low position.
6132 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6133 DAG.getConstant(8-(3-BitNo), MVT::i32));
6135 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6136 DAG.getConstant(1, MVT::i32));
6138 // If we are supposed to, toggle the bit.
6140 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6141 DAG.getConstant(1, MVT::i32));
6145 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6146 SelectionDAG &DAG) const {
6148 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6149 // instructions), but for smaller types, we need to first extend up to v2i32
6150 // before doing going farther.
6151 if (Op.getValueType() == MVT::v2i64) {
6152 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6153 if (ExtVT != MVT::v2i32) {
6154 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6155 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6156 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6157 ExtVT.getVectorElementType(), 4)));
6158 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6159 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6160 DAG.getValueType(MVT::v2i32));
6169 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6170 SelectionDAG &DAG) const {
6172 // Create a stack slot that is 16-byte aligned.
6173 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6174 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6175 EVT PtrVT = getPointerTy();
6176 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6178 // Store the input value into Value#0 of the stack slot.
6179 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6180 Op.getOperand(0), FIdx, MachinePointerInfo(),
6183 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6184 false, false, false, 0);
6187 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6189 if (Op.getValueType() == MVT::v4i32) {
6190 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6192 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6193 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6195 SDValue RHSSwap = // = vrlw RHS, 16
6196 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6198 // Shrinkify inputs to v8i16.
6199 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6200 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6201 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6203 // Low parts multiplied together, generating 32-bit results (we ignore the
6205 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6206 LHS, RHS, DAG, dl, MVT::v4i32);
6208 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6209 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6210 // Shift the high parts up 16 bits.
6211 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6213 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6214 } else if (Op.getValueType() == MVT::v8i16) {
6215 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6217 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6219 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6220 LHS, RHS, Zero, DAG, dl);
6221 } else if (Op.getValueType() == MVT::v16i8) {
6222 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6223 bool isLittleEndian = Subtarget.isLittleEndian();
6225 // Multiply the even 8-bit parts, producing 16-bit sums.
6226 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6227 LHS, RHS, DAG, dl, MVT::v8i16);
6228 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6230 // Multiply the odd 8-bit parts, producing 16-bit sums.
6231 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6232 LHS, RHS, DAG, dl, MVT::v8i16);
6233 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6235 // Merge the results together. Because vmuleub and vmuloub are
6236 // instructions with a big-endian bias, we must reverse the
6237 // element numbering and reverse the meaning of "odd" and "even"
6238 // when generating little endian code.
6240 for (unsigned i = 0; i != 8; ++i) {
6241 if (isLittleEndian) {
6243 Ops[i*2+1] = 2*i+16;
6246 Ops[i*2+1] = 2*i+1+16;
6250 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6252 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6254 llvm_unreachable("Unknown mul to lower!");
6258 /// LowerOperation - Provide custom lowering hooks for some operations.
6260 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6261 switch (Op.getOpcode()) {
6262 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6263 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6264 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6265 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6266 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6267 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6268 case ISD::SETCC: return LowerSETCC(Op, DAG);
6269 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6270 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6272 return LowerVASTART(Op, DAG, Subtarget);
6275 return LowerVAARG(Op, DAG, Subtarget);
6278 return LowerVACOPY(Op, DAG, Subtarget);
6280 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
6281 case ISD::DYNAMIC_STACKALLOC:
6282 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6284 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6285 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6287 case ISD::LOAD: return LowerLOAD(Op, DAG);
6288 case ISD::STORE: return LowerSTORE(Op, DAG);
6289 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6290 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6291 case ISD::FP_TO_UINT:
6292 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6294 case ISD::UINT_TO_FP:
6295 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6296 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6298 // Lower 64-bit shifts.
6299 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6300 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6301 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6303 // Vector-related lowering.
6304 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6305 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6306 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6307 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6308 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6309 case ISD::MUL: return LowerMUL(Op, DAG);
6311 // For counter-based loop handling.
6312 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6314 // Frame & Return address.
6315 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6316 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6320 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6321 SmallVectorImpl<SDValue>&Results,
6322 SelectionDAG &DAG) const {
6323 const TargetMachine &TM = getTargetMachine();
6325 switch (N->getOpcode()) {
6327 llvm_unreachable("Do not know how to custom type legalize this operation!");
6328 case ISD::INTRINSIC_W_CHAIN: {
6329 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6330 Intrinsic::ppc_is_decremented_ctr_nonzero)
6333 assert(N->getValueType(0) == MVT::i1 &&
6334 "Unexpected result type for CTR decrement intrinsic");
6335 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6336 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6337 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6340 Results.push_back(NewInt);
6341 Results.push_back(NewInt.getValue(1));
6345 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6346 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6349 EVT VT = N->getValueType(0);
6351 if (VT == MVT::i64) {
6352 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6354 Results.push_back(NewNode);
6355 Results.push_back(NewNode.getValue(1));
6359 case ISD::FP_ROUND_INREG: {
6360 assert(N->getValueType(0) == MVT::ppcf128);
6361 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6362 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6363 MVT::f64, N->getOperand(0),
6364 DAG.getIntPtrConstant(0));
6365 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6366 MVT::f64, N->getOperand(0),
6367 DAG.getIntPtrConstant(1));
6369 // Add the two halves of the long double in round-to-zero mode.
6370 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6372 // We know the low half is about to be thrown away, so just use something
6374 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6378 case ISD::FP_TO_SINT:
6379 // LowerFP_TO_INT() can only handle f32 and f64.
6380 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6382 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6388 //===----------------------------------------------------------------------===//
6389 // Other Lowering Code
6390 //===----------------------------------------------------------------------===//
6393 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6394 bool is64bit, unsigned BinOpcode) const {
6395 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6396 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6398 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6399 MachineFunction *F = BB->getParent();
6400 MachineFunction::iterator It = BB;
6403 unsigned dest = MI->getOperand(0).getReg();
6404 unsigned ptrA = MI->getOperand(1).getReg();
6405 unsigned ptrB = MI->getOperand(2).getReg();
6406 unsigned incr = MI->getOperand(3).getReg();
6407 DebugLoc dl = MI->getDebugLoc();
6409 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6410 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6411 F->insert(It, loopMBB);
6412 F->insert(It, exitMBB);
6413 exitMBB->splice(exitMBB->begin(), BB,
6414 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6415 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6417 MachineRegisterInfo &RegInfo = F->getRegInfo();
6418 unsigned TmpReg = (!BinOpcode) ? incr :
6419 RegInfo.createVirtualRegister(
6420 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6421 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6425 // fallthrough --> loopMBB
6426 BB->addSuccessor(loopMBB);
6429 // l[wd]arx dest, ptr
6430 // add r0, dest, incr
6431 // st[wd]cx. r0, ptr
6433 // fallthrough --> exitMBB
6435 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6436 .addReg(ptrA).addReg(ptrB);
6438 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6439 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6440 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6441 BuildMI(BB, dl, TII->get(PPC::BCC))
6442 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6443 BB->addSuccessor(loopMBB);
6444 BB->addSuccessor(exitMBB);
6453 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6454 MachineBasicBlock *BB,
6455 bool is8bit, // operation
6456 unsigned BinOpcode) const {
6457 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6458 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6459 // In 64 bit mode we have to use 64 bits for addresses, even though the
6460 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6461 // registers without caring whether they're 32 or 64, but here we're
6462 // doing actual arithmetic on the addresses.
6463 bool is64bit = Subtarget.isPPC64();
6464 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6466 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6467 MachineFunction *F = BB->getParent();
6468 MachineFunction::iterator It = BB;
6471 unsigned dest = MI->getOperand(0).getReg();
6472 unsigned ptrA = MI->getOperand(1).getReg();
6473 unsigned ptrB = MI->getOperand(2).getReg();
6474 unsigned incr = MI->getOperand(3).getReg();
6475 DebugLoc dl = MI->getDebugLoc();
6477 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6478 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6479 F->insert(It, loopMBB);
6480 F->insert(It, exitMBB);
6481 exitMBB->splice(exitMBB->begin(), BB,
6482 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6483 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6485 MachineRegisterInfo &RegInfo = F->getRegInfo();
6486 const TargetRegisterClass *RC =
6487 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6488 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6489 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6490 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6491 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6492 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6493 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6494 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6495 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6496 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6497 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6498 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6499 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6501 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6505 // fallthrough --> loopMBB
6506 BB->addSuccessor(loopMBB);
6508 // The 4-byte load must be aligned, while a char or short may be
6509 // anywhere in the word. Hence all this nasty bookkeeping code.
6510 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6511 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6512 // xori shift, shift1, 24 [16]
6513 // rlwinm ptr, ptr1, 0, 0, 29
6514 // slw incr2, incr, shift
6515 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6516 // slw mask, mask2, shift
6518 // lwarx tmpDest, ptr
6519 // add tmp, tmpDest, incr2
6520 // andc tmp2, tmpDest, mask
6521 // and tmp3, tmp, mask
6522 // or tmp4, tmp3, tmp2
6525 // fallthrough --> exitMBB
6526 // srw dest, tmpDest, shift
6527 if (ptrA != ZeroReg) {
6528 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6529 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6530 .addReg(ptrA).addReg(ptrB);
6534 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6535 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6536 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6537 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6539 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6540 .addReg(Ptr1Reg).addImm(0).addImm(61);
6542 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6543 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6544 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6545 .addReg(incr).addReg(ShiftReg);
6547 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6549 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6550 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6552 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6553 .addReg(Mask2Reg).addReg(ShiftReg);
6556 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6557 .addReg(ZeroReg).addReg(PtrReg);
6559 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6560 .addReg(Incr2Reg).addReg(TmpDestReg);
6561 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6562 .addReg(TmpDestReg).addReg(MaskReg);
6563 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6564 .addReg(TmpReg).addReg(MaskReg);
6565 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6566 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6567 BuildMI(BB, dl, TII->get(PPC::STWCX))
6568 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6569 BuildMI(BB, dl, TII->get(PPC::BCC))
6570 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6571 BB->addSuccessor(loopMBB);
6572 BB->addSuccessor(exitMBB);
6577 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6582 llvm::MachineBasicBlock*
6583 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6584 MachineBasicBlock *MBB) const {
6585 DebugLoc DL = MI->getDebugLoc();
6586 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6588 MachineFunction *MF = MBB->getParent();
6589 MachineRegisterInfo &MRI = MF->getRegInfo();
6591 const BasicBlock *BB = MBB->getBasicBlock();
6592 MachineFunction::iterator I = MBB;
6596 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6597 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6599 unsigned DstReg = MI->getOperand(0).getReg();
6600 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6601 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6602 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6603 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6605 MVT PVT = getPointerTy();
6606 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6607 "Invalid Pointer Size!");
6608 // For v = setjmp(buf), we generate
6611 // SjLjSetup mainMBB
6617 // buf[LabelOffset] = LR
6621 // v = phi(main, restore)
6624 MachineBasicBlock *thisMBB = MBB;
6625 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6626 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6627 MF->insert(I, mainMBB);
6628 MF->insert(I, sinkMBB);
6630 MachineInstrBuilder MIB;
6632 // Transfer the remainder of BB and its successor edges to sinkMBB.
6633 sinkMBB->splice(sinkMBB->begin(), MBB,
6634 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6635 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6637 // Note that the structure of the jmp_buf used here is not compatible
6638 // with that used by libc, and is not designed to be. Specifically, it
6639 // stores only those 'reserved' registers that LLVM does not otherwise
6640 // understand how to spill. Also, by convention, by the time this
6641 // intrinsic is called, Clang has already stored the frame address in the
6642 // first slot of the buffer and stack address in the third. Following the
6643 // X86 target code, we'll store the jump address in the second slot. We also
6644 // need to save the TOC pointer (R2) to handle jumps between shared
6645 // libraries, and that will be stored in the fourth slot. The thread
6646 // identifier (R13) is not affected.
6649 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6650 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6651 const int64_t BPOffset = 4 * PVT.getStoreSize();
6653 // Prepare IP either in reg.
6654 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6655 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6656 unsigned BufReg = MI->getOperand(1).getReg();
6658 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6659 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6663 MIB.setMemRefs(MMOBegin, MMOEnd);
6666 // Naked functions never have a base pointer, and so we use r1. For all
6667 // other functions, this decision must be delayed until during PEI.
6669 if (MF->getFunction()->getAttributes().hasAttribute(
6670 AttributeSet::FunctionIndex, Attribute::Naked))
6671 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6673 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6675 MIB = BuildMI(*thisMBB, MI, DL,
6676 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6680 MIB.setMemRefs(MMOBegin, MMOEnd);
6683 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6684 const PPCRegisterInfo *TRI =
6685 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6686 MIB.addRegMask(TRI->getNoPreservedMask());
6688 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6690 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6692 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6694 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6695 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6699 MIB = BuildMI(mainMBB, DL,
6700 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6703 if (Subtarget.isPPC64()) {
6704 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6706 .addImm(LabelOffset)
6709 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6711 .addImm(LabelOffset)
6715 MIB.setMemRefs(MMOBegin, MMOEnd);
6717 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6718 mainMBB->addSuccessor(sinkMBB);
6721 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6722 TII->get(PPC::PHI), DstReg)
6723 .addReg(mainDstReg).addMBB(mainMBB)
6724 .addReg(restoreDstReg).addMBB(thisMBB);
6726 MI->eraseFromParent();
6731 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6732 MachineBasicBlock *MBB) const {
6733 DebugLoc DL = MI->getDebugLoc();
6734 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6736 MachineFunction *MF = MBB->getParent();
6737 MachineRegisterInfo &MRI = MF->getRegInfo();
6740 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6741 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6743 MVT PVT = getPointerTy();
6744 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6745 "Invalid Pointer Size!");
6747 const TargetRegisterClass *RC =
6748 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6749 unsigned Tmp = MRI.createVirtualRegister(RC);
6750 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6751 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6752 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6753 unsigned BP = (PVT == MVT::i64) ? PPC::X30 :
6754 (Subtarget.isSVR4ABI() &&
6755 MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6756 PPC::R29 : PPC::R30);
6758 MachineInstrBuilder MIB;
6760 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6761 const int64_t SPOffset = 2 * PVT.getStoreSize();
6762 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6763 const int64_t BPOffset = 4 * PVT.getStoreSize();
6765 unsigned BufReg = MI->getOperand(0).getReg();
6767 // Reload FP (the jumped-to function may not have had a
6768 // frame pointer, and if so, then its r31 will be restored
6770 if (PVT == MVT::i64) {
6771 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6775 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6779 MIB.setMemRefs(MMOBegin, MMOEnd);
6782 if (PVT == MVT::i64) {
6783 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6784 .addImm(LabelOffset)
6787 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6788 .addImm(LabelOffset)
6791 MIB.setMemRefs(MMOBegin, MMOEnd);
6794 if (PVT == MVT::i64) {
6795 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6799 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6803 MIB.setMemRefs(MMOBegin, MMOEnd);
6806 if (PVT == MVT::i64) {
6807 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6811 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6815 MIB.setMemRefs(MMOBegin, MMOEnd);
6818 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
6819 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6823 MIB.setMemRefs(MMOBegin, MMOEnd);
6827 BuildMI(*MBB, MI, DL,
6828 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6829 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6831 MI->eraseFromParent();
6836 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6837 MachineBasicBlock *BB) const {
6838 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6839 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6840 return emitEHSjLjSetJmp(MI, BB);
6841 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6842 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6843 return emitEHSjLjLongJmp(MI, BB);
6846 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6848 // To "insert" these instructions we actually have to insert their
6849 // control-flow patterns.
6850 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6851 MachineFunction::iterator It = BB;
6854 MachineFunction *F = BB->getParent();
6856 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6857 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6858 MI->getOpcode() == PPC::SELECT_I4 ||
6859 MI->getOpcode() == PPC::SELECT_I8)) {
6860 SmallVector<MachineOperand, 2> Cond;
6861 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6862 MI->getOpcode() == PPC::SELECT_CC_I8)
6863 Cond.push_back(MI->getOperand(4));
6865 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6866 Cond.push_back(MI->getOperand(1));
6868 DebugLoc dl = MI->getDebugLoc();
6869 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6870 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6871 Cond, MI->getOperand(2).getReg(),
6872 MI->getOperand(3).getReg());
6873 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6874 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6875 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6876 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6877 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6878 MI->getOpcode() == PPC::SELECT_I4 ||
6879 MI->getOpcode() == PPC::SELECT_I8 ||
6880 MI->getOpcode() == PPC::SELECT_F4 ||
6881 MI->getOpcode() == PPC::SELECT_F8 ||
6882 MI->getOpcode() == PPC::SELECT_VRRC) {
6883 // The incoming instruction knows the destination vreg to set, the
6884 // condition code register to branch on, the true/false values to
6885 // select between, and a branch opcode to use.
6890 // cmpTY ccX, r1, r2
6892 // fallthrough --> copy0MBB
6893 MachineBasicBlock *thisMBB = BB;
6894 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6895 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6896 DebugLoc dl = MI->getDebugLoc();
6897 F->insert(It, copy0MBB);
6898 F->insert(It, sinkMBB);
6900 // Transfer the remainder of BB and its successor edges to sinkMBB.
6901 sinkMBB->splice(sinkMBB->begin(), BB,
6902 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6903 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6905 // Next, add the true and fallthrough blocks as its successors.
6906 BB->addSuccessor(copy0MBB);
6907 BB->addSuccessor(sinkMBB);
6909 if (MI->getOpcode() == PPC::SELECT_I4 ||
6910 MI->getOpcode() == PPC::SELECT_I8 ||
6911 MI->getOpcode() == PPC::SELECT_F4 ||
6912 MI->getOpcode() == PPC::SELECT_F8 ||
6913 MI->getOpcode() == PPC::SELECT_VRRC) {
6914 BuildMI(BB, dl, TII->get(PPC::BC))
6915 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6917 unsigned SelectPred = MI->getOperand(4).getImm();
6918 BuildMI(BB, dl, TII->get(PPC::BCC))
6919 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6923 // %FalseValue = ...
6924 // # fallthrough to sinkMBB
6927 // Update machine-CFG edges
6928 BB->addSuccessor(sinkMBB);
6931 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6934 BuildMI(*BB, BB->begin(), dl,
6935 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6936 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6937 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6939 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6940 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6941 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6942 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6943 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6944 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6945 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6946 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6948 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6949 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6950 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6951 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6952 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6953 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6954 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6955 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6957 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6958 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6959 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6960 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6961 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6962 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6963 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6964 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6966 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6967 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6968 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6969 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6970 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6971 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6972 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6973 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6975 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6976 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
6977 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6978 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
6979 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6980 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
6981 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6982 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
6984 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6985 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6986 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6987 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6988 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6989 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6990 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6991 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6993 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6994 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6995 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6996 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6997 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6998 BB = EmitAtomicBinary(MI, BB, false, 0);
6999 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7000 BB = EmitAtomicBinary(MI, BB, true, 0);
7002 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7003 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7004 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7006 unsigned dest = MI->getOperand(0).getReg();
7007 unsigned ptrA = MI->getOperand(1).getReg();
7008 unsigned ptrB = MI->getOperand(2).getReg();
7009 unsigned oldval = MI->getOperand(3).getReg();
7010 unsigned newval = MI->getOperand(4).getReg();
7011 DebugLoc dl = MI->getDebugLoc();
7013 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7014 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7015 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7016 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7017 F->insert(It, loop1MBB);
7018 F->insert(It, loop2MBB);
7019 F->insert(It, midMBB);
7020 F->insert(It, exitMBB);
7021 exitMBB->splice(exitMBB->begin(), BB,
7022 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7023 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7027 // fallthrough --> loopMBB
7028 BB->addSuccessor(loop1MBB);
7031 // l[wd]arx dest, ptr
7032 // cmp[wd] dest, oldval
7035 // st[wd]cx. newval, ptr
7039 // st[wd]cx. dest, ptr
7042 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7043 .addReg(ptrA).addReg(ptrB);
7044 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7045 .addReg(oldval).addReg(dest);
7046 BuildMI(BB, dl, TII->get(PPC::BCC))
7047 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7048 BB->addSuccessor(loop2MBB);
7049 BB->addSuccessor(midMBB);
7052 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7053 .addReg(newval).addReg(ptrA).addReg(ptrB);
7054 BuildMI(BB, dl, TII->get(PPC::BCC))
7055 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7056 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7057 BB->addSuccessor(loop1MBB);
7058 BB->addSuccessor(exitMBB);
7061 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7062 .addReg(dest).addReg(ptrA).addReg(ptrB);
7063 BB->addSuccessor(exitMBB);
7068 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7069 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7070 // We must use 64-bit registers for addresses when targeting 64-bit,
7071 // since we're actually doing arithmetic on them. Other registers
7073 bool is64bit = Subtarget.isPPC64();
7074 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7076 unsigned dest = MI->getOperand(0).getReg();
7077 unsigned ptrA = MI->getOperand(1).getReg();
7078 unsigned ptrB = MI->getOperand(2).getReg();
7079 unsigned oldval = MI->getOperand(3).getReg();
7080 unsigned newval = MI->getOperand(4).getReg();
7081 DebugLoc dl = MI->getDebugLoc();
7083 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7084 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7085 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7086 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7087 F->insert(It, loop1MBB);
7088 F->insert(It, loop2MBB);
7089 F->insert(It, midMBB);
7090 F->insert(It, exitMBB);
7091 exitMBB->splice(exitMBB->begin(), BB,
7092 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7093 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7095 MachineRegisterInfo &RegInfo = F->getRegInfo();
7096 const TargetRegisterClass *RC =
7097 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
7098 (const TargetRegisterClass *) &PPC::GPRCRegClass;
7099 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7100 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7101 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7102 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7103 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7104 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7105 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7106 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7107 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7108 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7109 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7110 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7111 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7113 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7114 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7117 // fallthrough --> loopMBB
7118 BB->addSuccessor(loop1MBB);
7120 // The 4-byte load must be aligned, while a char or short may be
7121 // anywhere in the word. Hence all this nasty bookkeeping code.
7122 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7123 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7124 // xori shift, shift1, 24 [16]
7125 // rlwinm ptr, ptr1, 0, 0, 29
7126 // slw newval2, newval, shift
7127 // slw oldval2, oldval,shift
7128 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7129 // slw mask, mask2, shift
7130 // and newval3, newval2, mask
7131 // and oldval3, oldval2, mask
7133 // lwarx tmpDest, ptr
7134 // and tmp, tmpDest, mask
7135 // cmpw tmp, oldval3
7138 // andc tmp2, tmpDest, mask
7139 // or tmp4, tmp2, newval3
7144 // stwcx. tmpDest, ptr
7146 // srw dest, tmpDest, shift
7147 if (ptrA != ZeroReg) {
7148 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7149 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7150 .addReg(ptrA).addReg(ptrB);
7154 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7155 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7156 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7157 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7159 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7160 .addReg(Ptr1Reg).addImm(0).addImm(61);
7162 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7163 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7164 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7165 .addReg(newval).addReg(ShiftReg);
7166 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7167 .addReg(oldval).addReg(ShiftReg);
7169 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7171 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7172 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7173 .addReg(Mask3Reg).addImm(65535);
7175 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7176 .addReg(Mask2Reg).addReg(ShiftReg);
7177 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7178 .addReg(NewVal2Reg).addReg(MaskReg);
7179 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7180 .addReg(OldVal2Reg).addReg(MaskReg);
7183 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7184 .addReg(ZeroReg).addReg(PtrReg);
7185 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7186 .addReg(TmpDestReg).addReg(MaskReg);
7187 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7188 .addReg(TmpReg).addReg(OldVal3Reg);
7189 BuildMI(BB, dl, TII->get(PPC::BCC))
7190 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7191 BB->addSuccessor(loop2MBB);
7192 BB->addSuccessor(midMBB);
7195 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7196 .addReg(TmpDestReg).addReg(MaskReg);
7197 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7198 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7199 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7200 .addReg(ZeroReg).addReg(PtrReg);
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(PPC::STWCX)).addReg(TmpDestReg)
7209 .addReg(ZeroReg).addReg(PtrReg);
7210 BB->addSuccessor(exitMBB);
7215 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7217 } else if (MI->getOpcode() == PPC::FADDrtz) {
7218 // This pseudo performs an FADD with rounding mode temporarily forced
7219 // to round-to-zero. We emit this via custom inserter since the FPSCR
7220 // is not modeled at the SelectionDAG level.
7221 unsigned Dest = MI->getOperand(0).getReg();
7222 unsigned Src1 = MI->getOperand(1).getReg();
7223 unsigned Src2 = MI->getOperand(2).getReg();
7224 DebugLoc dl = MI->getDebugLoc();
7226 MachineRegisterInfo &RegInfo = F->getRegInfo();
7227 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7229 // Save FPSCR value.
7230 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7232 // Set rounding mode to round-to-zero.
7233 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7234 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7236 // Perform addition.
7237 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7239 // Restore FPSCR value.
7240 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7241 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7242 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7243 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7244 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7245 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7246 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7247 PPC::ANDIo8 : PPC::ANDIo;
7248 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7249 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7251 MachineRegisterInfo &RegInfo = F->getRegInfo();
7252 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7253 &PPC::GPRCRegClass :
7254 &PPC::G8RCRegClass);
7256 DebugLoc dl = MI->getDebugLoc();
7257 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7258 .addReg(MI->getOperand(1).getReg()).addImm(1);
7259 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7260 MI->getOperand(0).getReg())
7261 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7263 llvm_unreachable("Unexpected instr type to insert");
7266 MI->eraseFromParent(); // The pseudo instruction is gone now.
7270 //===----------------------------------------------------------------------===//
7271 // Target Optimization Hooks
7272 //===----------------------------------------------------------------------===//
7274 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7275 DAGCombinerInfo &DCI) const {
7276 if (DCI.isAfterLegalizeVectorOps())
7279 EVT VT = Op.getValueType();
7281 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7282 (VT == MVT::f64 && Subtarget.hasFRE()) ||
7283 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7284 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7286 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7287 // For the reciprocal, we need to find the zero of the function:
7288 // F(X) = A X - 1 [which has a zero at X = 1/A]
7290 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7291 // does not require additional intermediate precision]
7293 // Convergence is quadratic, so we essentially double the number of digits
7294 // correct after every iteration. The minimum architected relative
7295 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7296 // 23 digits and double has 52 digits.
7297 int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7298 if (VT.getScalarType() == MVT::f64)
7301 SelectionDAG &DAG = DCI.DAG;
7305 DAG.getConstantFP(1.0, VT.getScalarType());
7306 if (VT.isVector()) {
7307 assert(VT.getVectorNumElements() == 4 &&
7308 "Unknown vector type");
7309 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7310 FPOne, FPOne, FPOne, FPOne);
7313 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7314 DCI.AddToWorklist(Est.getNode());
7316 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7317 for (int i = 0; i < Iterations; ++i) {
7318 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7319 DCI.AddToWorklist(NewEst.getNode());
7321 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7322 DCI.AddToWorklist(NewEst.getNode());
7324 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7325 DCI.AddToWorklist(NewEst.getNode());
7327 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7328 DCI.AddToWorklist(Est.getNode());
7337 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7338 DAGCombinerInfo &DCI) const {
7339 if (DCI.isAfterLegalizeVectorOps())
7342 EVT VT = Op.getValueType();
7344 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7345 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7346 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7347 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7349 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7350 // For the reciprocal sqrt, we need to find the zero of the function:
7351 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7353 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7354 // As a result, we precompute A/2 prior to the iteration loop.
7356 // Convergence is quadratic, so we essentially double the number of digits
7357 // correct after every iteration. The minimum architected relative
7358 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7359 // 23 digits and double has 52 digits.
7360 int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7361 if (VT.getScalarType() == MVT::f64)
7364 SelectionDAG &DAG = DCI.DAG;
7367 SDValue FPThreeHalves =
7368 DAG.getConstantFP(1.5, VT.getScalarType());
7369 if (VT.isVector()) {
7370 assert(VT.getVectorNumElements() == 4 &&
7371 "Unknown vector type");
7372 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7373 FPThreeHalves, FPThreeHalves,
7374 FPThreeHalves, FPThreeHalves);
7377 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7378 DCI.AddToWorklist(Est.getNode());
7380 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7381 // this entire sequence requires only one FP constant.
7382 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7383 DCI.AddToWorklist(HalfArg.getNode());
7385 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7386 DCI.AddToWorklist(HalfArg.getNode());
7388 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7389 for (int i = 0; i < Iterations; ++i) {
7390 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7391 DCI.AddToWorklist(NewEst.getNode());
7393 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7394 DCI.AddToWorklist(NewEst.getNode());
7396 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7397 DCI.AddToWorklist(NewEst.getNode());
7399 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7400 DCI.AddToWorklist(Est.getNode());
7409 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7410 // not enforce equality of the chain operands.
7411 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7412 unsigned Bytes, int Dist,
7413 SelectionDAG &DAG) {
7414 EVT VT = LS->getMemoryVT();
7415 if (VT.getSizeInBits() / 8 != Bytes)
7418 SDValue Loc = LS->getBasePtr();
7419 SDValue BaseLoc = Base->getBasePtr();
7420 if (Loc.getOpcode() == ISD::FrameIndex) {
7421 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7423 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7424 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7425 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7426 int FS = MFI->getObjectSize(FI);
7427 int BFS = MFI->getObjectSize(BFI);
7428 if (FS != BFS || FS != (int)Bytes) return false;
7429 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7433 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7434 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7437 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7438 const GlobalValue *GV1 = nullptr;
7439 const GlobalValue *GV2 = nullptr;
7440 int64_t Offset1 = 0;
7441 int64_t Offset2 = 0;
7442 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7443 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7444 if (isGA1 && isGA2 && GV1 == GV2)
7445 return Offset1 == (Offset2 + Dist*Bytes);
7449 // Return true is there is a nearyby consecutive load to the one provided
7450 // (regardless of alignment). We search up and down the chain, looking though
7451 // token factors and other loads (but nothing else). As a result, a true
7452 // results indicates that it is safe to create a new consecutive load adjacent
7453 // to the load provided.
7454 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7455 SDValue Chain = LD->getChain();
7456 EVT VT = LD->getMemoryVT();
7458 SmallSet<SDNode *, 16> LoadRoots;
7459 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7460 SmallSet<SDNode *, 16> Visited;
7462 // First, search up the chain, branching to follow all token-factor operands.
7463 // If we find a consecutive load, then we're done, otherwise, record all
7464 // nodes just above the top-level loads and token factors.
7465 while (!Queue.empty()) {
7466 SDNode *ChainNext = Queue.pop_back_val();
7467 if (!Visited.insert(ChainNext))
7470 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7471 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7474 if (!Visited.count(ChainLD->getChain().getNode()))
7475 Queue.push_back(ChainLD->getChain().getNode());
7476 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7477 for (const SDUse &O : ChainNext->ops())
7478 if (!Visited.count(O.getNode()))
7479 Queue.push_back(O.getNode());
7481 LoadRoots.insert(ChainNext);
7484 // Second, search down the chain, starting from the top-level nodes recorded
7485 // in the first phase. These top-level nodes are the nodes just above all
7486 // loads and token factors. Starting with their uses, recursively look though
7487 // all loads (just the chain uses) and token factors to find a consecutive
7492 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7493 IE = LoadRoots.end(); I != IE; ++I) {
7494 Queue.push_back(*I);
7496 while (!Queue.empty()) {
7497 SDNode *LoadRoot = Queue.pop_back_val();
7498 if (!Visited.insert(LoadRoot))
7501 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7502 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7505 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7506 UE = LoadRoot->use_end(); UI != UE; ++UI)
7507 if (((isa<LoadSDNode>(*UI) &&
7508 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7509 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7510 Queue.push_back(*UI);
7517 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7518 DAGCombinerInfo &DCI) const {
7519 SelectionDAG &DAG = DCI.DAG;
7522 assert(Subtarget.useCRBits() &&
7523 "Expecting to be tracking CR bits");
7524 // If we're tracking CR bits, we need to be careful that we don't have:
7525 // trunc(binary-ops(zext(x), zext(y)))
7527 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7528 // such that we're unnecessarily moving things into GPRs when it would be
7529 // better to keep them in CR bits.
7531 // Note that trunc here can be an actual i1 trunc, or can be the effective
7532 // truncation that comes from a setcc or select_cc.
7533 if (N->getOpcode() == ISD::TRUNCATE &&
7534 N->getValueType(0) != MVT::i1)
7537 if (N->getOperand(0).getValueType() != MVT::i32 &&
7538 N->getOperand(0).getValueType() != MVT::i64)
7541 if (N->getOpcode() == ISD::SETCC ||
7542 N->getOpcode() == ISD::SELECT_CC) {
7543 // If we're looking at a comparison, then we need to make sure that the
7544 // high bits (all except for the first) don't matter the result.
7546 cast<CondCodeSDNode>(N->getOperand(
7547 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7548 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7550 if (ISD::isSignedIntSetCC(CC)) {
7551 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7552 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7554 } else if (ISD::isUnsignedIntSetCC(CC)) {
7555 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7556 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7557 !DAG.MaskedValueIsZero(N->getOperand(1),
7558 APInt::getHighBitsSet(OpBits, OpBits-1)))
7561 // This is neither a signed nor an unsigned comparison, just make sure
7562 // that the high bits are equal.
7563 APInt Op1Zero, Op1One;
7564 APInt Op2Zero, Op2One;
7565 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7566 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7568 // We don't really care about what is known about the first bit (if
7569 // anything), so clear it in all masks prior to comparing them.
7570 Op1Zero.clearBit(0); Op1One.clearBit(0);
7571 Op2Zero.clearBit(0); Op2One.clearBit(0);
7573 if (Op1Zero != Op2Zero || Op1One != Op2One)
7578 // We now know that the higher-order bits are irrelevant, we just need to
7579 // make sure that all of the intermediate operations are bit operations, and
7580 // all inputs are extensions.
7581 if (N->getOperand(0).getOpcode() != ISD::AND &&
7582 N->getOperand(0).getOpcode() != ISD::OR &&
7583 N->getOperand(0).getOpcode() != ISD::XOR &&
7584 N->getOperand(0).getOpcode() != ISD::SELECT &&
7585 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7586 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7587 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7588 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7589 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7592 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7593 N->getOperand(1).getOpcode() != ISD::AND &&
7594 N->getOperand(1).getOpcode() != ISD::OR &&
7595 N->getOperand(1).getOpcode() != ISD::XOR &&
7596 N->getOperand(1).getOpcode() != ISD::SELECT &&
7597 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7598 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7599 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7600 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7601 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7604 SmallVector<SDValue, 4> Inputs;
7605 SmallVector<SDValue, 8> BinOps, PromOps;
7606 SmallPtrSet<SDNode *, 16> Visited;
7608 for (unsigned i = 0; i < 2; ++i) {
7609 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7610 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7611 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7612 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7613 isa<ConstantSDNode>(N->getOperand(i)))
7614 Inputs.push_back(N->getOperand(i));
7616 BinOps.push_back(N->getOperand(i));
7618 if (N->getOpcode() == ISD::TRUNCATE)
7622 // Visit all inputs, collect all binary operations (and, or, xor and
7623 // select) that are all fed by extensions.
7624 while (!BinOps.empty()) {
7625 SDValue BinOp = BinOps.back();
7628 if (!Visited.insert(BinOp.getNode()))
7631 PromOps.push_back(BinOp);
7633 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7634 // The condition of the select is not promoted.
7635 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7637 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7640 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7641 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7642 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7643 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7644 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7645 Inputs.push_back(BinOp.getOperand(i));
7646 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7647 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7648 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7649 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7650 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7651 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7652 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7653 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7654 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7655 BinOps.push_back(BinOp.getOperand(i));
7657 // We have an input that is not an extension or another binary
7658 // operation; we'll abort this transformation.
7664 // Make sure that this is a self-contained cluster of operations (which
7665 // is not quite the same thing as saying that everything has only one
7667 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7668 if (isa<ConstantSDNode>(Inputs[i]))
7671 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7672 UE = Inputs[i].getNode()->use_end();
7675 if (User != N && !Visited.count(User))
7678 // Make sure that we're not going to promote the non-output-value
7679 // operand(s) or SELECT or SELECT_CC.
7680 // FIXME: Although we could sometimes handle this, and it does occur in
7681 // practice that one of the condition inputs to the select is also one of
7682 // the outputs, we currently can't deal with this.
7683 if (User->getOpcode() == ISD::SELECT) {
7684 if (User->getOperand(0) == Inputs[i])
7686 } else if (User->getOpcode() == ISD::SELECT_CC) {
7687 if (User->getOperand(0) == Inputs[i] ||
7688 User->getOperand(1) == Inputs[i])
7694 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7695 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7696 UE = PromOps[i].getNode()->use_end();
7699 if (User != N && !Visited.count(User))
7702 // Make sure that we're not going to promote the non-output-value
7703 // operand(s) or SELECT or SELECT_CC.
7704 // FIXME: Although we could sometimes handle this, and it does occur in
7705 // practice that one of the condition inputs to the select is also one of
7706 // the outputs, we currently can't deal with this.
7707 if (User->getOpcode() == ISD::SELECT) {
7708 if (User->getOperand(0) == PromOps[i])
7710 } else if (User->getOpcode() == ISD::SELECT_CC) {
7711 if (User->getOperand(0) == PromOps[i] ||
7712 User->getOperand(1) == PromOps[i])
7718 // Replace all inputs with the extension operand.
7719 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7720 // Constants may have users outside the cluster of to-be-promoted nodes,
7721 // and so we need to replace those as we do the promotions.
7722 if (isa<ConstantSDNode>(Inputs[i]))
7725 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7728 // Replace all operations (these are all the same, but have a different
7729 // (i1) return type). DAG.getNode will validate that the types of
7730 // a binary operator match, so go through the list in reverse so that
7731 // we've likely promoted both operands first. Any intermediate truncations or
7732 // extensions disappear.
7733 while (!PromOps.empty()) {
7734 SDValue PromOp = PromOps.back();
7737 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7738 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7739 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7740 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7741 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7742 PromOp.getOperand(0).getValueType() != MVT::i1) {
7743 // The operand is not yet ready (see comment below).
7744 PromOps.insert(PromOps.begin(), PromOp);
7748 SDValue RepValue = PromOp.getOperand(0);
7749 if (isa<ConstantSDNode>(RepValue))
7750 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7752 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7757 switch (PromOp.getOpcode()) {
7758 default: C = 0; break;
7759 case ISD::SELECT: C = 1; break;
7760 case ISD::SELECT_CC: C = 2; break;
7763 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7764 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7765 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7766 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7767 // The to-be-promoted operands of this node have not yet been
7768 // promoted (this should be rare because we're going through the
7769 // list backward, but if one of the operands has several users in
7770 // this cluster of to-be-promoted nodes, it is possible).
7771 PromOps.insert(PromOps.begin(), PromOp);
7775 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7776 PromOp.getNode()->op_end());
7778 // If there are any constant inputs, make sure they're replaced now.
7779 for (unsigned i = 0; i < 2; ++i)
7780 if (isa<ConstantSDNode>(Ops[C+i]))
7781 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7783 DAG.ReplaceAllUsesOfValueWith(PromOp,
7784 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7787 // Now we're left with the initial truncation itself.
7788 if (N->getOpcode() == ISD::TRUNCATE)
7789 return N->getOperand(0);
7791 // Otherwise, this is a comparison. The operands to be compared have just
7792 // changed type (to i1), but everything else is the same.
7793 return SDValue(N, 0);
7796 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7797 DAGCombinerInfo &DCI) const {
7798 SelectionDAG &DAG = DCI.DAG;
7801 // If we're tracking CR bits, we need to be careful that we don't have:
7802 // zext(binary-ops(trunc(x), trunc(y)))
7804 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7805 // such that we're unnecessarily moving things into CR bits that can more
7806 // efficiently stay in GPRs. Note that if we're not certain that the high
7807 // bits are set as required by the final extension, we still may need to do
7808 // some masking to get the proper behavior.
7810 // This same functionality is important on PPC64 when dealing with
7811 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7812 // the return values of functions. Because it is so similar, it is handled
7815 if (N->getValueType(0) != MVT::i32 &&
7816 N->getValueType(0) != MVT::i64)
7819 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7820 Subtarget.useCRBits()) ||
7821 (N->getOperand(0).getValueType() == MVT::i32 &&
7822 Subtarget.isPPC64())))
7825 if (N->getOperand(0).getOpcode() != ISD::AND &&
7826 N->getOperand(0).getOpcode() != ISD::OR &&
7827 N->getOperand(0).getOpcode() != ISD::XOR &&
7828 N->getOperand(0).getOpcode() != ISD::SELECT &&
7829 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7832 SmallVector<SDValue, 4> Inputs;
7833 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7834 SmallPtrSet<SDNode *, 16> Visited;
7836 // Visit all inputs, collect all binary operations (and, or, xor and
7837 // select) that are all fed by truncations.
7838 while (!BinOps.empty()) {
7839 SDValue BinOp = BinOps.back();
7842 if (!Visited.insert(BinOp.getNode()))
7845 PromOps.push_back(BinOp);
7847 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7848 // The condition of the select is not promoted.
7849 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7851 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7854 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7855 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7856 Inputs.push_back(BinOp.getOperand(i));
7857 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7858 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7859 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7860 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7861 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7862 BinOps.push_back(BinOp.getOperand(i));
7864 // We have an input that is not a truncation or another binary
7865 // operation; we'll abort this transformation.
7871 // Make sure that this is a self-contained cluster of operations (which
7872 // is not quite the same thing as saying that everything has only one
7874 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7875 if (isa<ConstantSDNode>(Inputs[i]))
7878 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7879 UE = Inputs[i].getNode()->use_end();
7882 if (User != N && !Visited.count(User))
7885 // Make sure that we're not going to promote the non-output-value
7886 // operand(s) or SELECT or SELECT_CC.
7887 // FIXME: Although we could sometimes handle this, and it does occur in
7888 // practice that one of the condition inputs to the select is also one of
7889 // the outputs, we currently can't deal with this.
7890 if (User->getOpcode() == ISD::SELECT) {
7891 if (User->getOperand(0) == Inputs[i])
7893 } else if (User->getOpcode() == ISD::SELECT_CC) {
7894 if (User->getOperand(0) == Inputs[i] ||
7895 User->getOperand(1) == Inputs[i])
7901 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7902 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7903 UE = PromOps[i].getNode()->use_end();
7906 if (User != N && !Visited.count(User))
7909 // Make sure that we're not going to promote the non-output-value
7910 // operand(s) or SELECT or SELECT_CC.
7911 // FIXME: Although we could sometimes handle this, and it does occur in
7912 // practice that one of the condition inputs to the select is also one of
7913 // the outputs, we currently can't deal with this.
7914 if (User->getOpcode() == ISD::SELECT) {
7915 if (User->getOperand(0) == PromOps[i])
7917 } else if (User->getOpcode() == ISD::SELECT_CC) {
7918 if (User->getOperand(0) == PromOps[i] ||
7919 User->getOperand(1) == PromOps[i])
7925 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7926 bool ReallyNeedsExt = false;
7927 if (N->getOpcode() != ISD::ANY_EXTEND) {
7928 // If all of the inputs are not already sign/zero extended, then
7929 // we'll still need to do that at the end.
7930 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7931 if (isa<ConstantSDNode>(Inputs[i]))
7935 Inputs[i].getOperand(0).getValueSizeInBits();
7936 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7938 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7939 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7940 APInt::getHighBitsSet(OpBits,
7941 OpBits-PromBits))) ||
7942 (N->getOpcode() == ISD::SIGN_EXTEND &&
7943 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7944 (OpBits-(PromBits-1)))) {
7945 ReallyNeedsExt = true;
7951 // Replace all inputs, either with the truncation operand, or a
7952 // truncation or extension to the final output type.
7953 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7954 // Constant inputs need to be replaced with the to-be-promoted nodes that
7955 // use them because they might have users outside of the cluster of
7957 if (isa<ConstantSDNode>(Inputs[i]))
7960 SDValue InSrc = Inputs[i].getOperand(0);
7961 if (Inputs[i].getValueType() == N->getValueType(0))
7962 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7963 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7964 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7965 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7966 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7967 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7968 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7970 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7971 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7974 // Replace all operations (these are all the same, but have a different
7975 // (promoted) return type). DAG.getNode will validate that the types of
7976 // a binary operator match, so go through the list in reverse so that
7977 // we've likely promoted both operands first.
7978 while (!PromOps.empty()) {
7979 SDValue PromOp = PromOps.back();
7983 switch (PromOp.getOpcode()) {
7984 default: C = 0; break;
7985 case ISD::SELECT: C = 1; break;
7986 case ISD::SELECT_CC: C = 2; break;
7989 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7990 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7991 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7992 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7993 // The to-be-promoted operands of this node have not yet been
7994 // promoted (this should be rare because we're going through the
7995 // list backward, but if one of the operands has several users in
7996 // this cluster of to-be-promoted nodes, it is possible).
7997 PromOps.insert(PromOps.begin(), PromOp);
8001 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8002 PromOp.getNode()->op_end());
8004 // If this node has constant inputs, then they'll need to be promoted here.
8005 for (unsigned i = 0; i < 2; ++i) {
8006 if (!isa<ConstantSDNode>(Ops[C+i]))
8008 if (Ops[C+i].getValueType() == N->getValueType(0))
8011 if (N->getOpcode() == ISD::SIGN_EXTEND)
8012 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8013 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8014 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8016 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8019 DAG.ReplaceAllUsesOfValueWith(PromOp,
8020 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8023 // Now we're left with the initial extension itself.
8024 if (!ReallyNeedsExt)
8025 return N->getOperand(0);
8027 // To zero extend, just mask off everything except for the first bit (in the
8029 if (N->getOpcode() == ISD::ZERO_EXTEND)
8030 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8031 DAG.getConstant(APInt::getLowBitsSet(
8032 N->getValueSizeInBits(0), PromBits),
8033 N->getValueType(0)));
8035 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8036 "Invalid extension type");
8037 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8039 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8040 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
8041 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8042 N->getOperand(0), ShiftCst), ShiftCst);
8045 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8046 DAGCombinerInfo &DCI) const {
8047 const TargetMachine &TM = getTargetMachine();
8048 SelectionDAG &DAG = DCI.DAG;
8050 switch (N->getOpcode()) {
8053 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8054 if (C->isNullValue()) // 0 << V -> 0.
8055 return N->getOperand(0);
8059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8060 if (C->isNullValue()) // 0 >>u V -> 0.
8061 return N->getOperand(0);
8065 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8066 if (C->isNullValue() || // 0 >>s V -> 0.
8067 C->isAllOnesValue()) // -1 >>s V -> -1.
8068 return N->getOperand(0);
8071 case ISD::SIGN_EXTEND:
8072 case ISD::ZERO_EXTEND:
8073 case ISD::ANY_EXTEND:
8074 return DAGCombineExtBoolTrunc(N, DCI);
8077 case ISD::SELECT_CC:
8078 return DAGCombineTruncBoolExt(N, DCI);
8080 assert(TM.Options.UnsafeFPMath &&
8081 "Reciprocal estimates require UnsafeFPMath");
8083 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
8085 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
8087 DCI.AddToWorklist(RV.getNode());
8088 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8089 N->getOperand(0), RV);
8091 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
8092 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8094 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8097 DCI.AddToWorklist(RV.getNode());
8098 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
8099 N->getValueType(0), RV);
8100 DCI.AddToWorklist(RV.getNode());
8101 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8102 N->getOperand(0), RV);
8104 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
8105 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8107 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8110 DCI.AddToWorklist(RV.getNode());
8111 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
8112 N->getValueType(0), RV,
8113 N->getOperand(1).getOperand(1));
8114 DCI.AddToWorklist(RV.getNode());
8115 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8116 N->getOperand(0), RV);
8120 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
8122 DCI.AddToWorklist(RV.getNode());
8123 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8124 N->getOperand(0), RV);
8130 assert(TM.Options.UnsafeFPMath &&
8131 "Reciprocal estimates require UnsafeFPMath");
8133 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
8135 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
8137 DCI.AddToWorklist(RV.getNode());
8138 RV = DAGCombineFastRecip(RV, DCI);
8140 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
8141 // this case and force the answer to 0.
8143 EVT VT = RV.getValueType();
8145 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
8146 if (VT.isVector()) {
8147 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
8148 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
8152 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
8153 N->getOperand(0), Zero, ISD::SETEQ);
8154 DCI.AddToWorklist(ZeroCmp.getNode());
8155 DCI.AddToWorklist(RV.getNode());
8157 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
8165 case ISD::SINT_TO_FP:
8166 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8167 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8168 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8169 // We allow the src/dst to be either f32/f64, but the intermediate
8170 // type must be i64.
8171 if (N->getOperand(0).getValueType() == MVT::i64 &&
8172 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8173 SDValue Val = N->getOperand(0).getOperand(0);
8174 if (Val.getValueType() == MVT::f32) {
8175 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8176 DCI.AddToWorklist(Val.getNode());
8179 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8180 DCI.AddToWorklist(Val.getNode());
8181 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8182 DCI.AddToWorklist(Val.getNode());
8183 if (N->getValueType(0) == MVT::f32) {
8184 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8185 DAG.getIntPtrConstant(0));
8186 DCI.AddToWorklist(Val.getNode());
8189 } else if (N->getOperand(0).getValueType() == MVT::i32) {
8190 // If the intermediate type is i32, we can avoid the load/store here
8197 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8198 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8199 !cast<StoreSDNode>(N)->isTruncatingStore() &&
8200 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8201 N->getOperand(1).getValueType() == MVT::i32 &&
8202 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8203 SDValue Val = N->getOperand(1).getOperand(0);
8204 if (Val.getValueType() == MVT::f32) {
8205 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8206 DCI.AddToWorklist(Val.getNode());
8208 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8209 DCI.AddToWorklist(Val.getNode());
8212 N->getOperand(0), Val, N->getOperand(2),
8213 DAG.getValueType(N->getOperand(1).getValueType())
8216 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8217 DAG.getVTList(MVT::Other), Ops,
8218 cast<StoreSDNode>(N)->getMemoryVT(),
8219 cast<StoreSDNode>(N)->getMemOperand());
8220 DCI.AddToWorklist(Val.getNode());
8224 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8225 if (cast<StoreSDNode>(N)->isUnindexed() &&
8226 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8227 N->getOperand(1).getNode()->hasOneUse() &&
8228 (N->getOperand(1).getValueType() == MVT::i32 ||
8229 N->getOperand(1).getValueType() == MVT::i16 ||
8230 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8231 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8232 N->getOperand(1).getValueType() == MVT::i64))) {
8233 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8234 // Do an any-extend to 32-bits if this is a half-word input.
8235 if (BSwapOp.getValueType() == MVT::i16)
8236 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8239 N->getOperand(0), BSwapOp, N->getOperand(2),
8240 DAG.getValueType(N->getOperand(1).getValueType())
8243 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8244 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8245 cast<StoreSDNode>(N)->getMemOperand());
8249 LoadSDNode *LD = cast<LoadSDNode>(N);
8250 EVT VT = LD->getValueType(0);
8251 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8252 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8253 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8254 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8255 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8256 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8257 LD->getAlignment() < ABIAlignment) {
8258 // This is a type-legal unaligned Altivec load.
8259 SDValue Chain = LD->getChain();
8260 SDValue Ptr = LD->getBasePtr();
8261 bool isLittleEndian = Subtarget.isLittleEndian();
8263 // This implements the loading of unaligned vectors as described in
8264 // the venerable Apple Velocity Engine overview. Specifically:
8265 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8266 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8268 // The general idea is to expand a sequence of one or more unaligned
8269 // loads into an alignment-based permutation-control instruction (lvsl
8270 // or lvsr), a series of regular vector loads (which always truncate
8271 // their input address to an aligned address), and a series of
8272 // permutations. The results of these permutations are the requested
8273 // loaded values. The trick is that the last "extra" load is not taken
8274 // from the address you might suspect (sizeof(vector) bytes after the
8275 // last requested load), but rather sizeof(vector) - 1 bytes after the
8276 // last requested vector. The point of this is to avoid a page fault if
8277 // the base address happened to be aligned. This works because if the
8278 // base address is aligned, then adding less than a full vector length
8279 // will cause the last vector in the sequence to be (re)loaded.
8280 // Otherwise, the next vector will be fetched as you might suspect was
8283 // We might be able to reuse the permutation generation from
8284 // a different base address offset from this one by an aligned amount.
8285 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8286 // optimization later.
8287 Intrinsic::ID Intr = (isLittleEndian ?
8288 Intrinsic::ppc_altivec_lvsr :
8289 Intrinsic::ppc_altivec_lvsl);
8290 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8292 // Refine the alignment of the original load (a "new" load created here
8293 // which was identical to the first except for the alignment would be
8294 // merged with the existing node regardless).
8295 MachineFunction &MF = DAG.getMachineFunction();
8296 MachineMemOperand *MMO =
8297 MF.getMachineMemOperand(LD->getPointerInfo(),
8298 LD->getMemOperand()->getFlags(),
8299 LD->getMemoryVT().getStoreSize(),
8301 LD->refineAlignment(MMO);
8302 SDValue BaseLoad = SDValue(LD, 0);
8304 // Note that the value of IncOffset (which is provided to the next
8305 // load's pointer info offset value, and thus used to calculate the
8306 // alignment), and the value of IncValue (which is actually used to
8307 // increment the pointer value) are different! This is because we
8308 // require the next load to appear to be aligned, even though it
8309 // is actually offset from the base pointer by a lesser amount.
8310 int IncOffset = VT.getSizeInBits() / 8;
8311 int IncValue = IncOffset;
8313 // Walk (both up and down) the chain looking for another load at the real
8314 // (aligned) offset (the alignment of the other load does not matter in
8315 // this case). If found, then do not use the offset reduction trick, as
8316 // that will prevent the loads from being later combined (as they would
8317 // otherwise be duplicates).
8318 if (!findConsecutiveLoad(LD, DAG))
8321 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8322 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8325 DAG.getLoad(VT, dl, Chain, Ptr,
8326 LD->getPointerInfo().getWithOffset(IncOffset),
8327 LD->isVolatile(), LD->isNonTemporal(),
8328 LD->isInvariant(), ABIAlignment);
8330 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8331 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8333 if (BaseLoad.getValueType() != MVT::v4i32)
8334 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8336 if (ExtraLoad.getValueType() != MVT::v4i32)
8337 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8339 // Because vperm has a big-endian bias, we must reverse the order
8340 // of the input vectors and complement the permute control vector
8341 // when generating little endian code. We have already handled the
8342 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8343 // and ExtraLoad here.
8346 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8347 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8349 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8350 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8352 if (VT != MVT::v4i32)
8353 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8355 // Now we need to be really careful about how we update the users of the
8356 // original load. We cannot just call DCI.CombineTo (or
8357 // DAG.ReplaceAllUsesWith for that matter), because the load still has
8358 // uses created here (the permutation for example) that need to stay.
8359 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8361 SDUse &Use = UI.getUse();
8363 // Note: BaseLoad is checked here because it might not be N, but a
8365 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8366 User == TF.getNode() || Use.getResNo() > 1) {
8371 SDValue To = Use.getResNo() ? TF : Perm;
8374 SmallVector<SDValue, 8> Ops;
8375 for (const SDUse &O : User->ops()) {
8382 DAG.UpdateNodeOperands(User, Ops);
8385 return SDValue(N, 0);
8389 case ISD::INTRINSIC_WO_CHAIN: {
8390 bool isLittleEndian = Subtarget.isLittleEndian();
8391 Intrinsic::ID Intr = (isLittleEndian ?
8392 Intrinsic::ppc_altivec_lvsr :
8393 Intrinsic::ppc_altivec_lvsl);
8394 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8395 N->getOperand(1)->getOpcode() == ISD::ADD) {
8396 SDValue Add = N->getOperand(1);
8398 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8399 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8400 Add.getValueType().getScalarType().getSizeInBits()))) {
8401 SDNode *BasePtr = Add->getOperand(0).getNode();
8402 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8403 UE = BasePtr->use_end(); UI != UE; ++UI) {
8404 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8405 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8407 // We've found another LVSL/LVSR, and this address is an aligned
8408 // multiple of that one. The results will be the same, so use the
8409 // one we've just found instead.
8411 return SDValue(*UI, 0);
8420 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8421 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8422 N->getOperand(0).hasOneUse() &&
8423 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8424 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8425 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8426 N->getValueType(0) == MVT::i64))) {
8427 SDValue Load = N->getOperand(0);
8428 LoadSDNode *LD = cast<LoadSDNode>(Load);
8429 // Create the byte-swapping load.
8431 LD->getChain(), // Chain
8432 LD->getBasePtr(), // Ptr
8433 DAG.getValueType(N->getValueType(0)) // VT
8436 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8437 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8438 MVT::i64 : MVT::i32, MVT::Other),
8439 Ops, LD->getMemoryVT(), LD->getMemOperand());
8441 // If this is an i16 load, insert the truncate.
8442 SDValue ResVal = BSLoad;
8443 if (N->getValueType(0) == MVT::i16)
8444 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8446 // First, combine the bswap away. This makes the value produced by the
8448 DCI.CombineTo(N, ResVal);
8450 // Next, combine the load away, we give it a bogus result value but a real
8451 // chain result. The result value is dead because the bswap is dead.
8452 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8454 // Return N so it doesn't get rechecked!
8455 return SDValue(N, 0);
8459 case PPCISD::VCMP: {
8460 // If a VCMPo node already exists with exactly the same operands as this
8461 // node, use its result instead of this node (VCMPo computes both a CR6 and
8462 // a normal output).
8464 if (!N->getOperand(0).hasOneUse() &&
8465 !N->getOperand(1).hasOneUse() &&
8466 !N->getOperand(2).hasOneUse()) {
8468 // Scan all of the users of the LHS, looking for VCMPo's that match.
8469 SDNode *VCMPoNode = nullptr;
8471 SDNode *LHSN = N->getOperand(0).getNode();
8472 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8474 if (UI->getOpcode() == PPCISD::VCMPo &&
8475 UI->getOperand(1) == N->getOperand(1) &&
8476 UI->getOperand(2) == N->getOperand(2) &&
8477 UI->getOperand(0) == N->getOperand(0)) {
8482 // If there is no VCMPo node, or if the flag value has a single use, don't
8484 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8487 // Look at the (necessarily single) use of the flag value. If it has a
8488 // chain, this transformation is more complex. Note that multiple things
8489 // could use the value result, which we should ignore.
8490 SDNode *FlagUser = nullptr;
8491 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8492 FlagUser == nullptr; ++UI) {
8493 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8495 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8496 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8503 // If the user is a MFOCRF instruction, we know this is safe.
8504 // Otherwise we give up for right now.
8505 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8506 return SDValue(VCMPoNode, 0);
8511 SDValue Cond = N->getOperand(1);
8512 SDValue Target = N->getOperand(2);
8514 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8515 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8516 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8518 // We now need to make the intrinsic dead (it cannot be instruction
8520 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8521 assert(Cond.getNode()->hasOneUse() &&
8522 "Counter decrement has more than one use");
8524 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8525 N->getOperand(0), Target);
8530 // If this is a branch on an altivec predicate comparison, lower this so
8531 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8532 // lowering is done pre-legalize, because the legalizer lowers the predicate
8533 // compare down to code that is difficult to reassemble.
8534 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8535 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8537 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8538 // value. If so, pass-through the AND to get to the intrinsic.
8539 if (LHS.getOpcode() == ISD::AND &&
8540 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8541 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8542 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8543 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8544 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8546 LHS = LHS.getOperand(0);
8548 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8549 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8550 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8551 isa<ConstantSDNode>(RHS)) {
8552 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8553 "Counter decrement comparison is not EQ or NE");
8555 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8556 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8557 (CC == ISD::SETNE && !Val);
8559 // We now need to make the intrinsic dead (it cannot be instruction
8561 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8562 assert(LHS.getNode()->hasOneUse() &&
8563 "Counter decrement has more than one use");
8565 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8566 N->getOperand(0), N->getOperand(4));
8572 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8573 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8574 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8575 assert(isDot && "Can't compare against a vector result!");
8577 // If this is a comparison against something other than 0/1, then we know
8578 // that the condition is never/always true.
8579 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8580 if (Val != 0 && Val != 1) {
8581 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8582 return N->getOperand(0);
8583 // Always !=, turn it into an unconditional branch.
8584 return DAG.getNode(ISD::BR, dl, MVT::Other,
8585 N->getOperand(0), N->getOperand(4));
8588 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8590 // Create the PPCISD altivec 'dot' comparison node.
8592 LHS.getOperand(2), // LHS of compare
8593 LHS.getOperand(3), // RHS of compare
8594 DAG.getConstant(CompareOpc, MVT::i32)
8596 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8597 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8599 // Unpack the result based on how the target uses it.
8600 PPC::Predicate CompOpc;
8601 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8602 default: // Can't happen, don't crash on invalid number though.
8603 case 0: // Branch on the value of the EQ bit of CR6.
8604 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8606 case 1: // Branch on the inverted value of the EQ bit of CR6.
8607 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8609 case 2: // Branch on the value of the LT bit of CR6.
8610 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8612 case 3: // Branch on the inverted value of the LT bit of CR6.
8613 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8617 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8618 DAG.getConstant(CompOpc, MVT::i32),
8619 DAG.getRegister(PPC::CR6, MVT::i32),
8620 N->getOperand(4), CompNode.getValue(1));
8629 //===----------------------------------------------------------------------===//
8630 // Inline Assembly Support
8631 //===----------------------------------------------------------------------===//
8633 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8636 const SelectionDAG &DAG,
8637 unsigned Depth) const {
8638 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8639 switch (Op.getOpcode()) {
8641 case PPCISD::LBRX: {
8642 // lhbrx is known to have the top bits cleared out.
8643 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8644 KnownZero = 0xFFFF0000;
8647 case ISD::INTRINSIC_WO_CHAIN: {
8648 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8650 case Intrinsic::ppc_altivec_vcmpbfp_p:
8651 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8652 case Intrinsic::ppc_altivec_vcmpequb_p:
8653 case Intrinsic::ppc_altivec_vcmpequh_p:
8654 case Intrinsic::ppc_altivec_vcmpequw_p:
8655 case Intrinsic::ppc_altivec_vcmpgefp_p:
8656 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8657 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8658 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8659 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8660 case Intrinsic::ppc_altivec_vcmpgtub_p:
8661 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8662 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8663 KnownZero = ~1U; // All bits but the low one are known to be zero.
8671 /// getConstraintType - Given a constraint, return the type of
8672 /// constraint it is for this target.
8673 PPCTargetLowering::ConstraintType
8674 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8675 if (Constraint.size() == 1) {
8676 switch (Constraint[0]) {
8683 return C_RegisterClass;
8685 // FIXME: While Z does indicate a memory constraint, it specifically
8686 // indicates an r+r address (used in conjunction with the 'y' modifier
8687 // in the replacement string). Currently, we're forcing the base
8688 // register to be r0 in the asm printer (which is interpreted as zero)
8689 // and forming the complete address in the second register. This is
8693 } else if (Constraint == "wc") { // individual CR bits.
8694 return C_RegisterClass;
8695 } else if (Constraint == "wa" || Constraint == "wd" ||
8696 Constraint == "wf" || Constraint == "ws") {
8697 return C_RegisterClass; // VSX registers.
8699 return TargetLowering::getConstraintType(Constraint);
8702 /// Examine constraint type and operand type and determine a weight value.
8703 /// This object must already have been set up with the operand type
8704 /// and the current alternative constraint selected.
8705 TargetLowering::ConstraintWeight
8706 PPCTargetLowering::getSingleConstraintMatchWeight(
8707 AsmOperandInfo &info, const char *constraint) const {
8708 ConstraintWeight weight = CW_Invalid;
8709 Value *CallOperandVal = info.CallOperandVal;
8710 // If we don't have a value, we can't do a match,
8711 // but allow it at the lowest weight.
8712 if (!CallOperandVal)
8714 Type *type = CallOperandVal->getType();
8716 // Look at the constraint type.
8717 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8718 return CW_Register; // an individual CR bit.
8719 else if ((StringRef(constraint) == "wa" ||
8720 StringRef(constraint) == "wd" ||
8721 StringRef(constraint) == "wf") &&
8724 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8727 switch (*constraint) {
8729 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8732 if (type->isIntegerTy())
8733 weight = CW_Register;
8736 if (type->isFloatTy())
8737 weight = CW_Register;
8740 if (type->isDoubleTy())
8741 weight = CW_Register;
8744 if (type->isVectorTy())
8745 weight = CW_Register;
8748 weight = CW_Register;
8757 std::pair<unsigned, const TargetRegisterClass*>
8758 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8760 if (Constraint.size() == 1) {
8761 // GCC RS6000 Constraint Letters
8762 switch (Constraint[0]) {
8764 if (VT == MVT::i64 && Subtarget.isPPC64())
8765 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8766 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8768 if (VT == MVT::i64 && Subtarget.isPPC64())
8769 return std::make_pair(0U, &PPC::G8RCRegClass);
8770 return std::make_pair(0U, &PPC::GPRCRegClass);
8772 if (VT == MVT::f32 || VT == MVT::i32)
8773 return std::make_pair(0U, &PPC::F4RCRegClass);
8774 if (VT == MVT::f64 || VT == MVT::i64)
8775 return std::make_pair(0U, &PPC::F8RCRegClass);
8778 return std::make_pair(0U, &PPC::VRRCRegClass);
8780 return std::make_pair(0U, &PPC::CRRCRegClass);
8782 } else if (Constraint == "wc") { // an individual CR bit.
8783 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8784 } else if (Constraint == "wa" || Constraint == "wd" ||
8785 Constraint == "wf") {
8786 return std::make_pair(0U, &PPC::VSRCRegClass);
8787 } else if (Constraint == "ws") {
8788 return std::make_pair(0U, &PPC::VSFRCRegClass);
8791 std::pair<unsigned, const TargetRegisterClass*> R =
8792 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8794 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8795 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8796 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8798 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8799 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8800 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
8801 PPC::GPRCRegClass.contains(R.first)) {
8802 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8803 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8804 PPC::sub_32, &PPC::G8RCRegClass),
8805 &PPC::G8RCRegClass);
8812 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8813 /// vector. If it is invalid, don't add anything to Ops.
8814 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8815 std::string &Constraint,
8816 std::vector<SDValue>&Ops,
8817 SelectionDAG &DAG) const {
8820 // Only support length 1 constraints.
8821 if (Constraint.length() > 1) return;
8823 char Letter = Constraint[0];
8834 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8835 if (!CST) return; // Must be an immediate to match.
8836 unsigned Value = CST->getZExtValue();
8838 default: llvm_unreachable("Unknown constraint letter!");
8839 case 'I': // "I" is a signed 16-bit constant.
8840 if ((short)Value == (int)Value)
8841 Result = DAG.getTargetConstant(Value, Op.getValueType());
8843 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8844 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8845 if ((short)Value == 0)
8846 Result = DAG.getTargetConstant(Value, Op.getValueType());
8848 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8849 if ((Value >> 16) == 0)
8850 Result = DAG.getTargetConstant(Value, Op.getValueType());
8852 case 'M': // "M" is a constant that is greater than 31.
8854 Result = DAG.getTargetConstant(Value, Op.getValueType());
8856 case 'N': // "N" is a positive constant that is an exact power of two.
8857 if ((int)Value > 0 && isPowerOf2_32(Value))
8858 Result = DAG.getTargetConstant(Value, Op.getValueType());
8860 case 'O': // "O" is the constant zero.
8862 Result = DAG.getTargetConstant(Value, Op.getValueType());
8864 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8865 if ((short)-Value == (int)-Value)
8866 Result = DAG.getTargetConstant(Value, Op.getValueType());
8873 if (Result.getNode()) {
8874 Ops.push_back(Result);
8878 // Handle standard constraint letters.
8879 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8882 // isLegalAddressingMode - Return true if the addressing mode represented
8883 // by AM is legal for this target, for a load/store of the specified type.
8884 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8886 // FIXME: PPC does not allow r+i addressing modes for vectors!
8888 // PPC allows a sign-extended 16-bit immediate field.
8889 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8892 // No global is ever allowed as a base.
8896 // PPC only support r+r,
8898 case 0: // "r+i" or just "i", depending on HasBaseReg.
8901 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8903 // Otherwise we have r+r or r+i.
8906 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8908 // Allow 2*r as r+r.
8911 // No other scales are supported.
8918 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8919 SelectionDAG &DAG) const {
8920 MachineFunction &MF = DAG.getMachineFunction();
8921 MachineFrameInfo *MFI = MF.getFrameInfo();
8922 MFI->setReturnAddressIsTaken(true);
8924 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8928 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8930 // Make sure the function does not optimize away the store of the RA to
8932 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8933 FuncInfo->setLRStoreRequired();
8934 bool isPPC64 = Subtarget.isPPC64();
8935 bool isDarwinABI = Subtarget.isDarwinABI();
8938 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8941 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8942 isPPC64? MVT::i64 : MVT::i32);
8943 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8944 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8946 MachinePointerInfo(), false, false, false, 0);
8949 // Just load the return address off the stack.
8950 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8951 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8952 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8955 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8956 SelectionDAG &DAG) const {
8958 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8960 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8961 bool isPPC64 = PtrVT == MVT::i64;
8963 MachineFunction &MF = DAG.getMachineFunction();
8964 MachineFrameInfo *MFI = MF.getFrameInfo();
8965 MFI->setFrameAddressIsTaken(true);
8967 // Naked functions never have a frame pointer, and so we use r1. For all
8968 // other functions, this decision must be delayed until during PEI.
8970 if (MF.getFunction()->getAttributes().hasAttribute(
8971 AttributeSet::FunctionIndex, Attribute::Naked))
8972 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8974 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8976 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8979 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8980 FrameAddr, MachinePointerInfo(), false, false,
8985 // FIXME? Maybe this could be a TableGen attribute on some registers and
8986 // this table could be generated automatically from RegInfo.
8987 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
8989 bool isPPC64 = Subtarget.isPPC64();
8990 bool isDarwinABI = Subtarget.isDarwinABI();
8992 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
8993 (!isPPC64 && VT != MVT::i32))
8994 report_fatal_error("Invalid register global variable type");
8996 bool is64Bit = isPPC64 && VT == MVT::i64;
8997 unsigned Reg = StringSwitch<unsigned>(RegName)
8998 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
8999 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9000 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9001 (is64Bit ? PPC::X13 : PPC::R13))
9006 report_fatal_error("Invalid register name global variable");
9010 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9011 // The PowerPC target isn't yet aware of offsets.
9015 /// getOptimalMemOpType - Returns the target specific optimal type for load
9016 /// and store operations as a result of memset, memcpy, and memmove
9017 /// lowering. If DstAlign is zero that means it's safe to destination
9018 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9019 /// means there isn't a need to check it against alignment requirement,
9020 /// probably because the source does not need to be loaded. If 'IsMemset' is
9021 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9022 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9023 /// source is constant so it does not need to be loaded.
9024 /// It returns EVT::Other if the type should be determined using generic
9025 /// target-independent logic.
9026 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9027 unsigned DstAlign, unsigned SrcAlign,
9028 bool IsMemset, bool ZeroMemset,
9030 MachineFunction &MF) const {
9031 if (Subtarget.isPPC64()) {
9038 /// \brief Returns true if it is beneficial to convert a load of a constant
9039 /// to just the constant itself.
9040 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9042 assert(Ty->isIntegerTy());
9044 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9045 if (BitSize == 0 || BitSize > 64)
9050 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9051 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9053 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9054 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9055 return NumBits1 == 64 && NumBits2 == 32;
9058 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9059 if (!VT1.isInteger() || !VT2.isInteger())
9061 unsigned NumBits1 = VT1.getSizeInBits();
9062 unsigned NumBits2 = VT2.getSizeInBits();
9063 return NumBits1 == 64 && NumBits2 == 32;
9066 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9067 return isInt<16>(Imm) || isUInt<16>(Imm);
9070 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9071 return isInt<16>(Imm) || isUInt<16>(Imm);
9074 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
9077 if (DisablePPCUnaligned)
9080 // PowerPC supports unaligned memory access for simple non-vector types.
9081 // Although accessing unaligned addresses is not as efficient as accessing
9082 // aligned addresses, it is generally more efficient than manual expansion,
9083 // and generally only traps for software emulation when crossing page
9089 if (VT.getSimpleVT().isVector()) {
9090 if (Subtarget.hasVSX()) {
9091 if (VT != MVT::v2f64 && VT != MVT::v2i64)
9098 if (VT == MVT::ppcf128)
9107 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9108 VT = VT.getScalarType();
9113 switch (VT.getSimpleVT().SimpleTy) {
9125 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9126 EVT VT , unsigned DefinedValues) const {
9127 if (VT == MVT::v2i64)
9130 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9133 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9134 if (DisableILPPref || Subtarget.enableMachineScheduler())
9135 return TargetLowering::getSchedulingPreference(N);
9140 // Create a fast isel object.
9142 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9143 const TargetLibraryInfo *LibInfo) const {
9144 return PPC::createFastISel(FuncInfo, LibInfo);