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) {
56 return new TargetLoweringObjectFileMachO();
58 return new PPC64LinuxTargetObjectFile();
61 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
62 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))),
63 PPCSubTarget(*TM.getSubtargetImpl()) {
64 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
68 // Use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(true);
70 setUseUnderscoreLongJmp(true);
72 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
73 // arguments are at least 4/8 bytes aligned.
74 bool isPPC64 = Subtarget->isPPC64();
75 setMinStackArgumentAlignment(isPPC64 ? 8:4);
77 // Set up the register classes.
78 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
79 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
80 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
82 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
84 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
86 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
88 // PowerPC has pre-inc load and store's.
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
92 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
93 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
100 if (Subtarget->useCRBits()) {
101 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103 if (isPPC64 || Subtarget->hasFPCVT()) {
104 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
105 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
106 isPPC64 ? MVT::i64 : MVT::i32);
107 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
108 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
109 isPPC64 ? MVT::i64 : MVT::i32);
111 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
112 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
115 // PowerPC does not support direct load / store of condition registers
116 setOperationAction(ISD::LOAD, MVT::i1, Custom);
117 setOperationAction(ISD::STORE, MVT::i1, Custom);
119 // FIXME: Remove this once the ANDI glue bug is fixed:
121 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
126 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
127 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
128 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
133 // This is used in the ppcf128->int sequence. Note it has different semantics
134 // from FP_ROUND: that rounds to nearest, this rounds to zero.
135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137 // We do not currently implement these libm ops for PowerPC.
138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145 // PowerPC has no SREM/UREM instructions
146 setOperationAction(ISD::SREM, MVT::i32, Expand);
147 setOperationAction(ISD::UREM, MVT::i32, Expand);
148 setOperationAction(ISD::SREM, MVT::i64, Expand);
149 setOperationAction(ISD::UREM, MVT::i64, Expand);
151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161 // We don't support sin/cos/sqrt/fmod/pow
162 setOperationAction(ISD::FSIN , MVT::f64, Expand);
163 setOperationAction(ISD::FCOS , MVT::f64, Expand);
164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165 setOperationAction(ISD::FREM , MVT::f64, Expand);
166 setOperationAction(ISD::FPOW , MVT::f64, Expand);
167 setOperationAction(ISD::FMA , MVT::f64, Legal);
168 setOperationAction(ISD::FSIN , MVT::f32, Expand);
169 setOperationAction(ISD::FCOS , MVT::f32, Expand);
170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171 setOperationAction(ISD::FREM , MVT::f32, Expand);
172 setOperationAction(ISD::FPOW , MVT::f32, Expand);
173 setOperationAction(ISD::FMA , MVT::f32, Legal);
175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177 // If we're enabling GP optimizations, use hardware square root
178 if (!Subtarget->hasFSQRT() &&
179 !(TM.Options.UnsafeFPMath &&
180 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
181 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183 if (!Subtarget->hasFSQRT() &&
184 !(TM.Options.UnsafeFPMath &&
185 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
186 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188 if (Subtarget->hasFCPSGN()) {
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
196 if (Subtarget->hasFPRND()) {
197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200 setOperationAction(ISD::FROUND, MVT::f64, Legal);
202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205 setOperationAction(ISD::FROUND, MVT::f32, Legal);
208 // PowerPC does not have BSWAP, CTPOP or CTTZ
209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218 if (Subtarget->hasPOPCNTD()) {
219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
226 // PowerPC does not have ROTR
227 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
228 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
230 if (!Subtarget->useCRBits()) {
231 // PowerPC does not have Select
232 setOperationAction(ISD::SELECT, MVT::i32, Expand);
233 setOperationAction(ISD::SELECT, MVT::i64, Expand);
234 setOperationAction(ISD::SELECT, MVT::f32, Expand);
235 setOperationAction(ISD::SELECT, MVT::f64, Expand);
238 // PowerPC wants to turn select_cc of FP into fsel when possible.
239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 // PowerPC wants to optimize integer setcc a bit
243 if (!Subtarget->useCRBits())
244 setOperationAction(ISD::SETCC, MVT::i32, Custom);
246 // PowerPC does not have BRCOND which requires SetCC
247 if (!Subtarget->useCRBits())
248 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 // PowerPC does not have [U|S]INT_TO_FP
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264 // We cannot sextinreg(i1). Expand to shifts.
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269 // support continuation, user-level threading, and etc.. As a result, no
270 // other SjLj exception interfaces are implemented and please don't build
271 // your own exception handling based on them.
272 // LLVM/Clang supports zero-cost DWARF exception handling.
273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276 // We want to legalize GlobalAddress and ConstantPool nodes into the
277 // appropriate instructions to materialize the address.
278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
282 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
287 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
292 // TRAMPOLINE is custom lowered.
293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 if (Subtarget->isSVR4ABI()) {
301 // VAARG always uses double-word chunks, so promote anything smaller.
302 setOperationAction(ISD::VAARG, MVT::i1, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i8, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i16, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::i32, Promote);
309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310 setOperationAction(ISD::VAARG, MVT::Other, Expand);
312 // VAARG is custom lowered with the 32-bit SVR4 ABI.
313 setOperationAction(ISD::VAARG, MVT::Other, Custom);
314 setOperationAction(ISD::VAARG, MVT::i64, Custom);
317 setOperationAction(ISD::VAARG, MVT::Other, Expand);
319 if (Subtarget->isSVR4ABI() && !isPPC64)
320 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
323 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
325 // Use the default implementation.
326 setOperationAction(ISD::VAEND , MVT::Other, Expand);
327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
332 // We want to custom lower some of our intrinsics.
333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335 // To handle counter-based loop conditions.
336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338 // Comparisons that require checking two conditions.
339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352 if (Subtarget->has64BitSupport()) {
353 // They also have instructions for converting between i64 and fp.
354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358 // This is just the low 32 bits of a (signed) fp->i64 conversion.
359 // We cannot do this with Promote because i64 is not a legal type.
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
369 // With the instructions enabled under FPCVT, we can do everything.
370 if (PPCSubTarget.hasFPCVT()) {
371 if (Subtarget->has64BitSupport()) {
372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
384 if (Subtarget->use64BitRegs()) {
385 // 64-bit PowerPC implementations can support i64 types directly
386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389 // 64-bit PowerPC wants to expand i128 shifts itself.
390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394 // 32-bit PowerPC wants to expand i64 shifts itself.
395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
400 if (Subtarget->hasAltivec()) {
401 // First set operation action for all vector types to expand. Then we
402 // will selectively turn on ones that can be effectively codegen'd.
403 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
405 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
407 // add/sub are legal for all supported vector VT's.
408 setOperationAction(ISD::ADD , VT, Legal);
409 setOperationAction(ISD::SUB , VT, Legal);
411 // We promote all shuffles to v16i8.
412 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
413 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
415 // We promote all non-typed operations to v4i32.
416 setOperationAction(ISD::AND , VT, Promote);
417 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
418 setOperationAction(ISD::OR , VT, Promote);
419 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
420 setOperationAction(ISD::XOR , VT, Promote);
421 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
422 setOperationAction(ISD::LOAD , VT, Promote);
423 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
424 setOperationAction(ISD::SELECT, VT, Promote);
425 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
426 setOperationAction(ISD::STORE, VT, Promote);
427 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
429 // No other operations are legal.
430 setOperationAction(ISD::MUL , VT, Expand);
431 setOperationAction(ISD::SDIV, VT, Expand);
432 setOperationAction(ISD::SREM, VT, Expand);
433 setOperationAction(ISD::UDIV, VT, Expand);
434 setOperationAction(ISD::UREM, VT, Expand);
435 setOperationAction(ISD::FDIV, VT, Expand);
436 setOperationAction(ISD::FREM, VT, Expand);
437 setOperationAction(ISD::FNEG, VT, Expand);
438 setOperationAction(ISD::FSQRT, VT, Expand);
439 setOperationAction(ISD::FLOG, VT, Expand);
440 setOperationAction(ISD::FLOG10, VT, Expand);
441 setOperationAction(ISD::FLOG2, VT, Expand);
442 setOperationAction(ISD::FEXP, VT, Expand);
443 setOperationAction(ISD::FEXP2, VT, Expand);
444 setOperationAction(ISD::FSIN, VT, Expand);
445 setOperationAction(ISD::FCOS, VT, Expand);
446 setOperationAction(ISD::FABS, VT, Expand);
447 setOperationAction(ISD::FPOWI, VT, Expand);
448 setOperationAction(ISD::FFLOOR, VT, Expand);
449 setOperationAction(ISD::FCEIL, VT, Expand);
450 setOperationAction(ISD::FTRUNC, VT, Expand);
451 setOperationAction(ISD::FRINT, VT, Expand);
452 setOperationAction(ISD::FNEARBYINT, VT, Expand);
453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
454 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
455 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
456 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
458 setOperationAction(ISD::UDIVREM, VT, Expand);
459 setOperationAction(ISD::SDIVREM, VT, Expand);
460 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
461 setOperationAction(ISD::FPOW, VT, Expand);
462 setOperationAction(ISD::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 (PPCSubTarget.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 (PPCSubTarget.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 = PPCSubTarget.isPPC64() ? 8 : 4;
755 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
756 getMaxByValAlign(Ty, Align, PPCSubTarget.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::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
777 case PPCISD::LOAD: return "PPCISD::LOAD";
778 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
779 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
780 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
781 case PPCISD::SRL: return "PPCISD::SRL";
782 case PPCISD::SRA: return "PPCISD::SRA";
783 case PPCISD::SHL: return "PPCISD::SHL";
784 case PPCISD::CALL: return "PPCISD::CALL";
785 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
786 case PPCISD::MTCTR: return "PPCISD::MTCTR";
787 case PPCISD::BCTRL: return "PPCISD::BCTRL";
788 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
789 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
790 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
791 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
792 case PPCISD::VCMP: return "PPCISD::VCMP";
793 case PPCISD::VCMPo: return "PPCISD::VCMPo";
794 case PPCISD::LBRX: return "PPCISD::LBRX";
795 case PPCISD::STBRX: return "PPCISD::STBRX";
796 case PPCISD::LARX: return "PPCISD::LARX";
797 case PPCISD::STCX: return "PPCISD::STCX";
798 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
799 case PPCISD::BDNZ: return "PPCISD::BDNZ";
800 case PPCISD::BDZ: return "PPCISD::BDZ";
801 case PPCISD::MFFS: return "PPCISD::MFFS";
802 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
803 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
804 case PPCISD::CR6SET: return "PPCISD::CR6SET";
805 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
806 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
807 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
808 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
809 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
810 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
811 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
812 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
813 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
814 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
815 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
816 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
817 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
818 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
819 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
820 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
821 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
822 case PPCISD::SC: return "PPCISD::SC";
826 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
828 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
829 return VT.changeVectorElementTypeToInteger();
832 //===----------------------------------------------------------------------===//
833 // Node matching predicates, for use by the tblgen matching code.
834 //===----------------------------------------------------------------------===//
836 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
837 static bool isFloatingPointZero(SDValue Op) {
838 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
839 return CFP->getValueAPF().isZero();
840 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
841 // Maybe this has already been legalized into the constant pool?
842 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
843 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
844 return CFP->getValueAPF().isZero();
849 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
850 /// true if Op is undef or if it matches the specified value.
851 static bool isConstantOrUndef(int Op, int Val) {
852 return Op < 0 || Op == Val;
855 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
856 /// VPKUHUM instruction.
857 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
859 for (unsigned i = 0; i != 16; ++i)
860 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
863 for (unsigned i = 0; i != 8; ++i)
864 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
865 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
871 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
872 /// VPKUWUM instruction.
873 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
875 for (unsigned i = 0; i != 16; i += 2)
876 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
877 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
880 for (unsigned i = 0; i != 8; i += 2)
881 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
882 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
883 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
884 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
890 /// isVMerge - Common function, used to match vmrg* shuffles.
892 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
893 unsigned LHSStart, unsigned RHSStart) {
894 if (N->getValueType(0) != MVT::v16i8)
896 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
897 "Unsupported merge size!");
899 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
900 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
901 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
902 LHSStart+j+i*UnitSize) ||
903 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
904 RHSStart+j+i*UnitSize))
910 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
911 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
912 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
915 return isVMerge(N, UnitSize, 8, 24);
916 return isVMerge(N, UnitSize, 8, 8);
919 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
920 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
921 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
924 return isVMerge(N, UnitSize, 0, 16);
925 return isVMerge(N, UnitSize, 0, 0);
929 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
930 /// amount, otherwise return -1.
931 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
932 if (N->getValueType(0) != MVT::v16i8)
935 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
937 // Find the first non-undef value in the shuffle mask.
939 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
942 if (i == 16) return -1; // all undef.
944 // Otherwise, check to see if the rest of the elements are consecutively
945 // numbered from this value.
946 unsigned ShiftAmt = SVOp->getMaskElt(i);
947 if (ShiftAmt < i) return -1;
951 // Check the rest of the elements to see if they are consecutive.
952 for (++i; i != 16; ++i)
953 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
956 // Check the rest of the elements to see if they are consecutive.
957 for (++i; i != 16; ++i)
958 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
964 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
965 /// specifies a splat of a single element that is suitable for input to
966 /// VSPLTB/VSPLTH/VSPLTW.
967 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
968 assert(N->getValueType(0) == MVT::v16i8 &&
969 (EltSize == 1 || EltSize == 2 || EltSize == 4));
971 // This is a splat operation if each element of the permute is the same, and
972 // if the value doesn't reference the second vector.
973 unsigned ElementBase = N->getMaskElt(0);
975 // FIXME: Handle UNDEF elements too!
976 if (ElementBase >= 16)
979 // Check that the indices are consecutive, in the case of a multi-byte element
980 // splatted with a v16i8 mask.
981 for (unsigned i = 1; i != EltSize; ++i)
982 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
985 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
986 if (N->getMaskElt(i) < 0) continue;
987 for (unsigned j = 0; j != EltSize; ++j)
988 if (N->getMaskElt(i+j) != N->getMaskElt(j))
994 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
996 bool PPC::isAllNegativeZeroVector(SDNode *N) {
997 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
999 APInt APVal, APUndef;
1003 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1004 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1005 return CFP->getValueAPF().isNegZero();
1010 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1011 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1012 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
1013 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1014 assert(isSplatShuffleMask(SVOp, EltSize));
1015 return SVOp->getMaskElt(0) / EltSize;
1018 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1019 /// by using a vspltis[bhw] instruction of the specified element size, return
1020 /// the constant being splatted. The ByteSize field indicates the number of
1021 /// bytes of each element [124] -> [bhw].
1022 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1023 SDValue OpVal(nullptr, 0);
1025 // If ByteSize of the splat is bigger than the element size of the
1026 // build_vector, then we have a case where we are checking for a splat where
1027 // multiple elements of the buildvector are folded together into a single
1028 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1029 unsigned EltSize = 16/N->getNumOperands();
1030 if (EltSize < ByteSize) {
1031 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1032 SDValue UniquedVals[4];
1033 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1035 // See if all of the elements in the buildvector agree across.
1036 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1037 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1038 // If the element isn't a constant, bail fully out.
1039 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1042 if (!UniquedVals[i&(Multiple-1)].getNode())
1043 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1044 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1045 return SDValue(); // no match.
1048 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1049 // either constant or undef values that are identical for each chunk. See
1050 // if these chunks can form into a larger vspltis*.
1052 // Check to see if all of the leading entries are either 0 or -1. If
1053 // neither, then this won't fit into the immediate field.
1054 bool LeadingZero = true;
1055 bool LeadingOnes = true;
1056 for (unsigned i = 0; i != Multiple-1; ++i) {
1057 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1059 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1060 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1062 // Finally, check the least significant entry.
1064 if (!UniquedVals[Multiple-1].getNode())
1065 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1066 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1068 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1071 if (!UniquedVals[Multiple-1].getNode())
1072 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1073 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1074 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1075 return DAG.getTargetConstant(Val, MVT::i32);
1081 // Check to see if this buildvec has a single non-undef value in its elements.
1082 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1083 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1084 if (!OpVal.getNode())
1085 OpVal = N->getOperand(i);
1086 else if (OpVal != N->getOperand(i))
1090 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1092 unsigned ValSizeInBytes = EltSize;
1094 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1095 Value = CN->getZExtValue();
1096 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1097 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1098 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1101 // If the splat value is larger than the element value, then we can never do
1102 // this splat. The only case that we could fit the replicated bits into our
1103 // immediate field for would be zero, and we prefer to use vxor for it.
1104 if (ValSizeInBytes < ByteSize) return SDValue();
1106 // If the element value is larger than the splat value, cut it in half and
1107 // check to see if the two halves are equal. Continue doing this until we
1108 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1109 while (ValSizeInBytes > ByteSize) {
1110 ValSizeInBytes >>= 1;
1112 // If the top half equals the bottom half, we're still ok.
1113 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1114 (Value & ((1 << (8*ValSizeInBytes))-1)))
1118 // Properly sign extend the value.
1119 int MaskVal = SignExtend32(Value, ByteSize * 8);
1121 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1122 if (MaskVal == 0) return SDValue();
1124 // Finally, if this value fits in a 5 bit sext field, return it
1125 if (SignExtend32<5>(MaskVal) == MaskVal)
1126 return DAG.getTargetConstant(MaskVal, MVT::i32);
1130 //===----------------------------------------------------------------------===//
1131 // Addressing Mode Selection
1132 //===----------------------------------------------------------------------===//
1134 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1135 /// or 64-bit immediate, and if the value can be accurately represented as a
1136 /// sign extension from a 16-bit value. If so, this returns true and the
1138 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1139 if (!isa<ConstantSDNode>(N))
1142 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1143 if (N->getValueType(0) == MVT::i32)
1144 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1146 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1148 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1149 return isIntS16Immediate(Op.getNode(), Imm);
1153 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1154 /// can be represented as an indexed [r+r] operation. Returns false if it
1155 /// can be more efficiently represented with [r+imm].
1156 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1158 SelectionDAG &DAG) const {
1160 if (N.getOpcode() == ISD::ADD) {
1161 if (isIntS16Immediate(N.getOperand(1), imm))
1162 return false; // r+i
1163 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1164 return false; // r+i
1166 Base = N.getOperand(0);
1167 Index = N.getOperand(1);
1169 } else if (N.getOpcode() == ISD::OR) {
1170 if (isIntS16Immediate(N.getOperand(1), imm))
1171 return false; // r+i can fold it if we can.
1173 // If this is an or of disjoint bitfields, we can codegen this as an add
1174 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1176 APInt LHSKnownZero, LHSKnownOne;
1177 APInt RHSKnownZero, RHSKnownOne;
1178 DAG.computeKnownBits(N.getOperand(0),
1179 LHSKnownZero, LHSKnownOne);
1181 if (LHSKnownZero.getBoolValue()) {
1182 DAG.computeKnownBits(N.getOperand(1),
1183 RHSKnownZero, RHSKnownOne);
1184 // If all of the bits are known zero on the LHS or RHS, the add won't
1186 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1187 Base = N.getOperand(0);
1188 Index = N.getOperand(1);
1197 // If we happen to be doing an i64 load or store into a stack slot that has
1198 // less than a 4-byte alignment, then the frame-index elimination may need to
1199 // use an indexed load or store instruction (because the offset may not be a
1200 // multiple of 4). The extra register needed to hold the offset comes from the
1201 // register scavenger, and it is possible that the scavenger will need to use
1202 // an emergency spill slot. As a result, we need to make sure that a spill slot
1203 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1205 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1206 // FIXME: This does not handle the LWA case.
1210 // NOTE: We'll exclude negative FIs here, which come from argument
1211 // lowering, because there are no known test cases triggering this problem
1212 // using packed structures (or similar). We can remove this exclusion if
1213 // we find such a test case. The reason why this is so test-case driven is
1214 // because this entire 'fixup' is only to prevent crashes (from the
1215 // register scavenger) on not-really-valid inputs. For example, if we have:
1217 // %b = bitcast i1* %a to i64*
1218 // store i64* a, i64 b
1219 // then the store should really be marked as 'align 1', but is not. If it
1220 // were marked as 'align 1' then the indexed form would have been
1221 // instruction-selected initially, and the problem this 'fixup' is preventing
1222 // won't happen regardless.
1226 MachineFunction &MF = DAG.getMachineFunction();
1227 MachineFrameInfo *MFI = MF.getFrameInfo();
1229 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1233 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1234 FuncInfo->setHasNonRISpills();
1237 /// Returns true if the address N can be represented by a base register plus
1238 /// a signed 16-bit displacement [r+imm], and if it is not better
1239 /// represented as reg+reg. If Aligned is true, only accept displacements
1240 /// suitable for STD and friends, i.e. multiples of 4.
1241 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1244 bool Aligned) const {
1245 // FIXME dl should come from parent load or store, not from address
1247 // If this can be more profitably realized as r+r, fail.
1248 if (SelectAddressRegReg(N, Disp, Base, DAG))
1251 if (N.getOpcode() == ISD::ADD) {
1253 if (isIntS16Immediate(N.getOperand(1), imm) &&
1254 (!Aligned || (imm & 3) == 0)) {
1255 Disp = DAG.getTargetConstant(imm, N.getValueType());
1256 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1257 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1258 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1260 Base = N.getOperand(0);
1262 return true; // [r+i]
1263 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1264 // Match LOAD (ADD (X, Lo(G))).
1265 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1266 && "Cannot handle constant offsets yet!");
1267 Disp = N.getOperand(1).getOperand(0); // The global address.
1268 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1269 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1270 Disp.getOpcode() == ISD::TargetConstantPool ||
1271 Disp.getOpcode() == ISD::TargetJumpTable);
1272 Base = N.getOperand(0);
1273 return true; // [&g+r]
1275 } else if (N.getOpcode() == ISD::OR) {
1277 if (isIntS16Immediate(N.getOperand(1), imm) &&
1278 (!Aligned || (imm & 3) == 0)) {
1279 // If this is an or of disjoint bitfields, we can codegen this as an add
1280 // (for better address arithmetic) if the LHS and RHS of the OR are
1281 // provably disjoint.
1282 APInt LHSKnownZero, LHSKnownOne;
1283 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1285 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1286 // If all of the bits are known zero on the LHS or RHS, the add won't
1288 Base = N.getOperand(0);
1289 Disp = DAG.getTargetConstant(imm, N.getValueType());
1293 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1294 // Loading from a constant address.
1296 // If this address fits entirely in a 16-bit sext immediate field, codegen
1299 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1300 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1301 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1302 CN->getValueType(0));
1306 // Handle 32-bit sext immediates with LIS + addr mode.
1307 if ((CN->getValueType(0) == MVT::i32 ||
1308 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1309 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1310 int Addr = (int)CN->getZExtValue();
1312 // Otherwise, break this down into an LIS + disp.
1313 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1315 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1316 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1317 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1322 Disp = DAG.getTargetConstant(0, getPointerTy());
1323 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1324 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1325 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1328 return true; // [r+0]
1331 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1332 /// represented as an indexed [r+r] operation.
1333 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1335 SelectionDAG &DAG) const {
1336 // Check to see if we can easily represent this as an [r+r] address. This
1337 // will fail if it thinks that the address is more profitably represented as
1338 // reg+imm, e.g. where imm = 0.
1339 if (SelectAddressRegReg(N, Base, Index, DAG))
1342 // If the operand is an addition, always emit this as [r+r], since this is
1343 // better (for code size, and execution, as the memop does the add for free)
1344 // than emitting an explicit add.
1345 if (N.getOpcode() == ISD::ADD) {
1346 Base = N.getOperand(0);
1347 Index = N.getOperand(1);
1351 // Otherwise, do it the hard way, using R0 as the base register.
1352 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1358 /// getPreIndexedAddressParts - returns true by value, base pointer and
1359 /// offset pointer and addressing mode by reference if the node's address
1360 /// can be legally represented as pre-indexed load / store address.
1361 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1363 ISD::MemIndexedMode &AM,
1364 SelectionDAG &DAG) const {
1365 if (DisablePPCPreinc) return false;
1371 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1372 Ptr = LD->getBasePtr();
1373 VT = LD->getMemoryVT();
1374 Alignment = LD->getAlignment();
1375 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1376 Ptr = ST->getBasePtr();
1377 VT = ST->getMemoryVT();
1378 Alignment = ST->getAlignment();
1383 // PowerPC doesn't have preinc load/store instructions for vectors.
1387 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1389 // Common code will reject creating a pre-inc form if the base pointer
1390 // is a frame index, or if N is a store and the base pointer is either
1391 // the same as or a predecessor of the value being stored. Check for
1392 // those situations here, and try with swapped Base/Offset instead.
1395 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1398 SDValue Val = cast<StoreSDNode>(N)->getValue();
1399 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1404 std::swap(Base, Offset);
1410 // LDU/STU can only handle immediates that are a multiple of 4.
1411 if (VT != MVT::i64) {
1412 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1415 // LDU/STU need an address with at least 4-byte alignment.
1419 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1423 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1424 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1425 // sext i32 to i64 when addr mode is r+i.
1426 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1427 LD->getExtensionType() == ISD::SEXTLOAD &&
1428 isa<ConstantSDNode>(Offset))
1436 //===----------------------------------------------------------------------===//
1437 // LowerOperation implementation
1438 //===----------------------------------------------------------------------===//
1440 /// GetLabelAccessInfo - Return true if we should reference labels using a
1441 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1442 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1443 unsigned &LoOpFlags,
1444 const GlobalValue *GV = nullptr) {
1445 HiOpFlags = PPCII::MO_HA;
1446 LoOpFlags = PPCII::MO_LO;
1448 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1449 // non-darwin platform. We don't support PIC on other platforms yet.
1450 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1451 TM.getSubtarget<PPCSubtarget>().isDarwin();
1453 HiOpFlags |= PPCII::MO_PIC_FLAG;
1454 LoOpFlags |= PPCII::MO_PIC_FLAG;
1457 // If this is a reference to a global value that requires a non-lazy-ptr, make
1458 // sure that instruction lowering adds it.
1459 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1460 HiOpFlags |= PPCII::MO_NLP_FLAG;
1461 LoOpFlags |= PPCII::MO_NLP_FLAG;
1463 if (GV->hasHiddenVisibility()) {
1464 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1465 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1472 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1473 SelectionDAG &DAG) {
1474 EVT PtrVT = HiPart.getValueType();
1475 SDValue Zero = DAG.getConstant(0, PtrVT);
1478 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1479 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1481 // With PIC, the first instruction is actually "GR+hi(&G)".
1483 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1484 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1486 // Generate non-pic code that has direct accesses to the constant pool.
1487 // The address of the global is just (hi(&g)+lo(&g)).
1488 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1491 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1492 SelectionDAG &DAG) const {
1493 EVT PtrVT = Op.getValueType();
1494 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1495 const Constant *C = CP->getConstVal();
1497 // 64-bit SVR4 ABI code is always position-independent.
1498 // The actual address of the GlobalValue is stored in the TOC.
1499 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1500 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1501 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1502 DAG.getRegister(PPC::X2, MVT::i64));
1505 unsigned MOHiFlag, MOLoFlag;
1506 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1508 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1510 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1511 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1514 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1515 EVT PtrVT = Op.getValueType();
1516 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1518 // 64-bit SVR4 ABI code is always position-independent.
1519 // The actual address of the GlobalValue is stored in the TOC.
1520 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1521 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1522 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1523 DAG.getRegister(PPC::X2, MVT::i64));
1526 unsigned MOHiFlag, MOLoFlag;
1527 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1528 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1529 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1530 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1533 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1534 SelectionDAG &DAG) const {
1535 EVT PtrVT = Op.getValueType();
1537 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1539 unsigned MOHiFlag, MOLoFlag;
1540 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1541 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1542 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1543 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1546 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1547 SelectionDAG &DAG) const {
1549 // FIXME: TLS addresses currently use medium model code sequences,
1550 // which is the most useful form. Eventually support for small and
1551 // large models could be added if users need it, at the cost of
1552 // additional complexity.
1553 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1555 const GlobalValue *GV = GA->getGlobal();
1556 EVT PtrVT = getPointerTy();
1557 bool is64bit = PPCSubTarget.isPPC64();
1559 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1561 if (Model == TLSModel::LocalExec) {
1562 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1563 PPCII::MO_TPREL_HA);
1564 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1565 PPCII::MO_TPREL_LO);
1566 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1567 is64bit ? MVT::i64 : MVT::i32);
1568 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1569 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1572 if (Model == TLSModel::InitialExec) {
1573 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1574 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1578 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1579 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1580 PtrVT, GOTReg, TGA);
1582 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1583 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1584 PtrVT, TGA, GOTPtr);
1585 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1588 if (Model == TLSModel::GeneralDynamic) {
1589 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1590 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1591 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1593 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1596 // We need a chain node, and don't have one handy. The underlying
1597 // call has no side effects, so using the function entry node
1599 SDValue Chain = DAG.getEntryNode();
1600 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1601 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1602 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1603 PtrVT, ParmReg, TGA);
1604 // The return value from GET_TLS_ADDR really is in X3 already, but
1605 // some hacks are needed here to tie everything together. The extra
1606 // copies dissolve during subsequent transforms.
1607 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1608 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1611 if (Model == TLSModel::LocalDynamic) {
1612 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1613 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1614 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1616 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1619 // We need a chain node, and don't have one handy. The underlying
1620 // call has no side effects, so using the function entry node
1622 SDValue Chain = DAG.getEntryNode();
1623 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1624 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1625 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1626 PtrVT, ParmReg, TGA);
1627 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1628 // some hacks are needed here to tie everything together. The extra
1629 // copies dissolve during subsequent transforms.
1630 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1631 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1632 Chain, ParmReg, TGA);
1633 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1636 llvm_unreachable("Unknown TLS model!");
1639 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1640 SelectionDAG &DAG) const {
1641 EVT PtrVT = Op.getValueType();
1642 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1644 const GlobalValue *GV = GSDN->getGlobal();
1646 // 64-bit SVR4 ABI code is always position-independent.
1647 // The actual address of the GlobalValue is stored in the TOC.
1648 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1649 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1650 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1651 DAG.getRegister(PPC::X2, MVT::i64));
1654 unsigned MOHiFlag, MOLoFlag;
1655 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1658 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1660 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1662 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1664 // If the global reference is actually to a non-lazy-pointer, we have to do an
1665 // extra load to get the address of the global.
1666 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1667 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1668 false, false, false, 0);
1672 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1673 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1676 if (Op.getValueType() == MVT::v2i64) {
1677 // When the operands themselves are v2i64 values, we need to do something
1678 // special because VSX has no underlying comparison operations for these.
1679 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1680 // Equality can be handled by casting to the legal type for Altivec
1681 // comparisons, everything else needs to be expanded.
1682 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1683 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1684 DAG.getSetCC(dl, MVT::v4i32,
1685 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1686 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1693 // We handle most of these in the usual way.
1697 // If we're comparing for equality to zero, expose the fact that this is
1698 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1699 // fold the new nodes.
1700 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1701 if (C->isNullValue() && CC == ISD::SETEQ) {
1702 EVT VT = Op.getOperand(0).getValueType();
1703 SDValue Zext = Op.getOperand(0);
1704 if (VT.bitsLT(MVT::i32)) {
1706 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1708 unsigned Log2b = Log2_32(VT.getSizeInBits());
1709 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1710 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1711 DAG.getConstant(Log2b, MVT::i32));
1712 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1714 // Leave comparisons against 0 and -1 alone for now, since they're usually
1715 // optimized. FIXME: revisit this when we can custom lower all setcc
1717 if (C->isAllOnesValue() || C->isNullValue())
1721 // If we have an integer seteq/setne, turn it into a compare against zero
1722 // by xor'ing the rhs with the lhs, which is faster than setting a
1723 // condition register, reading it back out, and masking the correct bit. The
1724 // normal approach here uses sub to do this instead of xor. Using xor exposes
1725 // the result to other bit-twiddling opportunities.
1726 EVT LHSVT = Op.getOperand(0).getValueType();
1727 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1728 EVT VT = Op.getValueType();
1729 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1731 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1736 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1737 const PPCSubtarget &Subtarget) const {
1738 SDNode *Node = Op.getNode();
1739 EVT VT = Node->getValueType(0);
1740 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1741 SDValue InChain = Node->getOperand(0);
1742 SDValue VAListPtr = Node->getOperand(1);
1743 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1746 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1749 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1750 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1752 InChain = GprIndex.getValue(1);
1754 if (VT == MVT::i64) {
1755 // Check if GprIndex is even
1756 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1757 DAG.getConstant(1, MVT::i32));
1758 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1759 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1760 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1761 DAG.getConstant(1, MVT::i32));
1762 // Align GprIndex to be even if it isn't
1763 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1767 // fpr index is 1 byte after gpr
1768 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1769 DAG.getConstant(1, MVT::i32));
1772 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1773 FprPtr, MachinePointerInfo(SV), MVT::i8,
1775 InChain = FprIndex.getValue(1);
1777 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1778 DAG.getConstant(8, MVT::i32));
1780 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1781 DAG.getConstant(4, MVT::i32));
1784 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1785 MachinePointerInfo(), false, false,
1787 InChain = OverflowArea.getValue(1);
1789 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1790 MachinePointerInfo(), false, false,
1792 InChain = RegSaveArea.getValue(1);
1794 // select overflow_area if index > 8
1795 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1796 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1798 // adjustment constant gpr_index * 4/8
1799 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1800 VT.isInteger() ? GprIndex : FprIndex,
1801 DAG.getConstant(VT.isInteger() ? 4 : 8,
1804 // OurReg = RegSaveArea + RegConstant
1805 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1808 // Floating types are 32 bytes into RegSaveArea
1809 if (VT.isFloatingPoint())
1810 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1811 DAG.getConstant(32, MVT::i32));
1813 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1814 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1815 VT.isInteger() ? GprIndex : FprIndex,
1816 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1819 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1820 VT.isInteger() ? VAListPtr : FprPtr,
1821 MachinePointerInfo(SV),
1822 MVT::i8, false, false, 0);
1824 // determine if we should load from reg_save_area or overflow_area
1825 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1827 // increase overflow_area by 4/8 if gpr/fpr > 8
1828 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1829 DAG.getConstant(VT.isInteger() ? 4 : 8,
1832 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1835 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1837 MachinePointerInfo(),
1838 MVT::i32, false, false, 0);
1840 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1841 false, false, false, 0);
1844 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1845 const PPCSubtarget &Subtarget) const {
1846 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1848 // We have to copy the entire va_list struct:
1849 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1850 return DAG.getMemcpy(Op.getOperand(0), Op,
1851 Op.getOperand(1), Op.getOperand(2),
1852 DAG.getConstant(12, MVT::i32), 8, false, true,
1853 MachinePointerInfo(), MachinePointerInfo());
1856 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1857 SelectionDAG &DAG) const {
1858 return Op.getOperand(0);
1861 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1862 SelectionDAG &DAG) const {
1863 SDValue Chain = Op.getOperand(0);
1864 SDValue Trmp = Op.getOperand(1); // trampoline
1865 SDValue FPtr = Op.getOperand(2); // nested function
1866 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1869 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1870 bool isPPC64 = (PtrVT == MVT::i64);
1872 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1875 TargetLowering::ArgListTy Args;
1876 TargetLowering::ArgListEntry Entry;
1878 Entry.Ty = IntPtrTy;
1879 Entry.Node = Trmp; Args.push_back(Entry);
1881 // TrampSize == (isPPC64 ? 48 : 40);
1882 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1883 isPPC64 ? MVT::i64 : MVT::i32);
1884 Args.push_back(Entry);
1886 Entry.Node = FPtr; Args.push_back(Entry);
1887 Entry.Node = Nest; Args.push_back(Entry);
1889 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1890 TargetLowering::CallLoweringInfo CLI(DAG);
1891 CLI.setDebugLoc(dl).setChain(Chain)
1892 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
1893 DAG.getExternalSymbol("__trampoline_setup", PtrVT), &Args, 0);
1895 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1896 return CallResult.second;
1899 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1900 const PPCSubtarget &Subtarget) const {
1901 MachineFunction &MF = DAG.getMachineFunction();
1902 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1906 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1907 // vastart just stores the address of the VarArgsFrameIndex slot into the
1908 // memory location argument.
1909 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1910 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1911 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1912 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1913 MachinePointerInfo(SV),
1917 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1918 // We suppose the given va_list is already allocated.
1921 // char gpr; /* index into the array of 8 GPRs
1922 // * stored in the register save area
1923 // * gpr=0 corresponds to r3,
1924 // * gpr=1 to r4, etc.
1926 // char fpr; /* index into the array of 8 FPRs
1927 // * stored in the register save area
1928 // * fpr=0 corresponds to f1,
1929 // * fpr=1 to f2, etc.
1931 // char *overflow_arg_area;
1932 // /* location on stack that holds
1933 // * the next overflow argument
1935 // char *reg_save_area;
1936 // /* where r3:r10 and f1:f8 (if saved)
1942 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1943 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1946 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1948 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1950 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1953 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1954 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1956 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1957 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1959 uint64_t FPROffset = 1;
1960 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1962 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1964 // Store first byte : number of int regs
1965 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1967 MachinePointerInfo(SV),
1968 MVT::i8, false, false, 0);
1969 uint64_t nextOffset = FPROffset;
1970 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1973 // Store second byte : number of float regs
1974 SDValue secondStore =
1975 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1976 MachinePointerInfo(SV, nextOffset), MVT::i8,
1978 nextOffset += StackOffset;
1979 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1981 // Store second word : arguments given on stack
1982 SDValue thirdStore =
1983 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1984 MachinePointerInfo(SV, nextOffset),
1986 nextOffset += FrameOffset;
1987 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1989 // Store third word : arguments given in registers
1990 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1991 MachinePointerInfo(SV, nextOffset),
1996 #include "PPCGenCallingConv.inc"
1998 // Function whose sole purpose is to kill compiler warnings
1999 // stemming from unused functions included from PPCGenCallingConv.inc.
2000 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2001 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2004 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2005 CCValAssign::LocInfo &LocInfo,
2006 ISD::ArgFlagsTy &ArgFlags,
2011 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2013 CCValAssign::LocInfo &LocInfo,
2014 ISD::ArgFlagsTy &ArgFlags,
2016 static const MCPhysReg ArgRegs[] = {
2017 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2018 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2020 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2022 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2024 // Skip one register if the first unallocated register has an even register
2025 // number and there are still argument registers available which have not been
2026 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2027 // need to skip a register if RegNum is odd.
2028 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2029 State.AllocateReg(ArgRegs[RegNum]);
2032 // Always return false here, as this function only makes sure that the first
2033 // unallocated register has an odd register number and does not actually
2034 // allocate a register for the current argument.
2038 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2040 CCValAssign::LocInfo &LocInfo,
2041 ISD::ArgFlagsTy &ArgFlags,
2043 static const MCPhysReg ArgRegs[] = {
2044 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2048 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2050 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2052 // If there is only one Floating-point register left we need to put both f64
2053 // values of a split ppc_fp128 value on the stack.
2054 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2055 State.AllocateReg(ArgRegs[RegNum]);
2058 // Always return false here, as this function only makes sure that the two f64
2059 // values a ppc_fp128 value is split into are both passed in registers or both
2060 // passed on the stack and does not actually allocate a register for the
2061 // current argument.
2065 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2067 static const MCPhysReg *GetFPR() {
2068 static const MCPhysReg FPR[] = {
2069 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2070 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2076 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2078 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2079 unsigned PtrByteSize) {
2080 unsigned ArgSize = ArgVT.getStoreSize();
2081 if (Flags.isByVal())
2082 ArgSize = Flags.getByValSize();
2083 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2089 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2090 CallingConv::ID CallConv, bool isVarArg,
2091 const SmallVectorImpl<ISD::InputArg>
2093 SDLoc dl, SelectionDAG &DAG,
2094 SmallVectorImpl<SDValue> &InVals)
2096 if (PPCSubTarget.isSVR4ABI()) {
2097 if (PPCSubTarget.isPPC64())
2098 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2101 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2104 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2110 PPCTargetLowering::LowerFormalArguments_32SVR4(
2112 CallingConv::ID CallConv, bool isVarArg,
2113 const SmallVectorImpl<ISD::InputArg>
2115 SDLoc dl, SelectionDAG &DAG,
2116 SmallVectorImpl<SDValue> &InVals) const {
2118 // 32-bit SVR4 ABI Stack Frame Layout:
2119 // +-----------------------------------+
2120 // +--> | Back chain |
2121 // | +-----------------------------------+
2122 // | | Floating-point register save area |
2123 // | +-----------------------------------+
2124 // | | General register save area |
2125 // | +-----------------------------------+
2126 // | | CR save word |
2127 // | +-----------------------------------+
2128 // | | VRSAVE save word |
2129 // | +-----------------------------------+
2130 // | | Alignment padding |
2131 // | +-----------------------------------+
2132 // | | Vector register save area |
2133 // | +-----------------------------------+
2134 // | | Local variable space |
2135 // | +-----------------------------------+
2136 // | | Parameter list area |
2137 // | +-----------------------------------+
2138 // | | LR save word |
2139 // | +-----------------------------------+
2140 // SP--> +--- | Back chain |
2141 // +-----------------------------------+
2144 // System V Application Binary Interface PowerPC Processor Supplement
2145 // AltiVec Technology Programming Interface Manual
2147 MachineFunction &MF = DAG.getMachineFunction();
2148 MachineFrameInfo *MFI = MF.getFrameInfo();
2149 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2151 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2152 // Potential tail calls could cause overwriting of argument stack slots.
2153 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2154 (CallConv == CallingConv::Fast));
2155 unsigned PtrByteSize = 4;
2157 // Assign locations to all of the incoming arguments.
2158 SmallVector<CCValAssign, 16> ArgLocs;
2159 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2160 getTargetMachine(), ArgLocs, *DAG.getContext());
2162 // Reserve space for the linkage area on the stack.
2163 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2165 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2167 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2168 CCValAssign &VA = ArgLocs[i];
2170 // Arguments stored in registers.
2171 if (VA.isRegLoc()) {
2172 const TargetRegisterClass *RC;
2173 EVT ValVT = VA.getValVT();
2175 switch (ValVT.getSimpleVT().SimpleTy) {
2177 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2180 RC = &PPC::GPRCRegClass;
2183 RC = &PPC::F4RCRegClass;
2186 if (PPCSubTarget.hasVSX())
2187 RC = &PPC::VSFRCRegClass;
2189 RC = &PPC::F8RCRegClass;
2195 RC = &PPC::VRRCRegClass;
2199 RC = &PPC::VSHRCRegClass;
2203 // Transform the arguments stored in physical registers into virtual ones.
2204 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2205 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2206 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2208 if (ValVT == MVT::i1)
2209 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2211 InVals.push_back(ArgValue);
2213 // Argument stored in memory.
2214 assert(VA.isMemLoc());
2216 unsigned ArgSize = VA.getLocVT().getStoreSize();
2217 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2220 // Create load nodes to retrieve arguments from the stack.
2221 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2222 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2223 MachinePointerInfo(),
2224 false, false, false, 0));
2228 // Assign locations to all of the incoming aggregate by value arguments.
2229 // Aggregates passed by value are stored in the local variable space of the
2230 // caller's stack frame, right above the parameter list area.
2231 SmallVector<CCValAssign, 16> ByValArgLocs;
2232 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2233 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2235 // Reserve stack space for the allocations in CCInfo.
2236 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2238 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2240 // Area that is at least reserved in the caller of this function.
2241 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2243 // Set the size that is at least reserved in caller of this function. Tail
2244 // call optimized function's reserved stack space needs to be aligned so that
2245 // taking the difference between two stack areas will result in an aligned
2247 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2250 std::max(MinReservedArea,
2251 PPCFrameLowering::getMinCallFrameSize(false, false));
2253 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2254 getStackAlignment();
2255 unsigned AlignMask = TargetAlign-1;
2256 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2258 FI->setMinReservedArea(MinReservedArea);
2260 SmallVector<SDValue, 8> MemOps;
2262 // If the function takes variable number of arguments, make a frame index for
2263 // the start of the first vararg value... for expansion of llvm.va_start.
2265 static const MCPhysReg GPArgRegs[] = {
2266 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2267 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2269 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2271 static const MCPhysReg FPArgRegs[] = {
2272 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2275 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2277 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2279 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2282 // Make room for NumGPArgRegs and NumFPArgRegs.
2283 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2284 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2286 FuncInfo->setVarArgsStackOffset(
2287 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2288 CCInfo.getNextStackOffset(), true));
2290 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2291 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2293 // The fixed integer arguments of a variadic function are stored to the
2294 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2295 // the result of va_next.
2296 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2297 // Get an existing live-in vreg, or add a new one.
2298 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2300 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2302 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2303 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2304 MachinePointerInfo(), false, false, 0);
2305 MemOps.push_back(Store);
2306 // Increment the address by four for the next argument to store
2307 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2308 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2311 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2313 // The double arguments are stored to the VarArgsFrameIndex
2315 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2316 // Get an existing live-in vreg, or add a new one.
2317 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2319 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2321 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2322 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2323 MachinePointerInfo(), false, false, 0);
2324 MemOps.push_back(Store);
2325 // Increment the address by eight for the next argument to store
2326 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2328 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2332 if (!MemOps.empty())
2333 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2338 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2339 // value to MVT::i64 and then truncate to the correct register size.
2341 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2342 SelectionDAG &DAG, SDValue ArgVal,
2345 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2346 DAG.getValueType(ObjectVT));
2347 else if (Flags.isZExt())
2348 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2349 DAG.getValueType(ObjectVT));
2351 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2354 // Set the size that is at least reserved in caller of this function. Tail
2355 // call optimized functions' reserved stack space needs to be aligned so that
2356 // taking the difference between two stack areas will result in an aligned
2359 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2360 unsigned nAltivecParamsAtEnd,
2361 unsigned MinReservedArea,
2362 bool isPPC64) const {
2363 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2364 // Add the Altivec parameters at the end, if needed.
2365 if (nAltivecParamsAtEnd) {
2366 MinReservedArea = ((MinReservedArea+15)/16)*16;
2367 MinReservedArea += 16*nAltivecParamsAtEnd;
2370 std::max(MinReservedArea,
2371 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2372 unsigned TargetAlign
2373 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2374 getStackAlignment();
2375 unsigned AlignMask = TargetAlign-1;
2376 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2377 FI->setMinReservedArea(MinReservedArea);
2381 PPCTargetLowering::LowerFormalArguments_64SVR4(
2383 CallingConv::ID CallConv, bool isVarArg,
2384 const SmallVectorImpl<ISD::InputArg>
2386 SDLoc dl, SelectionDAG &DAG,
2387 SmallVectorImpl<SDValue> &InVals) const {
2388 // TODO: add description of PPC stack frame format, or at least some docs.
2390 MachineFunction &MF = DAG.getMachineFunction();
2391 MachineFrameInfo *MFI = MF.getFrameInfo();
2392 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2394 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2395 // Potential tail calls could cause overwriting of argument stack slots.
2396 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2397 (CallConv == CallingConv::Fast));
2398 unsigned PtrByteSize = 8;
2400 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2401 // Area that is at least reserved in caller of this function.
2402 unsigned MinReservedArea = ArgOffset;
2404 static const MCPhysReg GPR[] = {
2405 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2406 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2409 static const MCPhysReg *FPR = GetFPR();
2411 static const MCPhysReg VR[] = {
2412 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2413 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2415 static const MCPhysReg VSRH[] = {
2416 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2417 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2420 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2421 const unsigned Num_FPR_Regs = 13;
2422 const unsigned Num_VR_Regs = array_lengthof(VR);
2424 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2426 // Add DAG nodes to load the arguments or copy them out of registers. On
2427 // entry to a function on PPC, the arguments start after the linkage area,
2428 // although the first ones are often in registers.
2430 SmallVector<SDValue, 8> MemOps;
2431 unsigned nAltivecParamsAtEnd = 0;
2432 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2433 unsigned CurArgIdx = 0;
2434 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2436 bool needsLoad = false;
2437 EVT ObjectVT = Ins[ArgNo].VT;
2438 unsigned ObjSize = ObjectVT.getStoreSize();
2439 unsigned ArgSize = ObjSize;
2440 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2441 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2442 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2444 unsigned CurArgOffset = ArgOffset;
2446 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2447 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2448 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8 ||
2449 ObjectVT==MVT::v2f64 || ObjectVT==MVT::v2i64) {
2451 MinReservedArea = ((MinReservedArea+15)/16)*16;
2452 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2456 nAltivecParamsAtEnd++;
2458 // Calculate min reserved area.
2459 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2463 // FIXME the codegen can be much improved in some cases.
2464 // We do not have to keep everything in memory.
2465 if (Flags.isByVal()) {
2466 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2467 ObjSize = Flags.getByValSize();
2468 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2469 // Empty aggregate parameters do not take up registers. Examples:
2473 // etc. However, we have to provide a place-holder in InVals, so
2474 // pretend we have an 8-byte item at the current address for that
2477 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2478 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2479 InVals.push_back(FIN);
2483 unsigned BVAlign = Flags.getByValAlign();
2485 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2486 CurArgOffset = ArgOffset;
2489 // All aggregates smaller than 8 bytes must be passed right-justified.
2490 if (ObjSize < PtrByteSize)
2491 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2492 // The value of the object is its address.
2493 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2494 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2495 InVals.push_back(FIN);
2498 if (GPR_idx != Num_GPR_Regs) {
2499 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2500 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2503 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2504 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2505 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2506 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2507 MachinePointerInfo(FuncArg),
2508 ObjType, false, false, 0);
2510 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2511 // store the whole register as-is to the parameter save area
2512 // slot. The address of the parameter was already calculated
2513 // above (InVals.push_back(FIN)) to be the right-justified
2514 // offset within the slot. For this store, we need a new
2515 // frame index that points at the beginning of the slot.
2516 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2517 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2518 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2519 MachinePointerInfo(FuncArg),
2523 MemOps.push_back(Store);
2526 // Whether we copied from a register or not, advance the offset
2527 // into the parameter save area by a full doubleword.
2528 ArgOffset += PtrByteSize;
2532 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2533 // Store whatever pieces of the object are in registers
2534 // to memory. ArgOffset will be the address of the beginning
2536 if (GPR_idx != Num_GPR_Regs) {
2538 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2539 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2540 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2541 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2542 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2543 MachinePointerInfo(FuncArg, j),
2545 MemOps.push_back(Store);
2547 ArgOffset += PtrByteSize;
2549 ArgOffset += ArgSize - j;
2556 switch (ObjectVT.getSimpleVT().SimpleTy) {
2557 default: llvm_unreachable("Unhandled argument type!");
2561 if (GPR_idx != Num_GPR_Regs) {
2562 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2563 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2565 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2566 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2567 // value to MVT::i64 and then truncate to the correct register size.
2568 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2573 ArgSize = PtrByteSize;
2580 // Every 8 bytes of argument space consumes one of the GPRs available for
2581 // argument passing.
2582 if (GPR_idx != Num_GPR_Regs) {
2585 if (FPR_idx != Num_FPR_Regs) {
2588 if (ObjectVT == MVT::f32)
2589 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2591 VReg = MF.addLiveIn(FPR[FPR_idx], PPCSubTarget.hasVSX() ?
2592 &PPC::VSFRCRegClass :
2593 &PPC::F8RCRegClass);
2595 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2599 ArgSize = PtrByteSize;
2610 // Note that vector arguments in registers don't reserve stack space,
2611 // except in varargs functions.
2612 if (VR_idx != Num_VR_Regs) {
2613 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2614 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2615 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2616 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2618 while ((ArgOffset % 16) != 0) {
2619 ArgOffset += PtrByteSize;
2620 if (GPR_idx != Num_GPR_Regs)
2624 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2628 // Vectors are aligned.
2629 ArgOffset = ((ArgOffset+15)/16)*16;
2630 CurArgOffset = ArgOffset;
2637 // We need to load the argument to a virtual register if we determined
2638 // above that we ran out of physical registers of the appropriate type.
2640 int FI = MFI->CreateFixedObject(ObjSize,
2641 CurArgOffset + (ArgSize - ObjSize),
2643 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2644 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2645 false, false, false, 0);
2648 InVals.push_back(ArgVal);
2651 // Set the size that is at least reserved in caller of this function. Tail
2652 // call optimized functions' reserved stack space needs to be aligned so that
2653 // taking the difference between two stack areas will result in an aligned
2655 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2657 // If the function takes variable number of arguments, make a frame index for
2658 // the start of the first vararg value... for expansion of llvm.va_start.
2660 int Depth = ArgOffset;
2662 FuncInfo->setVarArgsFrameIndex(
2663 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2664 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2666 // If this function is vararg, store any remaining integer argument regs
2667 // to their spots on the stack so that they may be loaded by deferencing the
2668 // result of va_next.
2669 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2670 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2671 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2672 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2673 MachinePointerInfo(), false, false, 0);
2674 MemOps.push_back(Store);
2675 // Increment the address by four for the next argument to store
2676 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2677 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2681 if (!MemOps.empty())
2682 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2688 PPCTargetLowering::LowerFormalArguments_Darwin(
2690 CallingConv::ID CallConv, bool isVarArg,
2691 const SmallVectorImpl<ISD::InputArg>
2693 SDLoc dl, SelectionDAG &DAG,
2694 SmallVectorImpl<SDValue> &InVals) const {
2695 // TODO: add description of PPC stack frame format, or at least some docs.
2697 MachineFunction &MF = DAG.getMachineFunction();
2698 MachineFrameInfo *MFI = MF.getFrameInfo();
2699 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2701 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2702 bool isPPC64 = PtrVT == MVT::i64;
2703 // Potential tail calls could cause overwriting of argument stack slots.
2704 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2705 (CallConv == CallingConv::Fast));
2706 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2708 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2709 // Area that is at least reserved in caller of this function.
2710 unsigned MinReservedArea = ArgOffset;
2712 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2713 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2714 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2716 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2717 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2718 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2721 static const MCPhysReg *FPR = GetFPR();
2723 static const MCPhysReg VR[] = {
2724 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2725 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2728 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2729 const unsigned Num_FPR_Regs = 13;
2730 const unsigned Num_VR_Regs = array_lengthof( VR);
2732 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2734 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2736 // In 32-bit non-varargs functions, the stack space for vectors is after the
2737 // stack space for non-vectors. We do not use this space unless we have
2738 // too many vectors to fit in registers, something that only occurs in
2739 // constructed examples:), but we have to walk the arglist to figure
2740 // that out...for the pathological case, compute VecArgOffset as the
2741 // start of the vector parameter area. Computing VecArgOffset is the
2742 // entire point of the following loop.
2743 unsigned VecArgOffset = ArgOffset;
2744 if (!isVarArg && !isPPC64) {
2745 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2747 EVT ObjectVT = Ins[ArgNo].VT;
2748 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2750 if (Flags.isByVal()) {
2751 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2752 unsigned ObjSize = Flags.getByValSize();
2754 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2755 VecArgOffset += ArgSize;
2759 switch(ObjectVT.getSimpleVT().SimpleTy) {
2760 default: llvm_unreachable("Unhandled argument type!");
2766 case MVT::i64: // PPC64
2768 // FIXME: We are guaranteed to be !isPPC64 at this point.
2769 // Does MVT::i64 apply?
2776 // Nothing to do, we're only looking at Nonvector args here.
2781 // We've found where the vector parameter area in memory is. Skip the
2782 // first 12 parameters; these don't use that memory.
2783 VecArgOffset = ((VecArgOffset+15)/16)*16;
2784 VecArgOffset += 12*16;
2786 // Add DAG nodes to load the arguments or copy them out of registers. On
2787 // entry to a function on PPC, the arguments start after the linkage area,
2788 // although the first ones are often in registers.
2790 SmallVector<SDValue, 8> MemOps;
2791 unsigned nAltivecParamsAtEnd = 0;
2792 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2793 unsigned CurArgIdx = 0;
2794 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2796 bool needsLoad = false;
2797 EVT ObjectVT = Ins[ArgNo].VT;
2798 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2799 unsigned ArgSize = ObjSize;
2800 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2801 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2802 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2804 unsigned CurArgOffset = ArgOffset;
2806 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2807 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2808 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2809 if (isVarArg || isPPC64) {
2810 MinReservedArea = ((MinReservedArea+15)/16)*16;
2811 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2814 } else nAltivecParamsAtEnd++;
2816 // Calculate min reserved area.
2817 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2821 // FIXME the codegen can be much improved in some cases.
2822 // We do not have to keep everything in memory.
2823 if (Flags.isByVal()) {
2824 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2825 ObjSize = Flags.getByValSize();
2826 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2827 // Objects of size 1 and 2 are right justified, everything else is
2828 // left justified. This means the memory address is adjusted forwards.
2829 if (ObjSize==1 || ObjSize==2) {
2830 CurArgOffset = CurArgOffset + (4 - ObjSize);
2832 // The value of the object is its address.
2833 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2834 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2835 InVals.push_back(FIN);
2836 if (ObjSize==1 || ObjSize==2) {
2837 if (GPR_idx != Num_GPR_Regs) {
2840 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2842 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2843 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2844 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2845 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2846 MachinePointerInfo(FuncArg),
2847 ObjType, false, false, 0);
2848 MemOps.push_back(Store);
2852 ArgOffset += PtrByteSize;
2856 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2857 // Store whatever pieces of the object are in registers
2858 // to memory. ArgOffset will be the address of the beginning
2860 if (GPR_idx != Num_GPR_Regs) {
2863 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2865 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2866 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2867 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2868 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2869 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2870 MachinePointerInfo(FuncArg, j),
2872 MemOps.push_back(Store);
2874 ArgOffset += PtrByteSize;
2876 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2883 switch (ObjectVT.getSimpleVT().SimpleTy) {
2884 default: llvm_unreachable("Unhandled argument type!");
2888 if (GPR_idx != Num_GPR_Regs) {
2889 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2890 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2892 if (ObjectVT == MVT::i1)
2893 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2898 ArgSize = PtrByteSize;
2900 // All int arguments reserve stack space in the Darwin ABI.
2901 ArgOffset += PtrByteSize;
2905 case MVT::i64: // PPC64
2906 if (GPR_idx != Num_GPR_Regs) {
2907 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2908 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2910 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2911 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2912 // value to MVT::i64 and then truncate to the correct register size.
2913 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2918 ArgSize = PtrByteSize;
2920 // All int arguments reserve stack space in the Darwin ABI.
2926 // Every 4 bytes of argument space consumes one of the GPRs available for
2927 // argument passing.
2928 if (GPR_idx != Num_GPR_Regs) {
2930 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2933 if (FPR_idx != Num_FPR_Regs) {
2936 if (ObjectVT == MVT::f32)
2937 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2939 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2941 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2947 // All FP arguments reserve stack space in the Darwin ABI.
2948 ArgOffset += isPPC64 ? 8 : ObjSize;
2954 // Note that vector arguments in registers don't reserve stack space,
2955 // except in varargs functions.
2956 if (VR_idx != Num_VR_Regs) {
2957 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2958 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2960 while ((ArgOffset % 16) != 0) {
2961 ArgOffset += PtrByteSize;
2962 if (GPR_idx != Num_GPR_Regs)
2966 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2970 if (!isVarArg && !isPPC64) {
2971 // Vectors go after all the nonvectors.
2972 CurArgOffset = VecArgOffset;
2975 // Vectors are aligned.
2976 ArgOffset = ((ArgOffset+15)/16)*16;
2977 CurArgOffset = ArgOffset;
2985 // We need to load the argument to a virtual register if we determined above
2986 // that we ran out of physical registers of the appropriate type.
2988 int FI = MFI->CreateFixedObject(ObjSize,
2989 CurArgOffset + (ArgSize - ObjSize),
2991 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2992 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2993 false, false, false, 0);
2996 InVals.push_back(ArgVal);
2999 // Set the size that is at least reserved in caller of this function. Tail
3000 // call optimized functions' reserved stack space needs to be aligned so that
3001 // taking the difference between two stack areas will result in an aligned
3003 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
3005 // If the function takes variable number of arguments, make a frame index for
3006 // the start of the first vararg value... for expansion of llvm.va_start.
3008 int Depth = ArgOffset;
3010 FuncInfo->setVarArgsFrameIndex(
3011 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3013 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3015 // If this function is vararg, store any remaining integer argument regs
3016 // to their spots on the stack so that they may be loaded by deferencing the
3017 // result of va_next.
3018 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3022 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3024 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3026 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3027 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3028 MachinePointerInfo(), false, false, 0);
3029 MemOps.push_back(Store);
3030 // Increment the address by four for the next argument to store
3031 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3032 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3036 if (!MemOps.empty())
3037 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3042 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
3043 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
3045 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
3049 const SmallVectorImpl<ISD::OutputArg>
3051 const SmallVectorImpl<SDValue> &OutVals,
3052 unsigned &nAltivecParamsAtEnd) {
3053 // Count how many bytes are to be pushed on the stack, including the linkage
3054 // area, and parameter passing area. We start with 24/48 bytes, which is
3055 // prereserved space for [SP][CR][LR][3 x unused].
3056 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
3057 unsigned NumOps = Outs.size();
3058 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3060 // Add up all the space actually used.
3061 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
3062 // they all go in registers, but we must reserve stack space for them for
3063 // possible use by the caller. In varargs or 64-bit calls, parameters are
3064 // assigned stack space in order, with padding so Altivec parameters are
3066 nAltivecParamsAtEnd = 0;
3067 for (unsigned i = 0; i != NumOps; ++i) {
3068 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3069 EVT ArgVT = Outs[i].VT;
3070 // Varargs Altivec parameters are padded to a 16 byte boundary.
3071 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
3072 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8 ||
3073 ArgVT==MVT::v2f64 || ArgVT==MVT::v2i64) {
3074 if (!isVarArg && !isPPC64) {
3075 // Non-varargs Altivec parameters go after all the non-Altivec
3076 // parameters; handle those later so we know how much padding we need.
3077 nAltivecParamsAtEnd++;
3080 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
3081 NumBytes = ((NumBytes+15)/16)*16;
3083 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3086 // Allow for Altivec parameters at the end, if needed.
3087 if (nAltivecParamsAtEnd) {
3088 NumBytes = ((NumBytes+15)/16)*16;
3089 NumBytes += 16*nAltivecParamsAtEnd;
3092 // The prolog code of the callee may store up to 8 GPR argument registers to
3093 // the stack, allowing va_start to index over them in memory if its varargs.
3094 // Because we cannot tell if this is needed on the caller side, we have to
3095 // conservatively assume that it is needed. As such, make sure we have at
3096 // least enough stack space for the caller to store the 8 GPRs.
3097 NumBytes = std::max(NumBytes,
3098 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
3100 // Tail call needs the stack to be aligned.
3101 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
3102 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
3103 getFrameLowering()->getStackAlignment();
3104 unsigned AlignMask = TargetAlign-1;
3105 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3111 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3112 /// adjusted to accommodate the arguments for the tailcall.
3113 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3114 unsigned ParamSize) {
3116 if (!isTailCall) return 0;
3118 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3119 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3120 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3121 // Remember only if the new adjustement is bigger.
3122 if (SPDiff < FI->getTailCallSPDelta())
3123 FI->setTailCallSPDelta(SPDiff);
3128 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3129 /// for tail call optimization. Targets which want to do tail call
3130 /// optimization should implement this function.
3132 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3133 CallingConv::ID CalleeCC,
3135 const SmallVectorImpl<ISD::InputArg> &Ins,
3136 SelectionDAG& DAG) const {
3137 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3140 // Variable argument functions are not supported.
3144 MachineFunction &MF = DAG.getMachineFunction();
3145 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3146 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3147 // Functions containing by val parameters are not supported.
3148 for (unsigned i = 0; i != Ins.size(); i++) {
3149 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3150 if (Flags.isByVal()) return false;
3153 // Non-PIC/GOT tail calls are supported.
3154 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3157 // At the moment we can only do local tail calls (in same module, hidden
3158 // or protected) if we are generating PIC.
3159 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3160 return G->getGlobal()->hasHiddenVisibility()
3161 || G->getGlobal()->hasProtectedVisibility();
3167 /// isCallCompatibleAddress - Return the immediate to use if the specified
3168 /// 32-bit value is representable in the immediate field of a BxA instruction.
3169 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3170 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3171 if (!C) return nullptr;
3173 int Addr = C->getZExtValue();
3174 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3175 SignExtend32<26>(Addr) != Addr)
3176 return nullptr; // Top 6 bits have to be sext of immediate.
3178 return DAG.getConstant((int)C->getZExtValue() >> 2,
3179 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3184 struct TailCallArgumentInfo {
3189 TailCallArgumentInfo() : FrameIdx(0) {}
3194 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3196 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3198 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3199 SmallVectorImpl<SDValue> &MemOpChains,
3201 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3202 SDValue Arg = TailCallArgs[i].Arg;
3203 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3204 int FI = TailCallArgs[i].FrameIdx;
3205 // Store relative to framepointer.
3206 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3207 MachinePointerInfo::getFixedStack(FI),
3212 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3213 /// the appropriate stack slot for the tail call optimized function call.
3214 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3215 MachineFunction &MF,
3224 // Calculate the new stack slot for the return address.
3225 int SlotSize = isPPC64 ? 8 : 4;
3226 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3228 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3229 NewRetAddrLoc, true);
3230 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3231 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3232 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3233 MachinePointerInfo::getFixedStack(NewRetAddr),
3236 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3237 // slot as the FP is never overwritten.
3240 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3241 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3243 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3244 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3245 MachinePointerInfo::getFixedStack(NewFPIdx),
3252 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3253 /// the position of the argument.
3255 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3256 SDValue Arg, int SPDiff, unsigned ArgOffset,
3257 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3258 int Offset = ArgOffset + SPDiff;
3259 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3260 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3261 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3262 SDValue FIN = DAG.getFrameIndex(FI, VT);
3263 TailCallArgumentInfo Info;
3265 Info.FrameIdxOp = FIN;
3267 TailCallArguments.push_back(Info);
3270 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3271 /// stack slot. Returns the chain as result and the loaded frame pointers in
3272 /// LROpOut/FPOpout. Used when tail calling.
3273 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3281 // Load the LR and FP stack slot for later adjusting.
3282 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3283 LROpOut = getReturnAddrFrameIndex(DAG);
3284 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3285 false, false, false, 0);
3286 Chain = SDValue(LROpOut.getNode(), 1);
3288 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3289 // slot as the FP is never overwritten.
3291 FPOpOut = getFramePointerFrameIndex(DAG);
3292 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3293 false, false, false, 0);
3294 Chain = SDValue(FPOpOut.getNode(), 1);
3300 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3301 /// by "Src" to address "Dst" of size "Size". Alignment information is
3302 /// specified by the specific parameter attribute. The copy will be passed as
3303 /// a byval function parameter.
3304 /// Sometimes what we are copying is the end of a larger object, the part that
3305 /// does not fit in registers.
3307 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3308 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3310 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3311 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3312 false, false, MachinePointerInfo(),
3313 MachinePointerInfo());
3316 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3319 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3320 SDValue Arg, SDValue PtrOff, int SPDiff,
3321 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3322 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3323 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3325 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3330 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3332 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3333 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3334 DAG.getConstant(ArgOffset, PtrVT));
3336 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3337 MachinePointerInfo(), false, false, 0));
3338 // Calculate and remember argument location.
3339 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3344 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3345 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3346 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3347 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3348 MachineFunction &MF = DAG.getMachineFunction();
3350 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3351 // might overwrite each other in case of tail call optimization.
3352 SmallVector<SDValue, 8> MemOpChains2;
3353 // Do not flag preceding copytoreg stuff together with the following stuff.
3355 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3357 if (!MemOpChains2.empty())
3358 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3360 // Store the return address to the appropriate stack slot.
3361 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3362 isPPC64, isDarwinABI, dl);
3364 // Emit callseq_end just before tailcall node.
3365 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3366 DAG.getIntPtrConstant(0, true), InFlag, dl);
3367 InFlag = Chain.getValue(1);
3371 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3372 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3373 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3374 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3375 const PPCSubtarget &PPCSubTarget) {
3377 bool isPPC64 = PPCSubTarget.isPPC64();
3378 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3380 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3381 NodeTys.push_back(MVT::Other); // Returns a chain
3382 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3384 unsigned CallOpc = PPCISD::CALL;
3386 bool needIndirectCall = true;
3387 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3388 // If this is an absolute destination address, use the munged value.
3389 Callee = SDValue(Dest, 0);
3390 needIndirectCall = false;
3393 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3394 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3395 // Use indirect calls for ALL functions calls in JIT mode, since the
3396 // far-call stubs may be outside relocation limits for a BL instruction.
3397 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3398 unsigned OpFlags = 0;
3399 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3400 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3401 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3402 (G->getGlobal()->isDeclaration() ||
3403 G->getGlobal()->isWeakForLinker())) {
3404 // PC-relative references to external symbols should go through $stub,
3405 // unless we're building with the leopard linker or later, which
3406 // automatically synthesizes these stubs.
3407 OpFlags = PPCII::MO_DARWIN_STUB;
3410 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3411 // every direct call is) turn it into a TargetGlobalAddress /
3412 // TargetExternalSymbol node so that legalize doesn't hack it.
3413 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3414 Callee.getValueType(),
3416 needIndirectCall = false;
3420 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3421 unsigned char OpFlags = 0;
3423 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3424 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3425 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3426 // PC-relative references to external symbols should go through $stub,
3427 // unless we're building with the leopard linker or later, which
3428 // automatically synthesizes these stubs.
3429 OpFlags = PPCII::MO_DARWIN_STUB;
3432 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3434 needIndirectCall = false;
3437 if (needIndirectCall) {
3438 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3439 // to do the call, we can't use PPCISD::CALL.
3440 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3442 if (isSVR4ABI && isPPC64) {
3443 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3444 // entry point, but to the function descriptor (the function entry point
3445 // address is part of the function descriptor though).
3446 // The function descriptor is a three doubleword structure with the
3447 // following fields: function entry point, TOC base address and
3448 // environment pointer.
3449 // Thus for a call through a function pointer, the following actions need
3451 // 1. Save the TOC of the caller in the TOC save area of its stack
3452 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3453 // 2. Load the address of the function entry point from the function
3455 // 3. Load the TOC of the callee from the function descriptor into r2.
3456 // 4. Load the environment pointer from the function descriptor into
3458 // 5. Branch to the function entry point address.
3459 // 6. On return of the callee, the TOC of the caller needs to be
3460 // restored (this is done in FinishCall()).
3462 // All those operations are flagged together to ensure that no other
3463 // operations can be scheduled in between. E.g. without flagging the
3464 // operations together, a TOC access in the caller could be scheduled
3465 // between the load of the callee TOC and the branch to the callee, which
3466 // results in the TOC access going through the TOC of the callee instead
3467 // of going through the TOC of the caller, which leads to incorrect code.
3469 // Load the address of the function entry point from the function
3471 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3472 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3473 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3474 Chain = LoadFuncPtr.getValue(1);
3475 InFlag = LoadFuncPtr.getValue(2);
3477 // Load environment pointer into r11.
3478 // Offset of the environment pointer within the function descriptor.
3479 SDValue PtrOff = DAG.getIntPtrConstant(16);
3481 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3482 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3484 Chain = LoadEnvPtr.getValue(1);
3485 InFlag = LoadEnvPtr.getValue(2);
3487 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3489 Chain = EnvVal.getValue(0);
3490 InFlag = EnvVal.getValue(1);
3492 // Load TOC of the callee into r2. We are using a target-specific load
3493 // with r2 hard coded, because the result of a target-independent load
3494 // would never go directly into r2, since r2 is a reserved register (which
3495 // prevents the register allocator from allocating it), resulting in an
3496 // additional register being allocated and an unnecessary move instruction
3498 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3499 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3501 Chain = LoadTOCPtr.getValue(0);
3502 InFlag = LoadTOCPtr.getValue(1);
3504 MTCTROps[0] = Chain;
3505 MTCTROps[1] = LoadFuncPtr;
3506 MTCTROps[2] = InFlag;
3509 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3510 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3511 InFlag = Chain.getValue(1);
3514 NodeTys.push_back(MVT::Other);
3515 NodeTys.push_back(MVT::Glue);
3516 Ops.push_back(Chain);
3517 CallOpc = PPCISD::BCTRL;
3518 Callee.setNode(nullptr);
3519 // Add use of X11 (holding environment pointer)
3520 if (isSVR4ABI && isPPC64)
3521 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3522 // Add CTR register as callee so a bctr can be emitted later.
3524 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3527 // If this is a direct call, pass the chain and the callee.
3528 if (Callee.getNode()) {
3529 Ops.push_back(Chain);
3530 Ops.push_back(Callee);
3532 // If this is a tail call add stack pointer delta.
3534 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3536 // Add argument registers to the end of the list so that they are known live
3538 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3539 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3540 RegsToPass[i].second.getValueType()));
3546 bool isLocalCall(const SDValue &Callee)
3548 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3549 return !G->getGlobal()->isDeclaration() &&
3550 !G->getGlobal()->isWeakForLinker();
3555 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3556 CallingConv::ID CallConv, bool isVarArg,
3557 const SmallVectorImpl<ISD::InputArg> &Ins,
3558 SDLoc dl, SelectionDAG &DAG,
3559 SmallVectorImpl<SDValue> &InVals) const {
3561 SmallVector<CCValAssign, 16> RVLocs;
3562 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3563 getTargetMachine(), RVLocs, *DAG.getContext());
3564 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3566 // Copy all of the result registers out of their specified physreg.
3567 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3568 CCValAssign &VA = RVLocs[i];
3569 assert(VA.isRegLoc() && "Can only return in registers!");
3571 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3572 VA.getLocReg(), VA.getLocVT(), InFlag);
3573 Chain = Val.getValue(1);
3574 InFlag = Val.getValue(2);
3576 switch (VA.getLocInfo()) {
3577 default: llvm_unreachable("Unknown loc info!");
3578 case CCValAssign::Full: break;
3579 case CCValAssign::AExt:
3580 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3582 case CCValAssign::ZExt:
3583 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3584 DAG.getValueType(VA.getValVT()));
3585 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3587 case CCValAssign::SExt:
3588 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3589 DAG.getValueType(VA.getValVT()));
3590 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3594 InVals.push_back(Val);
3601 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3602 bool isTailCall, bool isVarArg,
3604 SmallVector<std::pair<unsigned, SDValue>, 8>
3606 SDValue InFlag, SDValue Chain,
3608 int SPDiff, unsigned NumBytes,
3609 const SmallVectorImpl<ISD::InputArg> &Ins,
3610 SmallVectorImpl<SDValue> &InVals) const {
3611 std::vector<EVT> NodeTys;
3612 SmallVector<SDValue, 8> Ops;
3613 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3614 isTailCall, RegsToPass, Ops, NodeTys,
3617 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3618 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3619 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3621 // When performing tail call optimization the callee pops its arguments off
3622 // the stack. Account for this here so these bytes can be pushed back on in
3623 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3624 int BytesCalleePops =
3625 (CallConv == CallingConv::Fast &&
3626 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3628 // Add a register mask operand representing the call-preserved registers.
3629 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3630 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3631 assert(Mask && "Missing call preserved mask for calling convention");
3632 Ops.push_back(DAG.getRegisterMask(Mask));
3634 if (InFlag.getNode())
3635 Ops.push_back(InFlag);
3639 assert(((Callee.getOpcode() == ISD::Register &&
3640 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3641 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3642 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3643 isa<ConstantSDNode>(Callee)) &&
3644 "Expecting an global address, external symbol, absolute value or register");
3646 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3649 // Add a NOP immediately after the branch instruction when using the 64-bit
3650 // SVR4 ABI. At link time, if caller and callee are in a different module and
3651 // thus have a different TOC, the call will be replaced with a call to a stub
3652 // function which saves the current TOC, loads the TOC of the callee and
3653 // branches to the callee. The NOP will be replaced with a load instruction
3654 // which restores the TOC of the caller from the TOC save slot of the current
3655 // stack frame. If caller and callee belong to the same module (and have the
3656 // same TOC), the NOP will remain unchanged.
3658 bool needsTOCRestore = false;
3659 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3660 if (CallOpc == PPCISD::BCTRL) {
3661 // This is a call through a function pointer.
3662 // Restore the caller TOC from the save area into R2.
3663 // See PrepareCall() for more information about calls through function
3664 // pointers in the 64-bit SVR4 ABI.
3665 // We are using a target-specific load with r2 hard coded, because the
3666 // result of a target-independent load would never go directly into r2,
3667 // since r2 is a reserved register (which prevents the register allocator
3668 // from allocating it), resulting in an additional register being
3669 // allocated and an unnecessary move instruction being generated.
3670 needsTOCRestore = true;
3671 } else if ((CallOpc == PPCISD::CALL) &&
3672 (!isLocalCall(Callee) ||
3673 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3674 // Otherwise insert NOP for non-local calls.
3675 CallOpc = PPCISD::CALL_NOP;
3679 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3680 InFlag = Chain.getValue(1);
3682 if (needsTOCRestore) {
3683 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3684 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3685 InFlag = Chain.getValue(1);
3688 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3689 DAG.getIntPtrConstant(BytesCalleePops, true),
3692 InFlag = Chain.getValue(1);
3694 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3695 Ins, dl, DAG, InVals);
3699 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3700 SmallVectorImpl<SDValue> &InVals) const {
3701 SelectionDAG &DAG = CLI.DAG;
3703 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3704 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3705 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3706 SDValue Chain = CLI.Chain;
3707 SDValue Callee = CLI.Callee;
3708 bool &isTailCall = CLI.IsTailCall;
3709 CallingConv::ID CallConv = CLI.CallConv;
3710 bool isVarArg = CLI.IsVarArg;
3713 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3716 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3717 report_fatal_error("failed to perform tail call elimination on a call "
3718 "site marked musttail");
3720 if (PPCSubTarget.isSVR4ABI()) {
3721 if (PPCSubTarget.isPPC64())
3722 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3723 isTailCall, Outs, OutVals, Ins,
3726 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3727 isTailCall, Outs, OutVals, Ins,
3731 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3732 isTailCall, Outs, OutVals, Ins,
3737 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3738 CallingConv::ID CallConv, bool isVarArg,
3740 const SmallVectorImpl<ISD::OutputArg> &Outs,
3741 const SmallVectorImpl<SDValue> &OutVals,
3742 const SmallVectorImpl<ISD::InputArg> &Ins,
3743 SDLoc dl, SelectionDAG &DAG,
3744 SmallVectorImpl<SDValue> &InVals) const {
3745 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3746 // of the 32-bit SVR4 ABI stack frame layout.
3748 assert((CallConv == CallingConv::C ||
3749 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3751 unsigned PtrByteSize = 4;
3753 MachineFunction &MF = DAG.getMachineFunction();
3755 // Mark this function as potentially containing a function that contains a
3756 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3757 // and restoring the callers stack pointer in this functions epilog. This is
3758 // done because by tail calling the called function might overwrite the value
3759 // in this function's (MF) stack pointer stack slot 0(SP).
3760 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3761 CallConv == CallingConv::Fast)
3762 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3764 // Count how many bytes are to be pushed on the stack, including the linkage
3765 // area, parameter list area and the part of the local variable space which
3766 // contains copies of aggregates which are passed by value.
3768 // Assign locations to all of the outgoing arguments.
3769 SmallVector<CCValAssign, 16> ArgLocs;
3770 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3771 getTargetMachine(), ArgLocs, *DAG.getContext());
3773 // Reserve space for the linkage area on the stack.
3774 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3777 // Handle fixed and variable vector arguments differently.
3778 // Fixed vector arguments go into registers as long as registers are
3779 // available. Variable vector arguments always go into memory.
3780 unsigned NumArgs = Outs.size();
3782 for (unsigned i = 0; i != NumArgs; ++i) {
3783 MVT ArgVT = Outs[i].VT;
3784 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3787 if (Outs[i].IsFixed) {
3788 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3791 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3797 errs() << "Call operand #" << i << " has unhandled type "
3798 << EVT(ArgVT).getEVTString() << "\n";
3800 llvm_unreachable(nullptr);
3804 // All arguments are treated the same.
3805 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3808 // Assign locations to all of the outgoing aggregate by value arguments.
3809 SmallVector<CCValAssign, 16> ByValArgLocs;
3810 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3811 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3813 // Reserve stack space for the allocations in CCInfo.
3814 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3816 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3818 // Size of the linkage area, parameter list area and the part of the local
3819 // space variable where copies of aggregates which are passed by value are
3821 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3823 // Calculate by how many bytes the stack has to be adjusted in case of tail
3824 // call optimization.
3825 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3827 // Adjust the stack pointer for the new arguments...
3828 // These operations are automatically eliminated by the prolog/epilog pass
3829 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3831 SDValue CallSeqStart = Chain;
3833 // Load the return address and frame pointer so it can be moved somewhere else
3836 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3839 // Set up a copy of the stack pointer for use loading and storing any
3840 // arguments that may not fit in the registers available for argument
3842 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3844 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3845 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3846 SmallVector<SDValue, 8> MemOpChains;
3848 bool seenFloatArg = false;
3849 // Walk the register/memloc assignments, inserting copies/loads.
3850 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3853 CCValAssign &VA = ArgLocs[i];
3854 SDValue Arg = OutVals[i];
3855 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3857 if (Flags.isByVal()) {
3858 // Argument is an aggregate which is passed by value, thus we need to
3859 // create a copy of it in the local variable space of the current stack
3860 // frame (which is the stack frame of the caller) and pass the address of
3861 // this copy to the callee.
3862 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3863 CCValAssign &ByValVA = ByValArgLocs[j++];
3864 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3866 // Memory reserved in the local variable space of the callers stack frame.
3867 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3869 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3870 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3872 // Create a copy of the argument in the local area of the current
3874 SDValue MemcpyCall =
3875 CreateCopyOfByValArgument(Arg, PtrOff,
3876 CallSeqStart.getNode()->getOperand(0),
3879 // This must go outside the CALLSEQ_START..END.
3880 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3881 CallSeqStart.getNode()->getOperand(1),
3883 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3884 NewCallSeqStart.getNode());
3885 Chain = CallSeqStart = NewCallSeqStart;
3887 // Pass the address of the aggregate copy on the stack either in a
3888 // physical register or in the parameter list area of the current stack
3889 // frame to the callee.
3893 if (VA.isRegLoc()) {
3894 if (Arg.getValueType() == MVT::i1)
3895 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3897 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3898 // Put argument in a physical register.
3899 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3901 // Put argument in the parameter list area of the current stack frame.
3902 assert(VA.isMemLoc());
3903 unsigned LocMemOffset = VA.getLocMemOffset();
3906 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3907 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3909 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3910 MachinePointerInfo(),
3913 // Calculate and remember argument location.
3914 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3920 if (!MemOpChains.empty())
3921 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3923 // Build a sequence of copy-to-reg nodes chained together with token chain
3924 // and flag operands which copy the outgoing args into the appropriate regs.
3926 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3927 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3928 RegsToPass[i].second, InFlag);
3929 InFlag = Chain.getValue(1);
3932 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3935 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3936 SDValue Ops[] = { Chain, InFlag };
3938 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3939 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
3941 InFlag = Chain.getValue(1);
3945 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3946 false, TailCallArguments);
3948 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3949 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3953 // Copy an argument into memory, being careful to do this outside the
3954 // call sequence for the call to which the argument belongs.
3956 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3957 SDValue CallSeqStart,
3958 ISD::ArgFlagsTy Flags,
3961 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3962 CallSeqStart.getNode()->getOperand(0),
3964 // The MEMCPY must go outside the CALLSEQ_START..END.
3965 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3966 CallSeqStart.getNode()->getOperand(1),
3968 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3969 NewCallSeqStart.getNode());
3970 return NewCallSeqStart;
3974 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3975 CallingConv::ID CallConv, bool isVarArg,
3977 const SmallVectorImpl<ISD::OutputArg> &Outs,
3978 const SmallVectorImpl<SDValue> &OutVals,
3979 const SmallVectorImpl<ISD::InputArg> &Ins,
3980 SDLoc dl, SelectionDAG &DAG,
3981 SmallVectorImpl<SDValue> &InVals) const {
3983 unsigned NumOps = Outs.size();
3985 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3986 unsigned PtrByteSize = 8;
3988 MachineFunction &MF = DAG.getMachineFunction();
3990 // Mark this function as potentially containing a function that contains a
3991 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3992 // and restoring the callers stack pointer in this functions epilog. This is
3993 // done because by tail calling the called function might overwrite the value
3994 // in this function's (MF) stack pointer stack slot 0(SP).
3995 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3996 CallConv == CallingConv::Fast)
3997 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3999 unsigned nAltivecParamsAtEnd = 0;
4001 // Count how many bytes are to be pushed on the stack, including the linkage
4002 // area, and parameter passing area. We start with at least 48 bytes, which
4003 // is reserved space for [SP][CR][LR][3 x unused].
4004 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
4007 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
4008 Outs, OutVals, nAltivecParamsAtEnd);
4010 // Calculate by how many bytes the stack has to be adjusted in case of tail
4011 // call optimization.
4012 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4014 // To protect arguments on the stack from being clobbered in a tail call,
4015 // force all the loads to happen before doing any other lowering.
4017 Chain = DAG.getStackArgumentTokenFactor(Chain);
4019 // Adjust the stack pointer for the new arguments...
4020 // These operations are automatically eliminated by the prolog/epilog pass
4021 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4023 SDValue CallSeqStart = Chain;
4025 // Load the return address and frame pointer so it can be move somewhere else
4028 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4031 // Set up a copy of the stack pointer for use loading and storing any
4032 // arguments that may not fit in the registers available for argument
4034 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4036 // Figure out which arguments are going to go in registers, and which in
4037 // memory. Also, if this is a vararg function, floating point operations
4038 // must be stored to our stack, and loaded into integer regs as well, if
4039 // any integer regs are available for argument passing.
4040 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
4041 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4043 static const MCPhysReg GPR[] = {
4044 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4045 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4047 static const MCPhysReg *FPR = GetFPR();
4049 static const MCPhysReg VR[] = {
4050 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4051 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4053 static const MCPhysReg VSRH[] = {
4054 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4055 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4058 const unsigned NumGPRs = array_lengthof(GPR);
4059 const unsigned NumFPRs = 13;
4060 const unsigned NumVRs = array_lengthof(VR);
4062 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4063 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4065 SmallVector<SDValue, 8> MemOpChains;
4066 for (unsigned i = 0; i != NumOps; ++i) {
4067 SDValue Arg = OutVals[i];
4068 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4070 // PtrOff will be used to store the current argument to the stack if a
4071 // register cannot be found for it.
4074 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4076 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4078 // Promote integers to 64-bit values.
4079 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4080 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4081 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4082 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4085 // FIXME memcpy is used way more than necessary. Correctness first.
4086 // Note: "by value" is code for passing a structure by value, not
4088 if (Flags.isByVal()) {
4089 // Note: Size includes alignment padding, so
4090 // struct x { short a; char b; }
4091 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4092 // These are the proper values we need for right-justifying the
4093 // aggregate in a parameter register.
4094 unsigned Size = Flags.getByValSize();
4096 // An empty aggregate parameter takes up no storage and no
4101 unsigned BVAlign = Flags.getByValAlign();
4103 if (BVAlign % PtrByteSize != 0)
4105 "ByVal alignment is not a multiple of the pointer size");
4107 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
4110 // All aggregates smaller than 8 bytes must be passed right-justified.
4111 if (Size==1 || Size==2 || Size==4) {
4112 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4113 if (GPR_idx != NumGPRs) {
4114 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4115 MachinePointerInfo(), VT,
4117 MemOpChains.push_back(Load.getValue(1));
4118 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4120 ArgOffset += PtrByteSize;
4125 if (GPR_idx == NumGPRs && Size < 8) {
4126 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4127 PtrOff.getValueType());
4128 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4129 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4132 ArgOffset += PtrByteSize;
4135 // Copy entire object into memory. There are cases where gcc-generated
4136 // code assumes it is there, even if it could be put entirely into
4137 // registers. (This is not what the doc says.)
4139 // FIXME: The above statement is likely due to a misunderstanding of the
4140 // documents. All arguments must be copied into the parameter area BY
4141 // THE CALLEE in the event that the callee takes the address of any
4142 // formal argument. That has not yet been implemented. However, it is
4143 // reasonable to use the stack area as a staging area for the register
4146 // Skip this for small aggregates, as we will use the same slot for a
4147 // right-justified copy, below.
4149 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4153 // When a register is available, pass a small aggregate right-justified.
4154 if (Size < 8 && GPR_idx != NumGPRs) {
4155 // The easiest way to get this right-justified in a register
4156 // is to copy the structure into the rightmost portion of a
4157 // local variable slot, then load the whole slot into the
4159 // FIXME: The memcpy seems to produce pretty awful code for
4160 // small aggregates, particularly for packed ones.
4161 // FIXME: It would be preferable to use the slot in the
4162 // parameter save area instead of a new local variable.
4163 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4164 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4165 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4169 // Load the slot into the register.
4170 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4171 MachinePointerInfo(),
4172 false, false, false, 0);
4173 MemOpChains.push_back(Load.getValue(1));
4174 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4176 // Done with this argument.
4177 ArgOffset += PtrByteSize;
4181 // For aggregates larger than PtrByteSize, copy the pieces of the
4182 // object that fit into registers from the parameter save area.
4183 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4184 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4185 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4186 if (GPR_idx != NumGPRs) {
4187 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4188 MachinePointerInfo(),
4189 false, false, false, 0);
4190 MemOpChains.push_back(Load.getValue(1));
4191 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4192 ArgOffset += PtrByteSize;
4194 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4201 switch (Arg.getSimpleValueType().SimpleTy) {
4202 default: llvm_unreachable("Unexpected ValueType for argument!");
4206 if (GPR_idx != NumGPRs) {
4207 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4209 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4210 true, isTailCall, false, MemOpChains,
4211 TailCallArguments, dl);
4213 ArgOffset += PtrByteSize;
4217 if (FPR_idx != NumFPRs) {
4218 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4221 // A single float or an aggregate containing only a single float
4222 // must be passed right-justified in the stack doubleword, and
4223 // in the GPR, if one is available.
4225 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4226 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4227 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4231 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4232 MachinePointerInfo(), false, false, 0);
4233 MemOpChains.push_back(Store);
4235 // Float varargs are always shadowed in available integer registers
4236 if (GPR_idx != NumGPRs) {
4237 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4238 MachinePointerInfo(), false, false,
4240 MemOpChains.push_back(Load.getValue(1));
4241 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4243 } else if (GPR_idx != NumGPRs)
4244 // If we have any FPRs remaining, we may also have GPRs remaining.
4247 // Single-precision floating-point values are mapped to the
4248 // second (rightmost) word of the stack doubleword.
4249 if (Arg.getValueType() == MVT::f32) {
4250 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4251 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4254 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4255 true, isTailCall, false, MemOpChains,
4256 TailCallArguments, dl);
4267 // These go aligned on the stack, or in the corresponding R registers
4268 // when within range. The Darwin PPC ABI doc claims they also go in
4269 // V registers; in fact gcc does this only for arguments that are
4270 // prototyped, not for those that match the ... We do it for all
4271 // arguments, seems to work.
4272 while (ArgOffset % 16 !=0) {
4273 ArgOffset += PtrByteSize;
4274 if (GPR_idx != NumGPRs)
4277 // We could elide this store in the case where the object fits
4278 // entirely in R registers. Maybe later.
4279 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4280 DAG.getConstant(ArgOffset, PtrVT));
4281 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4282 MachinePointerInfo(), false, false, 0);
4283 MemOpChains.push_back(Store);
4284 if (VR_idx != NumVRs) {
4285 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4286 MachinePointerInfo(),
4287 false, false, false, 0);
4288 MemOpChains.push_back(Load.getValue(1));
4290 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4291 Arg.getSimpleValueType() == MVT::v2i64) ?
4292 VSRH[VR_idx] : VR[VR_idx];
4295 RegsToPass.push_back(std::make_pair(VReg, Load));
4298 for (unsigned i=0; i<16; i+=PtrByteSize) {
4299 if (GPR_idx == NumGPRs)
4301 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4302 DAG.getConstant(i, PtrVT));
4303 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4304 false, false, false, 0);
4305 MemOpChains.push_back(Load.getValue(1));
4306 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4311 // Non-varargs Altivec params generally go in registers, but have
4312 // stack space allocated at the end.
4313 if (VR_idx != NumVRs) {
4314 // Doesn't have GPR space allocated.
4315 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4316 Arg.getSimpleValueType() == MVT::v2i64) ?
4317 VSRH[VR_idx] : VR[VR_idx];
4320 RegsToPass.push_back(std::make_pair(VReg, Arg));
4322 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4323 true, isTailCall, true, MemOpChains,
4324 TailCallArguments, dl);
4331 if (!MemOpChains.empty())
4332 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4334 // Check if this is an indirect call (MTCTR/BCTRL).
4335 // See PrepareCall() for more information about calls through function
4336 // pointers in the 64-bit SVR4 ABI.
4338 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4339 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4340 !isBLACompatibleAddress(Callee, DAG)) {
4341 // Load r2 into a virtual register and store it to the TOC save area.
4342 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4343 // TOC save area offset.
4344 SDValue PtrOff = DAG.getIntPtrConstant(40);
4345 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4346 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4348 // R12 must contain the address of an indirect callee. This does not
4349 // mean the MTCTR instruction must use R12; it's easier to model this
4350 // as an extra parameter, so do that.
4351 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4354 // Build a sequence of copy-to-reg nodes chained together with token chain
4355 // and flag operands which copy the outgoing args into the appropriate regs.
4357 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4358 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4359 RegsToPass[i].second, InFlag);
4360 InFlag = Chain.getValue(1);
4364 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4365 FPOp, true, TailCallArguments);
4367 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4368 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4373 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4374 CallingConv::ID CallConv, bool isVarArg,
4376 const SmallVectorImpl<ISD::OutputArg> &Outs,
4377 const SmallVectorImpl<SDValue> &OutVals,
4378 const SmallVectorImpl<ISD::InputArg> &Ins,
4379 SDLoc dl, SelectionDAG &DAG,
4380 SmallVectorImpl<SDValue> &InVals) const {
4382 unsigned NumOps = Outs.size();
4384 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4385 bool isPPC64 = PtrVT == MVT::i64;
4386 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4388 MachineFunction &MF = DAG.getMachineFunction();
4390 // Mark this function as potentially containing a function that contains a
4391 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4392 // and restoring the callers stack pointer in this functions epilog. This is
4393 // done because by tail calling the called function might overwrite the value
4394 // in this function's (MF) stack pointer stack slot 0(SP).
4395 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4396 CallConv == CallingConv::Fast)
4397 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4399 unsigned nAltivecParamsAtEnd = 0;
4401 // Count how many bytes are to be pushed on the stack, including the linkage
4402 // area, and parameter passing area. We start with 24/48 bytes, which is
4403 // prereserved space for [SP][CR][LR][3 x unused].
4405 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4407 nAltivecParamsAtEnd);
4409 // Calculate by how many bytes the stack has to be adjusted in case of tail
4410 // call optimization.
4411 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4413 // To protect arguments on the stack from being clobbered in a tail call,
4414 // force all the loads to happen before doing any other lowering.
4416 Chain = DAG.getStackArgumentTokenFactor(Chain);
4418 // Adjust the stack pointer for the new arguments...
4419 // These operations are automatically eliminated by the prolog/epilog pass
4420 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4422 SDValue CallSeqStart = Chain;
4424 // Load the return address and frame pointer so it can be move somewhere else
4427 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4430 // Set up a copy of the stack pointer for use loading and storing any
4431 // arguments that may not fit in the registers available for argument
4435 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4437 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4439 // Figure out which arguments are going to go in registers, and which in
4440 // memory. Also, if this is a vararg function, floating point operations
4441 // must be stored to our stack, and loaded into integer regs as well, if
4442 // any integer regs are available for argument passing.
4443 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4444 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4446 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4447 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4448 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4450 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4451 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4452 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4454 static const MCPhysReg *FPR = GetFPR();
4456 static const MCPhysReg VR[] = {
4457 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4458 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4460 const unsigned NumGPRs = array_lengthof(GPR_32);
4461 const unsigned NumFPRs = 13;
4462 const unsigned NumVRs = array_lengthof(VR);
4464 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4466 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4467 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4469 SmallVector<SDValue, 8> MemOpChains;
4470 for (unsigned i = 0; i != NumOps; ++i) {
4471 SDValue Arg = OutVals[i];
4472 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4474 // PtrOff will be used to store the current argument to the stack if a
4475 // register cannot be found for it.
4478 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4480 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4482 // On PPC64, promote integers to 64-bit values.
4483 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4484 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4485 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4486 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4489 // FIXME memcpy is used way more than necessary. Correctness first.
4490 // Note: "by value" is code for passing a structure by value, not
4492 if (Flags.isByVal()) {
4493 unsigned Size = Flags.getByValSize();
4494 // Very small objects are passed right-justified. Everything else is
4495 // passed left-justified.
4496 if (Size==1 || Size==2) {
4497 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4498 if (GPR_idx != NumGPRs) {
4499 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4500 MachinePointerInfo(), VT,
4502 MemOpChains.push_back(Load.getValue(1));
4503 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4505 ArgOffset += PtrByteSize;
4507 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4508 PtrOff.getValueType());
4509 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4510 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4513 ArgOffset += PtrByteSize;
4517 // Copy entire object into memory. There are cases where gcc-generated
4518 // code assumes it is there, even if it could be put entirely into
4519 // registers. (This is not what the doc says.)
4520 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4524 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4525 // copy the pieces of the object that fit into registers from the
4526 // parameter save area.
4527 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4528 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4529 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4530 if (GPR_idx != NumGPRs) {
4531 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4532 MachinePointerInfo(),
4533 false, false, false, 0);
4534 MemOpChains.push_back(Load.getValue(1));
4535 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4536 ArgOffset += PtrByteSize;
4538 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4545 switch (Arg.getSimpleValueType().SimpleTy) {
4546 default: llvm_unreachable("Unexpected ValueType for argument!");
4550 if (GPR_idx != NumGPRs) {
4551 if (Arg.getValueType() == MVT::i1)
4552 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4554 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4556 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4557 isPPC64, isTailCall, false, MemOpChains,
4558 TailCallArguments, dl);
4560 ArgOffset += PtrByteSize;
4564 if (FPR_idx != NumFPRs) {
4565 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4568 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4569 MachinePointerInfo(), false, false, 0);
4570 MemOpChains.push_back(Store);
4572 // Float varargs are always shadowed in available integer registers
4573 if (GPR_idx != NumGPRs) {
4574 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4575 MachinePointerInfo(), false, false,
4577 MemOpChains.push_back(Load.getValue(1));
4578 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4580 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4581 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4582 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4583 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4584 MachinePointerInfo(),
4585 false, false, false, 0);
4586 MemOpChains.push_back(Load.getValue(1));
4587 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4590 // If we have any FPRs remaining, we may also have GPRs remaining.
4591 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4593 if (GPR_idx != NumGPRs)
4595 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4596 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4600 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4601 isPPC64, isTailCall, false, MemOpChains,
4602 TailCallArguments, dl);
4606 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4613 // These go aligned on the stack, or in the corresponding R registers
4614 // when within range. The Darwin PPC ABI doc claims they also go in
4615 // V registers; in fact gcc does this only for arguments that are
4616 // prototyped, not for those that match the ... We do it for all
4617 // arguments, seems to work.
4618 while (ArgOffset % 16 !=0) {
4619 ArgOffset += PtrByteSize;
4620 if (GPR_idx != NumGPRs)
4623 // We could elide this store in the case where the object fits
4624 // entirely in R registers. Maybe later.
4625 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4626 DAG.getConstant(ArgOffset, PtrVT));
4627 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4628 MachinePointerInfo(), false, false, 0);
4629 MemOpChains.push_back(Store);
4630 if (VR_idx != NumVRs) {
4631 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4632 MachinePointerInfo(),
4633 false, false, false, 0);
4634 MemOpChains.push_back(Load.getValue(1));
4635 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4638 for (unsigned i=0; i<16; i+=PtrByteSize) {
4639 if (GPR_idx == NumGPRs)
4641 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4642 DAG.getConstant(i, PtrVT));
4643 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4644 false, false, false, 0);
4645 MemOpChains.push_back(Load.getValue(1));
4646 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4651 // Non-varargs Altivec params generally go in registers, but have
4652 // stack space allocated at the end.
4653 if (VR_idx != NumVRs) {
4654 // Doesn't have GPR space allocated.
4655 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4656 } else if (nAltivecParamsAtEnd==0) {
4657 // We are emitting Altivec params in order.
4658 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4659 isPPC64, isTailCall, true, MemOpChains,
4660 TailCallArguments, dl);
4666 // If all Altivec parameters fit in registers, as they usually do,
4667 // they get stack space following the non-Altivec parameters. We
4668 // don't track this here because nobody below needs it.
4669 // If there are more Altivec parameters than fit in registers emit
4671 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4673 // Offset is aligned; skip 1st 12 params which go in V registers.
4674 ArgOffset = ((ArgOffset+15)/16)*16;
4676 for (unsigned i = 0; i != NumOps; ++i) {
4677 SDValue Arg = OutVals[i];
4678 EVT ArgType = Outs[i].VT;
4679 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4680 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4683 // We are emitting Altivec params in order.
4684 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4685 isPPC64, isTailCall, true, MemOpChains,
4686 TailCallArguments, dl);
4693 if (!MemOpChains.empty())
4694 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4696 // On Darwin, R12 must contain the address of an indirect callee. This does
4697 // not mean the MTCTR instruction must use R12; it's easier to model this as
4698 // an extra parameter, so do that.
4700 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4701 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4702 !isBLACompatibleAddress(Callee, DAG))
4703 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4704 PPC::R12), Callee));
4706 // Build a sequence of copy-to-reg nodes chained together with token chain
4707 // and flag operands which copy the outgoing args into the appropriate regs.
4709 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4710 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4711 RegsToPass[i].second, InFlag);
4712 InFlag = Chain.getValue(1);
4716 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4717 FPOp, true, TailCallArguments);
4719 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4720 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4725 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4726 MachineFunction &MF, bool isVarArg,
4727 const SmallVectorImpl<ISD::OutputArg> &Outs,
4728 LLVMContext &Context) const {
4729 SmallVector<CCValAssign, 16> RVLocs;
4730 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4732 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4736 PPCTargetLowering::LowerReturn(SDValue Chain,
4737 CallingConv::ID CallConv, bool isVarArg,
4738 const SmallVectorImpl<ISD::OutputArg> &Outs,
4739 const SmallVectorImpl<SDValue> &OutVals,
4740 SDLoc dl, SelectionDAG &DAG) const {
4742 SmallVector<CCValAssign, 16> RVLocs;
4743 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4744 getTargetMachine(), RVLocs, *DAG.getContext());
4745 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4748 SmallVector<SDValue, 4> RetOps(1, Chain);
4750 // Copy the result values into the output registers.
4751 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4752 CCValAssign &VA = RVLocs[i];
4753 assert(VA.isRegLoc() && "Can only return in registers!");
4755 SDValue Arg = OutVals[i];
4757 switch (VA.getLocInfo()) {
4758 default: llvm_unreachable("Unknown loc info!");
4759 case CCValAssign::Full: break;
4760 case CCValAssign::AExt:
4761 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4763 case CCValAssign::ZExt:
4764 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4766 case CCValAssign::SExt:
4767 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4771 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4772 Flag = Chain.getValue(1);
4773 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4776 RetOps[0] = Chain; // Update chain.
4778 // Add the flag if we have it.
4780 RetOps.push_back(Flag);
4782 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
4785 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4786 const PPCSubtarget &Subtarget) const {
4787 // When we pop the dynamic allocation we need to restore the SP link.
4790 // Get the corect type for pointers.
4791 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4793 // Construct the stack pointer operand.
4794 bool isPPC64 = Subtarget.isPPC64();
4795 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4796 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4798 // Get the operands for the STACKRESTORE.
4799 SDValue Chain = Op.getOperand(0);
4800 SDValue SaveSP = Op.getOperand(1);
4802 // Load the old link SP.
4803 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4804 MachinePointerInfo(),
4805 false, false, false, 0);
4807 // Restore the stack pointer.
4808 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4810 // Store the old link SP.
4811 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4818 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4819 MachineFunction &MF = DAG.getMachineFunction();
4820 bool isPPC64 = PPCSubTarget.isPPC64();
4821 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4822 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4824 // Get current frame pointer save index. The users of this index will be
4825 // primarily DYNALLOC instructions.
4826 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4827 int RASI = FI->getReturnAddrSaveIndex();
4829 // If the frame pointer save index hasn't been defined yet.
4831 // Find out what the fix offset of the frame pointer save area.
4832 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4833 // Allocate the frame index for frame pointer save area.
4834 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4836 FI->setReturnAddrSaveIndex(RASI);
4838 return DAG.getFrameIndex(RASI, PtrVT);
4842 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4843 MachineFunction &MF = DAG.getMachineFunction();
4844 bool isPPC64 = PPCSubTarget.isPPC64();
4845 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4846 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4848 // Get current frame pointer save index. The users of this index will be
4849 // primarily DYNALLOC instructions.
4850 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4851 int FPSI = FI->getFramePointerSaveIndex();
4853 // If the frame pointer save index hasn't been defined yet.
4855 // Find out what the fix offset of the frame pointer save area.
4856 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4859 // Allocate the frame index for frame pointer save area.
4860 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4862 FI->setFramePointerSaveIndex(FPSI);
4864 return DAG.getFrameIndex(FPSI, PtrVT);
4867 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4869 const PPCSubtarget &Subtarget) const {
4871 SDValue Chain = Op.getOperand(0);
4872 SDValue Size = Op.getOperand(1);
4875 // Get the corect type for pointers.
4876 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4878 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4879 DAG.getConstant(0, PtrVT), Size);
4880 // Construct a node for the frame pointer save index.
4881 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4882 // Build a DYNALLOC node.
4883 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4884 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4885 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
4888 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4889 SelectionDAG &DAG) const {
4891 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4892 DAG.getVTList(MVT::i32, MVT::Other),
4893 Op.getOperand(0), Op.getOperand(1));
4896 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4897 SelectionDAG &DAG) const {
4899 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4900 Op.getOperand(0), Op.getOperand(1));
4903 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4904 assert(Op.getValueType() == MVT::i1 &&
4905 "Custom lowering only for i1 loads");
4907 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4910 LoadSDNode *LD = cast<LoadSDNode>(Op);
4912 SDValue Chain = LD->getChain();
4913 SDValue BasePtr = LD->getBasePtr();
4914 MachineMemOperand *MMO = LD->getMemOperand();
4916 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4917 BasePtr, MVT::i8, MMO);
4918 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4920 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4921 return DAG.getMergeValues(Ops, dl);
4924 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4925 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4926 "Custom lowering only for i1 stores");
4928 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4931 StoreSDNode *ST = cast<StoreSDNode>(Op);
4933 SDValue Chain = ST->getChain();
4934 SDValue BasePtr = ST->getBasePtr();
4935 SDValue Value = ST->getValue();
4936 MachineMemOperand *MMO = ST->getMemOperand();
4938 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4939 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4942 // FIXME: Remove this once the ANDI glue bug is fixed:
4943 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4944 assert(Op.getValueType() == MVT::i1 &&
4945 "Custom lowering only for i1 results");
4948 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4952 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4954 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4955 // Not FP? Not a fsel.
4956 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4957 !Op.getOperand(2).getValueType().isFloatingPoint())
4960 // We might be able to do better than this under some circumstances, but in
4961 // general, fsel-based lowering of select is a finite-math-only optimization.
4962 // For more information, see section F.3 of the 2.06 ISA specification.
4963 if (!DAG.getTarget().Options.NoInfsFPMath ||
4964 !DAG.getTarget().Options.NoNaNsFPMath)
4967 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4969 EVT ResVT = Op.getValueType();
4970 EVT CmpVT = Op.getOperand(0).getValueType();
4971 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4972 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4975 // If the RHS of the comparison is a 0.0, we don't need to do the
4976 // subtraction at all.
4978 if (isFloatingPointZero(RHS))
4980 default: break; // SETUO etc aren't handled by fsel.
4984 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4985 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4986 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4987 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4988 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4989 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4990 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4993 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4996 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4997 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4998 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5001 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5004 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5005 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5006 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5007 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5012 default: break; // SETUO etc aren't handled by fsel.
5016 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5017 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5018 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5019 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5020 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5021 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5022 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5023 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5026 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5027 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5028 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5029 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5032 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5033 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5034 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5035 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5038 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5039 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5040 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5041 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5044 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5045 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5046 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5047 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5052 // FIXME: Split this code up when LegalizeDAGTypes lands.
5053 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5055 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5056 SDValue Src = Op.getOperand(0);
5057 if (Src.getValueType() == MVT::f32)
5058 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5061 switch (Op.getSimpleValueType().SimpleTy) {
5062 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5064 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5065 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5070 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
5071 "i64 FP_TO_UINT is supported only with FPCVT");
5072 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5078 // Convert the FP value to an int value through memory.
5079 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
5080 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
5081 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5082 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5083 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5085 // Emit a store to the stack slot.
5088 MachineFunction &MF = DAG.getMachineFunction();
5089 MachineMemOperand *MMO =
5090 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5091 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5092 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5093 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5095 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5096 MPI, false, false, 0);
5098 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5100 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5101 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5102 DAG.getConstant(4, FIPtr.getValueType()));
5103 MPI = MachinePointerInfo();
5106 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5107 false, false, false, 0);
5110 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5111 SelectionDAG &DAG) const {
5113 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5114 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5117 if (Op.getOperand(0).getValueType() == MVT::i1)
5118 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5119 DAG.getConstantFP(1.0, Op.getValueType()),
5120 DAG.getConstantFP(0.0, Op.getValueType()));
5122 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
5123 "UINT_TO_FP is supported only with FPCVT");
5125 // If we have FCFIDS, then use it when converting to single-precision.
5126 // Otherwise, convert to double-precision and then round.
5127 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5128 (Op.getOpcode() == ISD::UINT_TO_FP ?
5129 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5130 (Op.getOpcode() == ISD::UINT_TO_FP ?
5131 PPCISD::FCFIDU : PPCISD::FCFID);
5132 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5133 MVT::f32 : MVT::f64;
5135 if (Op.getOperand(0).getValueType() == MVT::i64) {
5136 SDValue SINT = Op.getOperand(0);
5137 // When converting to single-precision, we actually need to convert
5138 // to double-precision first and then round to single-precision.
5139 // To avoid double-rounding effects during that operation, we have
5140 // to prepare the input operand. Bits that might be truncated when
5141 // converting to double-precision are replaced by a bit that won't
5142 // be lost at this stage, but is below the single-precision rounding
5145 // However, if -enable-unsafe-fp-math is in effect, accept double
5146 // rounding to avoid the extra overhead.
5147 if (Op.getValueType() == MVT::f32 &&
5148 !PPCSubTarget.hasFPCVT() &&
5149 !DAG.getTarget().Options.UnsafeFPMath) {
5151 // Twiddle input to make sure the low 11 bits are zero. (If this
5152 // is the case, we are guaranteed the value will fit into the 53 bit
5153 // mantissa of an IEEE double-precision value without rounding.)
5154 // If any of those low 11 bits were not zero originally, make sure
5155 // bit 12 (value 2048) is set instead, so that the final rounding
5156 // to single-precision gets the correct result.
5157 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5158 SINT, DAG.getConstant(2047, MVT::i64));
5159 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5160 Round, DAG.getConstant(2047, MVT::i64));
5161 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5162 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5163 Round, DAG.getConstant(-2048, MVT::i64));
5165 // However, we cannot use that value unconditionally: if the magnitude
5166 // of the input value is small, the bit-twiddling we did above might
5167 // end up visibly changing the output. Fortunately, in that case, we
5168 // don't need to twiddle bits since the original input will convert
5169 // exactly to double-precision floating-point already. Therefore,
5170 // construct a conditional to use the original value if the top 11
5171 // bits are all sign-bit copies, and use the rounded value computed
5173 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5174 SINT, DAG.getConstant(53, MVT::i32));
5175 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5176 Cond, DAG.getConstant(1, MVT::i64));
5177 Cond = DAG.getSetCC(dl, MVT::i32,
5178 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5180 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5183 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5184 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5186 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5187 FP = DAG.getNode(ISD::FP_ROUND, dl,
5188 MVT::f32, FP, DAG.getIntPtrConstant(0));
5192 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5193 "Unhandled INT_TO_FP type in custom expander!");
5194 // Since we only generate this in 64-bit mode, we can take advantage of
5195 // 64-bit registers. In particular, sign extend the input value into the
5196 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5197 // then lfd it and fcfid it.
5198 MachineFunction &MF = DAG.getMachineFunction();
5199 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5200 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5203 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5204 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5205 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5207 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5208 MachinePointerInfo::getFixedStack(FrameIdx),
5211 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5212 "Expected an i32 store");
5213 MachineMemOperand *MMO =
5214 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5215 MachineMemOperand::MOLoad, 4, 4);
5216 SDValue Ops[] = { Store, FIdx };
5217 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5218 PPCISD::LFIWZX : PPCISD::LFIWAX,
5219 dl, DAG.getVTList(MVT::f64, MVT::Other),
5220 Ops, MVT::i32, MMO);
5222 assert(PPCSubTarget.isPPC64() &&
5223 "i32->FP without LFIWAX supported only on PPC64");
5225 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5226 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5228 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5231 // STD the extended value into the stack slot.
5232 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5233 MachinePointerInfo::getFixedStack(FrameIdx),
5236 // Load the value as a double.
5237 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5238 MachinePointerInfo::getFixedStack(FrameIdx),
5239 false, false, false, 0);
5242 // FCFID it and return it.
5243 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5244 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5245 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5249 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5250 SelectionDAG &DAG) const {
5253 The rounding mode is in bits 30:31 of FPSR, and has the following
5260 FLT_ROUNDS, on the other hand, expects the following:
5267 To perform the conversion, we do:
5268 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5271 MachineFunction &MF = DAG.getMachineFunction();
5272 EVT VT = Op.getValueType();
5273 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5275 // Save FP Control Word to register
5277 MVT::f64, // return register
5278 MVT::Glue // unused in this context
5280 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5282 // Save FP register to stack slot
5283 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5284 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5285 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5286 StackSlot, MachinePointerInfo(), false, false,0);
5288 // Load FP Control Word from low 32 bits of stack slot.
5289 SDValue Four = DAG.getConstant(4, PtrVT);
5290 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5291 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5292 false, false, false, 0);
5294 // Transform as necessary
5296 DAG.getNode(ISD::AND, dl, MVT::i32,
5297 CWD, DAG.getConstant(3, MVT::i32));
5299 DAG.getNode(ISD::SRL, dl, MVT::i32,
5300 DAG.getNode(ISD::AND, dl, MVT::i32,
5301 DAG.getNode(ISD::XOR, dl, MVT::i32,
5302 CWD, DAG.getConstant(3, MVT::i32)),
5303 DAG.getConstant(3, MVT::i32)),
5304 DAG.getConstant(1, MVT::i32));
5307 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5309 return DAG.getNode((VT.getSizeInBits() < 16 ?
5310 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5313 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5314 EVT VT = Op.getValueType();
5315 unsigned BitWidth = VT.getSizeInBits();
5317 assert(Op.getNumOperands() == 3 &&
5318 VT == Op.getOperand(1).getValueType() &&
5321 // Expand into a bunch of logical ops. Note that these ops
5322 // depend on the PPC behavior for oversized shift amounts.
5323 SDValue Lo = Op.getOperand(0);
5324 SDValue Hi = Op.getOperand(1);
5325 SDValue Amt = Op.getOperand(2);
5326 EVT AmtVT = Amt.getValueType();
5328 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5329 DAG.getConstant(BitWidth, AmtVT), Amt);
5330 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5331 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5332 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5333 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5334 DAG.getConstant(-BitWidth, AmtVT));
5335 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5336 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5337 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5338 SDValue OutOps[] = { OutLo, OutHi };
5339 return DAG.getMergeValues(OutOps, dl);
5342 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5343 EVT VT = Op.getValueType();
5345 unsigned BitWidth = VT.getSizeInBits();
5346 assert(Op.getNumOperands() == 3 &&
5347 VT == Op.getOperand(1).getValueType() &&
5350 // Expand into a bunch of logical ops. Note that these ops
5351 // depend on the PPC behavior for oversized shift amounts.
5352 SDValue Lo = Op.getOperand(0);
5353 SDValue Hi = Op.getOperand(1);
5354 SDValue Amt = Op.getOperand(2);
5355 EVT AmtVT = Amt.getValueType();
5357 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5358 DAG.getConstant(BitWidth, AmtVT), Amt);
5359 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5360 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5361 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5362 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5363 DAG.getConstant(-BitWidth, AmtVT));
5364 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5365 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5366 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5367 SDValue OutOps[] = { OutLo, OutHi };
5368 return DAG.getMergeValues(OutOps, dl);
5371 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5373 EVT VT = Op.getValueType();
5374 unsigned BitWidth = VT.getSizeInBits();
5375 assert(Op.getNumOperands() == 3 &&
5376 VT == Op.getOperand(1).getValueType() &&
5379 // Expand into a bunch of logical ops, followed by a select_cc.
5380 SDValue Lo = Op.getOperand(0);
5381 SDValue Hi = Op.getOperand(1);
5382 SDValue Amt = Op.getOperand(2);
5383 EVT AmtVT = Amt.getValueType();
5385 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5386 DAG.getConstant(BitWidth, AmtVT), Amt);
5387 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5388 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5389 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5390 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5391 DAG.getConstant(-BitWidth, AmtVT));
5392 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5393 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5394 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5395 Tmp4, Tmp6, ISD::SETLE);
5396 SDValue OutOps[] = { OutLo, OutHi };
5397 return DAG.getMergeValues(OutOps, dl);
5400 //===----------------------------------------------------------------------===//
5401 // Vector related lowering.
5404 /// BuildSplatI - Build a canonical splati of Val with an element size of
5405 /// SplatSize. Cast the result to VT.
5406 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5407 SelectionDAG &DAG, SDLoc dl) {
5408 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5410 static const EVT VTys[] = { // canonical VT to use for each size.
5411 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5414 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5416 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5420 EVT CanonicalVT = VTys[SplatSize-1];
5422 // Build a canonical splat for this value.
5423 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5424 SmallVector<SDValue, 8> Ops;
5425 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5426 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5427 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5430 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5431 /// specified intrinsic ID.
5432 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5433 SelectionDAG &DAG, SDLoc dl,
5434 EVT DestVT = MVT::Other) {
5435 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5436 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5437 DAG.getConstant(IID, MVT::i32), Op);
5440 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5441 /// specified intrinsic ID.
5442 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5443 SelectionDAG &DAG, SDLoc dl,
5444 EVT DestVT = MVT::Other) {
5445 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5446 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5447 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5450 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5451 /// specified intrinsic ID.
5452 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5453 SDValue Op2, SelectionDAG &DAG,
5454 SDLoc dl, EVT DestVT = MVT::Other) {
5455 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5456 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5457 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5461 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5462 /// amount. The result has the specified value type.
5463 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5464 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5465 // Force LHS/RHS to be the right type.
5466 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5467 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5470 for (unsigned i = 0; i != 16; ++i)
5472 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5473 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5476 // If this is a case we can't handle, return null and let the default
5477 // expansion code take care of it. If we CAN select this case, and if it
5478 // selects to a single instruction, return Op. Otherwise, if we can codegen
5479 // this case more efficiently than a constant pool load, lower it to the
5480 // sequence of ops that should be used.
5481 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5482 SelectionDAG &DAG) const {
5484 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5485 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5487 // Check if this is a splat of a constant value.
5488 APInt APSplatBits, APSplatUndef;
5489 unsigned SplatBitSize;
5491 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5492 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5495 unsigned SplatBits = APSplatBits.getZExtValue();
5496 unsigned SplatUndef = APSplatUndef.getZExtValue();
5497 unsigned SplatSize = SplatBitSize / 8;
5499 // First, handle single instruction cases.
5502 if (SplatBits == 0) {
5503 // Canonicalize all zero vectors to be v4i32.
5504 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5505 SDValue Z = DAG.getConstant(0, MVT::i32);
5506 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5507 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5512 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5513 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5515 if (SextVal >= -16 && SextVal <= 15)
5516 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5519 // Two instruction sequences.
5521 // If this value is in the range [-32,30] and is even, use:
5522 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5523 // If this value is in the range [17,31] and is odd, use:
5524 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5525 // If this value is in the range [-31,-17] and is odd, use:
5526 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5527 // Note the last two are three-instruction sequences.
5528 if (SextVal >= -32 && SextVal <= 31) {
5529 // To avoid having these optimizations undone by constant folding,
5530 // we convert to a pseudo that will be expanded later into one of
5532 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5533 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5534 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5535 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5536 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5537 if (VT == Op.getValueType())
5540 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5543 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5544 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5546 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5547 // Make -1 and vspltisw -1:
5548 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5550 // Make the VSLW intrinsic, computing 0x8000_0000.
5551 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5554 // xor by OnesV to invert it.
5555 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5556 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5559 // Check to see if this is a wide variety of vsplti*, binop self cases.
5560 static const signed char SplatCsts[] = {
5561 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5562 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5565 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5566 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5567 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5568 int i = SplatCsts[idx];
5570 // Figure out what shift amount will be used by altivec if shifted by i in
5572 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5574 // vsplti + shl self.
5575 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5576 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5577 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5578 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5579 Intrinsic::ppc_altivec_vslw
5581 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5582 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5585 // vsplti + srl self.
5586 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5587 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5588 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5589 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5590 Intrinsic::ppc_altivec_vsrw
5592 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5593 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5596 // vsplti + sra self.
5597 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5598 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5599 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5600 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5601 Intrinsic::ppc_altivec_vsraw
5603 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5604 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5607 // vsplti + rol self.
5608 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5609 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5610 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5611 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5612 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5613 Intrinsic::ppc_altivec_vrlw
5615 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5616 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5619 // t = vsplti c, result = vsldoi t, t, 1
5620 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5621 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5622 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5624 // t = vsplti c, result = vsldoi t, t, 2
5625 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5626 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5627 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5629 // t = vsplti c, result = vsldoi t, t, 3
5630 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5631 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5632 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5639 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5640 /// the specified operations to build the shuffle.
5641 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5642 SDValue RHS, SelectionDAG &DAG,
5644 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5645 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5646 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5649 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5661 if (OpNum == OP_COPY) {
5662 if (LHSID == (1*9+2)*9+3) return LHS;
5663 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5667 SDValue OpLHS, OpRHS;
5668 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5669 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5673 default: llvm_unreachable("Unknown i32 permute!");
5675 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5676 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5677 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5678 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5681 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5682 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5683 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5684 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5687 for (unsigned i = 0; i != 16; ++i)
5688 ShufIdxs[i] = (i&3)+0;
5691 for (unsigned i = 0; i != 16; ++i)
5692 ShufIdxs[i] = (i&3)+4;
5695 for (unsigned i = 0; i != 16; ++i)
5696 ShufIdxs[i] = (i&3)+8;
5699 for (unsigned i = 0; i != 16; ++i)
5700 ShufIdxs[i] = (i&3)+12;
5703 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5705 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5707 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5709 EVT VT = OpLHS.getValueType();
5710 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5711 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5712 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5713 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5716 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5717 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5718 /// return the code it can be lowered into. Worst case, it can always be
5719 /// lowered into a vperm.
5720 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5721 SelectionDAG &DAG) const {
5723 SDValue V1 = Op.getOperand(0);
5724 SDValue V2 = Op.getOperand(1);
5725 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5726 EVT VT = Op.getValueType();
5728 // Cases that are handled by instructions that take permute immediates
5729 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5730 // selected by the instruction selector.
5731 if (V2.getOpcode() == ISD::UNDEF) {
5732 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5733 PPC::isSplatShuffleMask(SVOp, 2) ||
5734 PPC::isSplatShuffleMask(SVOp, 4) ||
5735 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5736 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5737 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5738 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5739 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5740 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5741 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5742 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5743 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5748 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5749 // and produce a fixed permutation. If any of these match, do not lower to
5751 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5752 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5753 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5754 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5755 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5756 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5757 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5758 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5759 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5762 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5763 // perfect shuffle table to emit an optimal matching sequence.
5764 ArrayRef<int> PermMask = SVOp->getMask();
5766 unsigned PFIndexes[4];
5767 bool isFourElementShuffle = true;
5768 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5769 unsigned EltNo = 8; // Start out undef.
5770 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5771 if (PermMask[i*4+j] < 0)
5772 continue; // Undef, ignore it.
5774 unsigned ByteSource = PermMask[i*4+j];
5775 if ((ByteSource & 3) != j) {
5776 isFourElementShuffle = false;
5781 EltNo = ByteSource/4;
5782 } else if (EltNo != ByteSource/4) {
5783 isFourElementShuffle = false;
5787 PFIndexes[i] = EltNo;
5790 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5791 // perfect shuffle vector to determine if it is cost effective to do this as
5792 // discrete instructions, or whether we should use a vperm.
5793 if (isFourElementShuffle) {
5794 // Compute the index in the perfect shuffle table.
5795 unsigned PFTableIndex =
5796 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5798 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5799 unsigned Cost = (PFEntry >> 30);
5801 // Determining when to avoid vperm is tricky. Many things affect the cost
5802 // of vperm, particularly how many times the perm mask needs to be computed.
5803 // For example, if the perm mask can be hoisted out of a loop or is already
5804 // used (perhaps because there are multiple permutes with the same shuffle
5805 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5806 // the loop requires an extra register.
5808 // As a compromise, we only emit discrete instructions if the shuffle can be
5809 // generated in 3 or fewer operations. When we have loop information
5810 // available, if this block is within a loop, we should avoid using vperm
5811 // for 3-operation perms and use a constant pool load instead.
5813 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5816 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5817 // vector that will get spilled to the constant pool.
5818 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5820 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5821 // that it is in input element units, not in bytes. Convert now.
5822 EVT EltVT = V1.getValueType().getVectorElementType();
5823 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5825 SmallVector<SDValue, 16> ResultMask;
5826 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5827 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5829 for (unsigned j = 0; j != BytesPerElement; ++j)
5830 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5834 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5836 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5839 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5840 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5841 /// information about the intrinsic.
5842 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5844 unsigned IntrinsicID =
5845 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5848 switch (IntrinsicID) {
5849 default: return false;
5850 // Comparison predicates.
5851 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5852 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5853 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5854 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5855 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5856 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5857 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5858 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5859 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5860 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5861 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5862 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5863 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5865 // Normal Comparisons.
5866 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5867 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5868 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5869 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5870 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5871 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5872 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5873 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5874 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5875 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5876 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5877 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5878 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5883 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5884 /// lower, do it, otherwise return null.
5885 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5886 SelectionDAG &DAG) const {
5887 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5888 // opcode number of the comparison.
5892 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5893 return SDValue(); // Don't custom lower most intrinsics.
5895 // If this is a non-dot comparison, make the VCMP node and we are done.
5897 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5898 Op.getOperand(1), Op.getOperand(2),
5899 DAG.getConstant(CompareOpc, MVT::i32));
5900 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5903 // Create the PPCISD altivec 'dot' comparison node.
5905 Op.getOperand(2), // LHS
5906 Op.getOperand(3), // RHS
5907 DAG.getConstant(CompareOpc, MVT::i32)
5909 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5910 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
5912 // Now that we have the comparison, emit a copy from the CR to a GPR.
5913 // This is flagged to the above dot comparison.
5914 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5915 DAG.getRegister(PPC::CR6, MVT::i32),
5916 CompNode.getValue(1));
5918 // Unpack the result based on how the target uses it.
5919 unsigned BitNo; // Bit # of CR6.
5920 bool InvertBit; // Invert result?
5921 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5922 default: // Can't happen, don't crash on invalid number though.
5923 case 0: // Return the value of the EQ bit of CR6.
5924 BitNo = 0; InvertBit = false;
5926 case 1: // Return the inverted value of the EQ bit of CR6.
5927 BitNo = 0; InvertBit = true;
5929 case 2: // Return the value of the LT bit of CR6.
5930 BitNo = 2; InvertBit = false;
5932 case 3: // Return the inverted value of the LT bit of CR6.
5933 BitNo = 2; InvertBit = true;
5937 // Shift the bit into the low position.
5938 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5939 DAG.getConstant(8-(3-BitNo), MVT::i32));
5941 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5942 DAG.getConstant(1, MVT::i32));
5944 // If we are supposed to, toggle the bit.
5946 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5947 DAG.getConstant(1, MVT::i32));
5951 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
5952 SelectionDAG &DAG) const {
5954 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
5955 // instructions), but for smaller types, we need to first extend up to v2i32
5956 // before doing going farther.
5957 if (Op.getValueType() == MVT::v2i64) {
5958 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5959 if (ExtVT != MVT::v2i32) {
5960 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
5961 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
5962 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
5963 ExtVT.getVectorElementType(), 4)));
5964 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
5965 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
5966 DAG.getValueType(MVT::v2i32));
5975 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5976 SelectionDAG &DAG) const {
5978 // Create a stack slot that is 16-byte aligned.
5979 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5980 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5981 EVT PtrVT = getPointerTy();
5982 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5984 // Store the input value into Value#0 of the stack slot.
5985 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5986 Op.getOperand(0), FIdx, MachinePointerInfo(),
5989 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5990 false, false, false, 0);
5993 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5995 if (Op.getValueType() == MVT::v4i32) {
5996 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5998 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5999 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6001 SDValue RHSSwap = // = vrlw RHS, 16
6002 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6004 // Shrinkify inputs to v8i16.
6005 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6006 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6007 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6009 // Low parts multiplied together, generating 32-bit results (we ignore the
6011 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6012 LHS, RHS, DAG, dl, MVT::v4i32);
6014 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6015 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6016 // Shift the high parts up 16 bits.
6017 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6019 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6020 } else if (Op.getValueType() == MVT::v8i16) {
6021 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6023 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6025 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6026 LHS, RHS, Zero, DAG, dl);
6027 } else if (Op.getValueType() == MVT::v16i8) {
6028 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6030 // Multiply the even 8-bit parts, producing 16-bit sums.
6031 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6032 LHS, RHS, DAG, dl, MVT::v8i16);
6033 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6035 // Multiply the odd 8-bit parts, producing 16-bit sums.
6036 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6037 LHS, RHS, DAG, dl, MVT::v8i16);
6038 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6040 // Merge the results together.
6042 for (unsigned i = 0; i != 8; ++i) {
6044 Ops[i*2+1] = 2*i+1+16;
6046 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6048 llvm_unreachable("Unknown mul to lower!");
6052 /// LowerOperation - Provide custom lowering hooks for some operations.
6054 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6055 switch (Op.getOpcode()) {
6056 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6057 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6058 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6059 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6060 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6061 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6062 case ISD::SETCC: return LowerSETCC(Op, DAG);
6063 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6064 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6066 return LowerVASTART(Op, DAG, PPCSubTarget);
6069 return LowerVAARG(Op, DAG, PPCSubTarget);
6072 return LowerVACOPY(Op, DAG, PPCSubTarget);
6074 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
6075 case ISD::DYNAMIC_STACKALLOC:
6076 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
6078 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6079 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6081 case ISD::LOAD: return LowerLOAD(Op, DAG);
6082 case ISD::STORE: return LowerSTORE(Op, DAG);
6083 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6084 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6085 case ISD::FP_TO_UINT:
6086 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6088 case ISD::UINT_TO_FP:
6089 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6090 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6092 // Lower 64-bit shifts.
6093 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6094 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6095 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6097 // Vector-related lowering.
6098 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6099 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6100 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6101 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6102 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6103 case ISD::MUL: return LowerMUL(Op, DAG);
6105 // For counter-based loop handling.
6106 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6108 // Frame & Return address.
6109 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6110 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6114 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6115 SmallVectorImpl<SDValue>&Results,
6116 SelectionDAG &DAG) const {
6117 const TargetMachine &TM = getTargetMachine();
6119 switch (N->getOpcode()) {
6121 llvm_unreachable("Do not know how to custom type legalize this operation!");
6122 case ISD::INTRINSIC_W_CHAIN: {
6123 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6124 Intrinsic::ppc_is_decremented_ctr_nonzero)
6127 assert(N->getValueType(0) == MVT::i1 &&
6128 "Unexpected result type for CTR decrement intrinsic");
6129 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6130 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6131 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6134 Results.push_back(NewInt);
6135 Results.push_back(NewInt.getValue(1));
6139 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6140 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6143 EVT VT = N->getValueType(0);
6145 if (VT == MVT::i64) {
6146 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
6148 Results.push_back(NewNode);
6149 Results.push_back(NewNode.getValue(1));
6153 case ISD::FP_ROUND_INREG: {
6154 assert(N->getValueType(0) == MVT::ppcf128);
6155 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6156 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6157 MVT::f64, N->getOperand(0),
6158 DAG.getIntPtrConstant(0));
6159 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6160 MVT::f64, N->getOperand(0),
6161 DAG.getIntPtrConstant(1));
6163 // Add the two halves of the long double in round-to-zero mode.
6164 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6166 // We know the low half is about to be thrown away, so just use something
6168 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6172 case ISD::FP_TO_SINT:
6173 // LowerFP_TO_INT() can only handle f32 and f64.
6174 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6176 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6182 //===----------------------------------------------------------------------===//
6183 // Other Lowering Code
6184 //===----------------------------------------------------------------------===//
6187 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6188 bool is64bit, unsigned BinOpcode) const {
6189 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6190 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6192 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6193 MachineFunction *F = BB->getParent();
6194 MachineFunction::iterator It = BB;
6197 unsigned dest = MI->getOperand(0).getReg();
6198 unsigned ptrA = MI->getOperand(1).getReg();
6199 unsigned ptrB = MI->getOperand(2).getReg();
6200 unsigned incr = MI->getOperand(3).getReg();
6201 DebugLoc dl = MI->getDebugLoc();
6203 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6204 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6205 F->insert(It, loopMBB);
6206 F->insert(It, exitMBB);
6207 exitMBB->splice(exitMBB->begin(), BB,
6208 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6209 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6211 MachineRegisterInfo &RegInfo = F->getRegInfo();
6212 unsigned TmpReg = (!BinOpcode) ? incr :
6213 RegInfo.createVirtualRegister(
6214 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6215 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6219 // fallthrough --> loopMBB
6220 BB->addSuccessor(loopMBB);
6223 // l[wd]arx dest, ptr
6224 // add r0, dest, incr
6225 // st[wd]cx. r0, ptr
6227 // fallthrough --> exitMBB
6229 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6230 .addReg(ptrA).addReg(ptrB);
6232 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6233 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6234 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6235 BuildMI(BB, dl, TII->get(PPC::BCC))
6236 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6237 BB->addSuccessor(loopMBB);
6238 BB->addSuccessor(exitMBB);
6247 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6248 MachineBasicBlock *BB,
6249 bool is8bit, // operation
6250 unsigned BinOpcode) const {
6251 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6252 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6253 // In 64 bit mode we have to use 64 bits for addresses, even though the
6254 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6255 // registers without caring whether they're 32 or 64, but here we're
6256 // doing actual arithmetic on the addresses.
6257 bool is64bit = PPCSubTarget.isPPC64();
6258 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6260 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6261 MachineFunction *F = BB->getParent();
6262 MachineFunction::iterator It = BB;
6265 unsigned dest = MI->getOperand(0).getReg();
6266 unsigned ptrA = MI->getOperand(1).getReg();
6267 unsigned ptrB = MI->getOperand(2).getReg();
6268 unsigned incr = MI->getOperand(3).getReg();
6269 DebugLoc dl = MI->getDebugLoc();
6271 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6272 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6273 F->insert(It, loopMBB);
6274 F->insert(It, exitMBB);
6275 exitMBB->splice(exitMBB->begin(), BB,
6276 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6277 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6279 MachineRegisterInfo &RegInfo = F->getRegInfo();
6280 const TargetRegisterClass *RC =
6281 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6282 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6283 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6284 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6285 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6286 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6287 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6288 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6289 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6290 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6291 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6292 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6293 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6295 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6299 // fallthrough --> loopMBB
6300 BB->addSuccessor(loopMBB);
6302 // The 4-byte load must be aligned, while a char or short may be
6303 // anywhere in the word. Hence all this nasty bookkeeping code.
6304 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6305 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6306 // xori shift, shift1, 24 [16]
6307 // rlwinm ptr, ptr1, 0, 0, 29
6308 // slw incr2, incr, shift
6309 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6310 // slw mask, mask2, shift
6312 // lwarx tmpDest, ptr
6313 // add tmp, tmpDest, incr2
6314 // andc tmp2, tmpDest, mask
6315 // and tmp3, tmp, mask
6316 // or tmp4, tmp3, tmp2
6319 // fallthrough --> exitMBB
6320 // srw dest, tmpDest, shift
6321 if (ptrA != ZeroReg) {
6322 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6323 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6324 .addReg(ptrA).addReg(ptrB);
6328 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6329 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6330 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6331 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6333 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6334 .addReg(Ptr1Reg).addImm(0).addImm(61);
6336 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6337 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6338 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6339 .addReg(incr).addReg(ShiftReg);
6341 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6343 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6344 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6346 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6347 .addReg(Mask2Reg).addReg(ShiftReg);
6350 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6351 .addReg(ZeroReg).addReg(PtrReg);
6353 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6354 .addReg(Incr2Reg).addReg(TmpDestReg);
6355 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6356 .addReg(TmpDestReg).addReg(MaskReg);
6357 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6358 .addReg(TmpReg).addReg(MaskReg);
6359 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6360 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6361 BuildMI(BB, dl, TII->get(PPC::STWCX))
6362 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6363 BuildMI(BB, dl, TII->get(PPC::BCC))
6364 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6365 BB->addSuccessor(loopMBB);
6366 BB->addSuccessor(exitMBB);
6371 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6376 llvm::MachineBasicBlock*
6377 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6378 MachineBasicBlock *MBB) const {
6379 DebugLoc DL = MI->getDebugLoc();
6380 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6382 MachineFunction *MF = MBB->getParent();
6383 MachineRegisterInfo &MRI = MF->getRegInfo();
6385 const BasicBlock *BB = MBB->getBasicBlock();
6386 MachineFunction::iterator I = MBB;
6390 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6391 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6393 unsigned DstReg = MI->getOperand(0).getReg();
6394 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6395 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6396 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6397 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6399 MVT PVT = getPointerTy();
6400 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6401 "Invalid Pointer Size!");
6402 // For v = setjmp(buf), we generate
6405 // SjLjSetup mainMBB
6411 // buf[LabelOffset] = LR
6415 // v = phi(main, restore)
6418 MachineBasicBlock *thisMBB = MBB;
6419 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6420 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6421 MF->insert(I, mainMBB);
6422 MF->insert(I, sinkMBB);
6424 MachineInstrBuilder MIB;
6426 // Transfer the remainder of BB and its successor edges to sinkMBB.
6427 sinkMBB->splice(sinkMBB->begin(), MBB,
6428 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6429 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6431 // Note that the structure of the jmp_buf used here is not compatible
6432 // with that used by libc, and is not designed to be. Specifically, it
6433 // stores only those 'reserved' registers that LLVM does not otherwise
6434 // understand how to spill. Also, by convention, by the time this
6435 // intrinsic is called, Clang has already stored the frame address in the
6436 // first slot of the buffer and stack address in the third. Following the
6437 // X86 target code, we'll store the jump address in the second slot. We also
6438 // need to save the TOC pointer (R2) to handle jumps between shared
6439 // libraries, and that will be stored in the fourth slot. The thread
6440 // identifier (R13) is not affected.
6443 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6444 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6445 const int64_t BPOffset = 4 * PVT.getStoreSize();
6447 // Prepare IP either in reg.
6448 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6449 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6450 unsigned BufReg = MI->getOperand(1).getReg();
6452 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6453 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6457 MIB.setMemRefs(MMOBegin, MMOEnd);
6460 // Naked functions never have a base pointer, and so we use r1. For all
6461 // other functions, this decision must be delayed until during PEI.
6463 if (MF->getFunction()->getAttributes().hasAttribute(
6464 AttributeSet::FunctionIndex, Attribute::Naked))
6465 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6467 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6469 MIB = BuildMI(*thisMBB, MI, DL,
6470 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6474 MIB.setMemRefs(MMOBegin, MMOEnd);
6477 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6478 const PPCRegisterInfo *TRI =
6479 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6480 MIB.addRegMask(TRI->getNoPreservedMask());
6482 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6484 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6486 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6488 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6489 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6493 MIB = BuildMI(mainMBB, DL,
6494 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6497 if (PPCSubTarget.isPPC64()) {
6498 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6500 .addImm(LabelOffset)
6503 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6505 .addImm(LabelOffset)
6509 MIB.setMemRefs(MMOBegin, MMOEnd);
6511 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6512 mainMBB->addSuccessor(sinkMBB);
6515 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6516 TII->get(PPC::PHI), DstReg)
6517 .addReg(mainDstReg).addMBB(mainMBB)
6518 .addReg(restoreDstReg).addMBB(thisMBB);
6520 MI->eraseFromParent();
6525 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6526 MachineBasicBlock *MBB) const {
6527 DebugLoc DL = MI->getDebugLoc();
6528 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6530 MachineFunction *MF = MBB->getParent();
6531 MachineRegisterInfo &MRI = MF->getRegInfo();
6534 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6535 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6537 MVT PVT = getPointerTy();
6538 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6539 "Invalid Pointer Size!");
6541 const TargetRegisterClass *RC =
6542 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6543 unsigned Tmp = MRI.createVirtualRegister(RC);
6544 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6545 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6546 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6547 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6549 MachineInstrBuilder MIB;
6551 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6552 const int64_t SPOffset = 2 * PVT.getStoreSize();
6553 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6554 const int64_t BPOffset = 4 * PVT.getStoreSize();
6556 unsigned BufReg = MI->getOperand(0).getReg();
6558 // Reload FP (the jumped-to function may not have had a
6559 // frame pointer, and if so, then its r31 will be restored
6561 if (PVT == MVT::i64) {
6562 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6566 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6570 MIB.setMemRefs(MMOBegin, MMOEnd);
6573 if (PVT == MVT::i64) {
6574 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6575 .addImm(LabelOffset)
6578 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6579 .addImm(LabelOffset)
6582 MIB.setMemRefs(MMOBegin, MMOEnd);
6585 if (PVT == MVT::i64) {
6586 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6590 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6594 MIB.setMemRefs(MMOBegin, MMOEnd);
6597 if (PVT == MVT::i64) {
6598 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6602 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6606 MIB.setMemRefs(MMOBegin, MMOEnd);
6609 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6610 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6614 MIB.setMemRefs(MMOBegin, MMOEnd);
6618 BuildMI(*MBB, MI, DL,
6619 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6620 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6622 MI->eraseFromParent();
6627 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6628 MachineBasicBlock *BB) const {
6629 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6630 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6631 return emitEHSjLjSetJmp(MI, BB);
6632 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6633 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6634 return emitEHSjLjLongJmp(MI, BB);
6637 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6639 // To "insert" these instructions we actually have to insert their
6640 // control-flow patterns.
6641 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6642 MachineFunction::iterator It = BB;
6645 MachineFunction *F = BB->getParent();
6647 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6648 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6649 MI->getOpcode() == PPC::SELECT_I4 ||
6650 MI->getOpcode() == PPC::SELECT_I8)) {
6651 SmallVector<MachineOperand, 2> Cond;
6652 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6653 MI->getOpcode() == PPC::SELECT_CC_I8)
6654 Cond.push_back(MI->getOperand(4));
6656 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6657 Cond.push_back(MI->getOperand(1));
6659 DebugLoc dl = MI->getDebugLoc();
6660 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6661 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6662 Cond, MI->getOperand(2).getReg(),
6663 MI->getOperand(3).getReg());
6664 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6665 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6666 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6667 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6668 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6669 MI->getOpcode() == PPC::SELECT_I4 ||
6670 MI->getOpcode() == PPC::SELECT_I8 ||
6671 MI->getOpcode() == PPC::SELECT_F4 ||
6672 MI->getOpcode() == PPC::SELECT_F8 ||
6673 MI->getOpcode() == PPC::SELECT_VRRC) {
6674 // The incoming instruction knows the destination vreg to set, the
6675 // condition code register to branch on, the true/false values to
6676 // select between, and a branch opcode to use.
6681 // cmpTY ccX, r1, r2
6683 // fallthrough --> copy0MBB
6684 MachineBasicBlock *thisMBB = BB;
6685 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6686 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6687 DebugLoc dl = MI->getDebugLoc();
6688 F->insert(It, copy0MBB);
6689 F->insert(It, sinkMBB);
6691 // Transfer the remainder of BB and its successor edges to sinkMBB.
6692 sinkMBB->splice(sinkMBB->begin(), BB,
6693 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6694 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6696 // Next, add the true and fallthrough blocks as its successors.
6697 BB->addSuccessor(copy0MBB);
6698 BB->addSuccessor(sinkMBB);
6700 if (MI->getOpcode() == PPC::SELECT_I4 ||
6701 MI->getOpcode() == PPC::SELECT_I8 ||
6702 MI->getOpcode() == PPC::SELECT_F4 ||
6703 MI->getOpcode() == PPC::SELECT_F8 ||
6704 MI->getOpcode() == PPC::SELECT_VRRC) {
6705 BuildMI(BB, dl, TII->get(PPC::BC))
6706 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6708 unsigned SelectPred = MI->getOperand(4).getImm();
6709 BuildMI(BB, dl, TII->get(PPC::BCC))
6710 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6714 // %FalseValue = ...
6715 // # fallthrough to sinkMBB
6718 // Update machine-CFG edges
6719 BB->addSuccessor(sinkMBB);
6722 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6725 BuildMI(*BB, BB->begin(), dl,
6726 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6727 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6728 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6730 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6731 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6732 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6733 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6734 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6735 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6736 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6737 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6739 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6740 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6741 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6742 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6743 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6744 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6745 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6746 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6748 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6749 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6750 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6751 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6752 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6753 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6754 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6755 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6757 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6758 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6759 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6760 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6761 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6762 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6763 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6764 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6766 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6767 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6768 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6769 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6770 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6771 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6772 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6773 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6775 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6776 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6777 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6778 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6779 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6780 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6781 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6782 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6784 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6785 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6786 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6787 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6788 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6789 BB = EmitAtomicBinary(MI, BB, false, 0);
6790 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6791 BB = EmitAtomicBinary(MI, BB, true, 0);
6793 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6794 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6795 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6797 unsigned dest = MI->getOperand(0).getReg();
6798 unsigned ptrA = MI->getOperand(1).getReg();
6799 unsigned ptrB = MI->getOperand(2).getReg();
6800 unsigned oldval = MI->getOperand(3).getReg();
6801 unsigned newval = MI->getOperand(4).getReg();
6802 DebugLoc dl = MI->getDebugLoc();
6804 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6805 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6806 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6807 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6808 F->insert(It, loop1MBB);
6809 F->insert(It, loop2MBB);
6810 F->insert(It, midMBB);
6811 F->insert(It, exitMBB);
6812 exitMBB->splice(exitMBB->begin(), BB,
6813 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6814 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6818 // fallthrough --> loopMBB
6819 BB->addSuccessor(loop1MBB);
6822 // l[wd]arx dest, ptr
6823 // cmp[wd] dest, oldval
6826 // st[wd]cx. newval, ptr
6830 // st[wd]cx. dest, ptr
6833 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6834 .addReg(ptrA).addReg(ptrB);
6835 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6836 .addReg(oldval).addReg(dest);
6837 BuildMI(BB, dl, TII->get(PPC::BCC))
6838 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6839 BB->addSuccessor(loop2MBB);
6840 BB->addSuccessor(midMBB);
6843 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6844 .addReg(newval).addReg(ptrA).addReg(ptrB);
6845 BuildMI(BB, dl, TII->get(PPC::BCC))
6846 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6847 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6848 BB->addSuccessor(loop1MBB);
6849 BB->addSuccessor(exitMBB);
6852 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6853 .addReg(dest).addReg(ptrA).addReg(ptrB);
6854 BB->addSuccessor(exitMBB);
6859 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6860 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6861 // We must use 64-bit registers for addresses when targeting 64-bit,
6862 // since we're actually doing arithmetic on them. Other registers
6864 bool is64bit = PPCSubTarget.isPPC64();
6865 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6867 unsigned dest = MI->getOperand(0).getReg();
6868 unsigned ptrA = MI->getOperand(1).getReg();
6869 unsigned ptrB = MI->getOperand(2).getReg();
6870 unsigned oldval = MI->getOperand(3).getReg();
6871 unsigned newval = MI->getOperand(4).getReg();
6872 DebugLoc dl = MI->getDebugLoc();
6874 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6875 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6876 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6877 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6878 F->insert(It, loop1MBB);
6879 F->insert(It, loop2MBB);
6880 F->insert(It, midMBB);
6881 F->insert(It, exitMBB);
6882 exitMBB->splice(exitMBB->begin(), BB,
6883 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6884 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6886 MachineRegisterInfo &RegInfo = F->getRegInfo();
6887 const TargetRegisterClass *RC =
6888 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6889 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6890 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6891 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6892 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6893 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6894 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6895 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6896 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6897 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6898 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6899 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6900 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6901 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6902 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6904 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6905 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6908 // fallthrough --> loopMBB
6909 BB->addSuccessor(loop1MBB);
6911 // The 4-byte load must be aligned, while a char or short may be
6912 // anywhere in the word. Hence all this nasty bookkeeping code.
6913 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6914 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6915 // xori shift, shift1, 24 [16]
6916 // rlwinm ptr, ptr1, 0, 0, 29
6917 // slw newval2, newval, shift
6918 // slw oldval2, oldval,shift
6919 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6920 // slw mask, mask2, shift
6921 // and newval3, newval2, mask
6922 // and oldval3, oldval2, mask
6924 // lwarx tmpDest, ptr
6925 // and tmp, tmpDest, mask
6926 // cmpw tmp, oldval3
6929 // andc tmp2, tmpDest, mask
6930 // or tmp4, tmp2, newval3
6935 // stwcx. tmpDest, ptr
6937 // srw dest, tmpDest, shift
6938 if (ptrA != ZeroReg) {
6939 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6940 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6941 .addReg(ptrA).addReg(ptrB);
6945 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6946 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6947 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6948 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6950 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6951 .addReg(Ptr1Reg).addImm(0).addImm(61);
6953 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6954 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6955 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6956 .addReg(newval).addReg(ShiftReg);
6957 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6958 .addReg(oldval).addReg(ShiftReg);
6960 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6962 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6963 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6964 .addReg(Mask3Reg).addImm(65535);
6966 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6967 .addReg(Mask2Reg).addReg(ShiftReg);
6968 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6969 .addReg(NewVal2Reg).addReg(MaskReg);
6970 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6971 .addReg(OldVal2Reg).addReg(MaskReg);
6974 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6975 .addReg(ZeroReg).addReg(PtrReg);
6976 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6977 .addReg(TmpDestReg).addReg(MaskReg);
6978 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6979 .addReg(TmpReg).addReg(OldVal3Reg);
6980 BuildMI(BB, dl, TII->get(PPC::BCC))
6981 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6982 BB->addSuccessor(loop2MBB);
6983 BB->addSuccessor(midMBB);
6986 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6987 .addReg(TmpDestReg).addReg(MaskReg);
6988 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6989 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6990 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6991 .addReg(ZeroReg).addReg(PtrReg);
6992 BuildMI(BB, dl, TII->get(PPC::BCC))
6993 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6994 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6995 BB->addSuccessor(loop1MBB);
6996 BB->addSuccessor(exitMBB);
6999 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7000 .addReg(ZeroReg).addReg(PtrReg);
7001 BB->addSuccessor(exitMBB);
7006 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7008 } else if (MI->getOpcode() == PPC::FADDrtz) {
7009 // This pseudo performs an FADD with rounding mode temporarily forced
7010 // to round-to-zero. We emit this via custom inserter since the FPSCR
7011 // is not modeled at the SelectionDAG level.
7012 unsigned Dest = MI->getOperand(0).getReg();
7013 unsigned Src1 = MI->getOperand(1).getReg();
7014 unsigned Src2 = MI->getOperand(2).getReg();
7015 DebugLoc dl = MI->getDebugLoc();
7017 MachineRegisterInfo &RegInfo = F->getRegInfo();
7018 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7020 // Save FPSCR value.
7021 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7023 // Set rounding mode to round-to-zero.
7024 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7025 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7027 // Perform addition.
7028 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7030 // Restore FPSCR value.
7031 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7032 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7033 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7034 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7035 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7036 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7037 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7038 PPC::ANDIo8 : PPC::ANDIo;
7039 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7040 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7042 MachineRegisterInfo &RegInfo = F->getRegInfo();
7043 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7044 &PPC::GPRCRegClass :
7045 &PPC::G8RCRegClass);
7047 DebugLoc dl = MI->getDebugLoc();
7048 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7049 .addReg(MI->getOperand(1).getReg()).addImm(1);
7050 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7051 MI->getOperand(0).getReg())
7052 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7054 llvm_unreachable("Unexpected instr type to insert");
7057 MI->eraseFromParent(); // The pseudo instruction is gone now.
7061 //===----------------------------------------------------------------------===//
7062 // Target Optimization Hooks
7063 //===----------------------------------------------------------------------===//
7065 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7066 DAGCombinerInfo &DCI) const {
7067 if (DCI.isAfterLegalizeVectorOps())
7070 EVT VT = Op.getValueType();
7072 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
7073 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
7074 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7075 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7077 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7078 // For the reciprocal, we need to find the zero of the function:
7079 // F(X) = A X - 1 [which has a zero at X = 1/A]
7081 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7082 // does not require additional intermediate precision]
7084 // Convergence is quadratic, so we essentially double the number of digits
7085 // correct after every iteration. The minimum architected relative
7086 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7087 // 23 digits and double has 52 digits.
7088 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7089 if (VT.getScalarType() == MVT::f64)
7092 SelectionDAG &DAG = DCI.DAG;
7096 DAG.getConstantFP(1.0, VT.getScalarType());
7097 if (VT.isVector()) {
7098 assert(VT.getVectorNumElements() == 4 &&
7099 "Unknown vector type");
7100 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7101 FPOne, FPOne, FPOne, FPOne);
7104 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7105 DCI.AddToWorklist(Est.getNode());
7107 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7108 for (int i = 0; i < Iterations; ++i) {
7109 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7110 DCI.AddToWorklist(NewEst.getNode());
7112 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7113 DCI.AddToWorklist(NewEst.getNode());
7115 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7116 DCI.AddToWorklist(NewEst.getNode());
7118 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7119 DCI.AddToWorklist(Est.getNode());
7128 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7129 DAGCombinerInfo &DCI) const {
7130 if (DCI.isAfterLegalizeVectorOps())
7133 EVT VT = Op.getValueType();
7135 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
7136 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
7137 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7138 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7140 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7141 // For the reciprocal sqrt, we need to find the zero of the function:
7142 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7144 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7145 // As a result, we precompute A/2 prior to the iteration loop.
7147 // Convergence is quadratic, so we essentially double the number of digits
7148 // correct after every iteration. The minimum architected relative
7149 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7150 // 23 digits and double has 52 digits.
7151 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7152 if (VT.getScalarType() == MVT::f64)
7155 SelectionDAG &DAG = DCI.DAG;
7158 SDValue FPThreeHalves =
7159 DAG.getConstantFP(1.5, VT.getScalarType());
7160 if (VT.isVector()) {
7161 assert(VT.getVectorNumElements() == 4 &&
7162 "Unknown vector type");
7163 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7164 FPThreeHalves, FPThreeHalves,
7165 FPThreeHalves, FPThreeHalves);
7168 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7169 DCI.AddToWorklist(Est.getNode());
7171 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7172 // this entire sequence requires only one FP constant.
7173 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7174 DCI.AddToWorklist(HalfArg.getNode());
7176 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7177 DCI.AddToWorklist(HalfArg.getNode());
7179 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7180 for (int i = 0; i < Iterations; ++i) {
7181 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7182 DCI.AddToWorklist(NewEst.getNode());
7184 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7185 DCI.AddToWorklist(NewEst.getNode());
7187 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7188 DCI.AddToWorklist(NewEst.getNode());
7190 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7191 DCI.AddToWorklist(Est.getNode());
7200 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7201 // not enforce equality of the chain operands.
7202 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7203 unsigned Bytes, int Dist,
7204 SelectionDAG &DAG) {
7205 EVT VT = LS->getMemoryVT();
7206 if (VT.getSizeInBits() / 8 != Bytes)
7209 SDValue Loc = LS->getBasePtr();
7210 SDValue BaseLoc = Base->getBasePtr();
7211 if (Loc.getOpcode() == ISD::FrameIndex) {
7212 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7214 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7215 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7216 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7217 int FS = MFI->getObjectSize(FI);
7218 int BFS = MFI->getObjectSize(BFI);
7219 if (FS != BFS || FS != (int)Bytes) return false;
7220 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7224 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7225 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7228 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7229 const GlobalValue *GV1 = nullptr;
7230 const GlobalValue *GV2 = nullptr;
7231 int64_t Offset1 = 0;
7232 int64_t Offset2 = 0;
7233 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7234 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7235 if (isGA1 && isGA2 && GV1 == GV2)
7236 return Offset1 == (Offset2 + Dist*Bytes);
7240 // Return true is there is a nearyby consecutive load to the one provided
7241 // (regardless of alignment). We search up and down the chain, looking though
7242 // token factors and other loads (but nothing else). As a result, a true
7243 // results indicates that it is safe to create a new consecutive load adjacent
7244 // to the load provided.
7245 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7246 SDValue Chain = LD->getChain();
7247 EVT VT = LD->getMemoryVT();
7249 SmallSet<SDNode *, 16> LoadRoots;
7250 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7251 SmallSet<SDNode *, 16> Visited;
7253 // First, search up the chain, branching to follow all token-factor operands.
7254 // If we find a consecutive load, then we're done, otherwise, record all
7255 // nodes just above the top-level loads and token factors.
7256 while (!Queue.empty()) {
7257 SDNode *ChainNext = Queue.pop_back_val();
7258 if (!Visited.insert(ChainNext))
7261 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7262 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7265 if (!Visited.count(ChainLD->getChain().getNode()))
7266 Queue.push_back(ChainLD->getChain().getNode());
7267 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7268 for (SDNode::op_iterator O = ChainNext->op_begin(),
7269 OE = ChainNext->op_end(); O != OE; ++O)
7270 if (!Visited.count(O->getNode()))
7271 Queue.push_back(O->getNode());
7273 LoadRoots.insert(ChainNext);
7276 // Second, search down the chain, starting from the top-level nodes recorded
7277 // in the first phase. These top-level nodes are the nodes just above all
7278 // loads and token factors. Starting with their uses, recursively look though
7279 // all loads (just the chain uses) and token factors to find a consecutive
7284 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7285 IE = LoadRoots.end(); I != IE; ++I) {
7286 Queue.push_back(*I);
7288 while (!Queue.empty()) {
7289 SDNode *LoadRoot = Queue.pop_back_val();
7290 if (!Visited.insert(LoadRoot))
7293 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7294 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7297 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7298 UE = LoadRoot->use_end(); UI != UE; ++UI)
7299 if (((isa<LoadSDNode>(*UI) &&
7300 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7301 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7302 Queue.push_back(*UI);
7309 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7310 DAGCombinerInfo &DCI) const {
7311 SelectionDAG &DAG = DCI.DAG;
7314 assert(PPCSubTarget.useCRBits() &&
7315 "Expecting to be tracking CR bits");
7316 // If we're tracking CR bits, we need to be careful that we don't have:
7317 // trunc(binary-ops(zext(x), zext(y)))
7319 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7320 // such that we're unnecessarily moving things into GPRs when it would be
7321 // better to keep them in CR bits.
7323 // Note that trunc here can be an actual i1 trunc, or can be the effective
7324 // truncation that comes from a setcc or select_cc.
7325 if (N->getOpcode() == ISD::TRUNCATE &&
7326 N->getValueType(0) != MVT::i1)
7329 if (N->getOperand(0).getValueType() != MVT::i32 &&
7330 N->getOperand(0).getValueType() != MVT::i64)
7333 if (N->getOpcode() == ISD::SETCC ||
7334 N->getOpcode() == ISD::SELECT_CC) {
7335 // If we're looking at a comparison, then we need to make sure that the
7336 // high bits (all except for the first) don't matter the result.
7338 cast<CondCodeSDNode>(N->getOperand(
7339 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7340 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7342 if (ISD::isSignedIntSetCC(CC)) {
7343 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7344 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7346 } else if (ISD::isUnsignedIntSetCC(CC)) {
7347 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7348 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7349 !DAG.MaskedValueIsZero(N->getOperand(1),
7350 APInt::getHighBitsSet(OpBits, OpBits-1)))
7353 // This is neither a signed nor an unsigned comparison, just make sure
7354 // that the high bits are equal.
7355 APInt Op1Zero, Op1One;
7356 APInt Op2Zero, Op2One;
7357 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7358 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7360 // We don't really care about what is known about the first bit (if
7361 // anything), so clear it in all masks prior to comparing them.
7362 Op1Zero.clearBit(0); Op1One.clearBit(0);
7363 Op2Zero.clearBit(0); Op2One.clearBit(0);
7365 if (Op1Zero != Op2Zero || Op1One != Op2One)
7370 // We now know that the higher-order bits are irrelevant, we just need to
7371 // make sure that all of the intermediate operations are bit operations, and
7372 // all inputs are extensions.
7373 if (N->getOperand(0).getOpcode() != ISD::AND &&
7374 N->getOperand(0).getOpcode() != ISD::OR &&
7375 N->getOperand(0).getOpcode() != ISD::XOR &&
7376 N->getOperand(0).getOpcode() != ISD::SELECT &&
7377 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7378 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7379 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7380 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7381 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7384 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7385 N->getOperand(1).getOpcode() != ISD::AND &&
7386 N->getOperand(1).getOpcode() != ISD::OR &&
7387 N->getOperand(1).getOpcode() != ISD::XOR &&
7388 N->getOperand(1).getOpcode() != ISD::SELECT &&
7389 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7390 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7391 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7392 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7393 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7396 SmallVector<SDValue, 4> Inputs;
7397 SmallVector<SDValue, 8> BinOps, PromOps;
7398 SmallPtrSet<SDNode *, 16> Visited;
7400 for (unsigned i = 0; i < 2; ++i) {
7401 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7402 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7403 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7404 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7405 isa<ConstantSDNode>(N->getOperand(i)))
7406 Inputs.push_back(N->getOperand(i));
7408 BinOps.push_back(N->getOperand(i));
7410 if (N->getOpcode() == ISD::TRUNCATE)
7414 // Visit all inputs, collect all binary operations (and, or, xor and
7415 // select) that are all fed by extensions.
7416 while (!BinOps.empty()) {
7417 SDValue BinOp = BinOps.back();
7420 if (!Visited.insert(BinOp.getNode()))
7423 PromOps.push_back(BinOp);
7425 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7426 // The condition of the select is not promoted.
7427 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7429 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7432 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7433 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7434 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7435 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7436 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7437 Inputs.push_back(BinOp.getOperand(i));
7438 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7439 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7440 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7441 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7442 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7443 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7444 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7445 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7446 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7447 BinOps.push_back(BinOp.getOperand(i));
7449 // We have an input that is not an extension or another binary
7450 // operation; we'll abort this transformation.
7456 // Make sure that this is a self-contained cluster of operations (which
7457 // is not quite the same thing as saying that everything has only one
7459 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7460 if (isa<ConstantSDNode>(Inputs[i]))
7463 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7464 UE = Inputs[i].getNode()->use_end();
7467 if (User != N && !Visited.count(User))
7470 // Make sure that we're not going to promote the non-output-value
7471 // operand(s) or SELECT or SELECT_CC.
7472 // FIXME: Although we could sometimes handle this, and it does occur in
7473 // practice that one of the condition inputs to the select is also one of
7474 // the outputs, we currently can't deal with this.
7475 if (User->getOpcode() == ISD::SELECT) {
7476 if (User->getOperand(0) == Inputs[i])
7478 } else if (User->getOpcode() == ISD::SELECT_CC) {
7479 if (User->getOperand(0) == Inputs[i] ||
7480 User->getOperand(1) == Inputs[i])
7486 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7487 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7488 UE = PromOps[i].getNode()->use_end();
7491 if (User != N && !Visited.count(User))
7494 // Make sure that we're not going to promote the non-output-value
7495 // operand(s) or SELECT or SELECT_CC.
7496 // FIXME: Although we could sometimes handle this, and it does occur in
7497 // practice that one of the condition inputs to the select is also one of
7498 // the outputs, we currently can't deal with this.
7499 if (User->getOpcode() == ISD::SELECT) {
7500 if (User->getOperand(0) == PromOps[i])
7502 } else if (User->getOpcode() == ISD::SELECT_CC) {
7503 if (User->getOperand(0) == PromOps[i] ||
7504 User->getOperand(1) == PromOps[i])
7510 // Replace all inputs with the extension operand.
7511 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7512 // Constants may have users outside the cluster of to-be-promoted nodes,
7513 // and so we need to replace those as we do the promotions.
7514 if (isa<ConstantSDNode>(Inputs[i]))
7517 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7520 // Replace all operations (these are all the same, but have a different
7521 // (i1) return type). DAG.getNode will validate that the types of
7522 // a binary operator match, so go through the list in reverse so that
7523 // we've likely promoted both operands first. Any intermediate truncations or
7524 // extensions disappear.
7525 while (!PromOps.empty()) {
7526 SDValue PromOp = PromOps.back();
7529 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7530 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7531 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7532 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7533 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7534 PromOp.getOperand(0).getValueType() != MVT::i1) {
7535 // The operand is not yet ready (see comment below).
7536 PromOps.insert(PromOps.begin(), PromOp);
7540 SDValue RepValue = PromOp.getOperand(0);
7541 if (isa<ConstantSDNode>(RepValue))
7542 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7544 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7549 switch (PromOp.getOpcode()) {
7550 default: C = 0; break;
7551 case ISD::SELECT: C = 1; break;
7552 case ISD::SELECT_CC: C = 2; break;
7555 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7556 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7557 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7558 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7559 // The to-be-promoted operands of this node have not yet been
7560 // promoted (this should be rare because we're going through the
7561 // list backward, but if one of the operands has several users in
7562 // this cluster of to-be-promoted nodes, it is possible).
7563 PromOps.insert(PromOps.begin(), PromOp);
7567 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7568 PromOp.getNode()->op_end());
7570 // If there are any constant inputs, make sure they're replaced now.
7571 for (unsigned i = 0; i < 2; ++i)
7572 if (isa<ConstantSDNode>(Ops[C+i]))
7573 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7575 DAG.ReplaceAllUsesOfValueWith(PromOp,
7576 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7579 // Now we're left with the initial truncation itself.
7580 if (N->getOpcode() == ISD::TRUNCATE)
7581 return N->getOperand(0);
7583 // Otherwise, this is a comparison. The operands to be compared have just
7584 // changed type (to i1), but everything else is the same.
7585 return SDValue(N, 0);
7588 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7589 DAGCombinerInfo &DCI) const {
7590 SelectionDAG &DAG = DCI.DAG;
7593 // If we're tracking CR bits, we need to be careful that we don't have:
7594 // zext(binary-ops(trunc(x), trunc(y)))
7596 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7597 // such that we're unnecessarily moving things into CR bits that can more
7598 // efficiently stay in GPRs. Note that if we're not certain that the high
7599 // bits are set as required by the final extension, we still may need to do
7600 // some masking to get the proper behavior.
7602 // This same functionality is important on PPC64 when dealing with
7603 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7604 // the return values of functions. Because it is so similar, it is handled
7607 if (N->getValueType(0) != MVT::i32 &&
7608 N->getValueType(0) != MVT::i64)
7611 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7612 PPCSubTarget.useCRBits()) ||
7613 (N->getOperand(0).getValueType() == MVT::i32 &&
7614 PPCSubTarget.isPPC64())))
7617 if (N->getOperand(0).getOpcode() != ISD::AND &&
7618 N->getOperand(0).getOpcode() != ISD::OR &&
7619 N->getOperand(0).getOpcode() != ISD::XOR &&
7620 N->getOperand(0).getOpcode() != ISD::SELECT &&
7621 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7624 SmallVector<SDValue, 4> Inputs;
7625 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7626 SmallPtrSet<SDNode *, 16> Visited;
7628 // Visit all inputs, collect all binary operations (and, or, xor and
7629 // select) that are all fed by truncations.
7630 while (!BinOps.empty()) {
7631 SDValue BinOp = BinOps.back();
7634 if (!Visited.insert(BinOp.getNode()))
7637 PromOps.push_back(BinOp);
7639 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7640 // The condition of the select is not promoted.
7641 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7643 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7646 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7647 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7648 Inputs.push_back(BinOp.getOperand(i));
7649 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7650 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7651 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7652 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7653 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7654 BinOps.push_back(BinOp.getOperand(i));
7656 // We have an input that is not a truncation or another binary
7657 // operation; we'll abort this transformation.
7663 // Make sure that this is a self-contained cluster of operations (which
7664 // is not quite the same thing as saying that everything has only one
7666 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7667 if (isa<ConstantSDNode>(Inputs[i]))
7670 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7671 UE = Inputs[i].getNode()->use_end();
7674 if (User != N && !Visited.count(User))
7677 // Make sure that we're not going to promote the non-output-value
7678 // operand(s) or SELECT or SELECT_CC.
7679 // FIXME: Although we could sometimes handle this, and it does occur in
7680 // practice that one of the condition inputs to the select is also one of
7681 // the outputs, we currently can't deal with this.
7682 if (User->getOpcode() == ISD::SELECT) {
7683 if (User->getOperand(0) == Inputs[i])
7685 } else if (User->getOpcode() == ISD::SELECT_CC) {
7686 if (User->getOperand(0) == Inputs[i] ||
7687 User->getOperand(1) == Inputs[i])
7693 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7694 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7695 UE = PromOps[i].getNode()->use_end();
7698 if (User != N && !Visited.count(User))
7701 // Make sure that we're not going to promote the non-output-value
7702 // operand(s) or SELECT or SELECT_CC.
7703 // FIXME: Although we could sometimes handle this, and it does occur in
7704 // practice that one of the condition inputs to the select is also one of
7705 // the outputs, we currently can't deal with this.
7706 if (User->getOpcode() == ISD::SELECT) {
7707 if (User->getOperand(0) == PromOps[i])
7709 } else if (User->getOpcode() == ISD::SELECT_CC) {
7710 if (User->getOperand(0) == PromOps[i] ||
7711 User->getOperand(1) == PromOps[i])
7717 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7718 bool ReallyNeedsExt = false;
7719 if (N->getOpcode() != ISD::ANY_EXTEND) {
7720 // If all of the inputs are not already sign/zero extended, then
7721 // we'll still need to do that at the end.
7722 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7723 if (isa<ConstantSDNode>(Inputs[i]))
7727 Inputs[i].getOperand(0).getValueSizeInBits();
7728 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7730 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7731 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7732 APInt::getHighBitsSet(OpBits,
7733 OpBits-PromBits))) ||
7734 (N->getOpcode() == ISD::SIGN_EXTEND &&
7735 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7736 (OpBits-(PromBits-1)))) {
7737 ReallyNeedsExt = true;
7743 // Replace all inputs, either with the truncation operand, or a
7744 // truncation or extension to the final output type.
7745 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7746 // Constant inputs need to be replaced with the to-be-promoted nodes that
7747 // use them because they might have users outside of the cluster of
7749 if (isa<ConstantSDNode>(Inputs[i]))
7752 SDValue InSrc = Inputs[i].getOperand(0);
7753 if (Inputs[i].getValueType() == N->getValueType(0))
7754 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7755 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7756 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7757 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7758 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7759 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7760 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7762 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7763 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7766 // Replace all operations (these are all the same, but have a different
7767 // (promoted) return type). DAG.getNode will validate that the types of
7768 // a binary operator match, so go through the list in reverse so that
7769 // we've likely promoted both operands first.
7770 while (!PromOps.empty()) {
7771 SDValue PromOp = PromOps.back();
7775 switch (PromOp.getOpcode()) {
7776 default: C = 0; break;
7777 case ISD::SELECT: C = 1; break;
7778 case ISD::SELECT_CC: C = 2; break;
7781 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7782 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7783 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7784 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7785 // The to-be-promoted operands of this node have not yet been
7786 // promoted (this should be rare because we're going through the
7787 // list backward, but if one of the operands has several users in
7788 // this cluster of to-be-promoted nodes, it is possible).
7789 PromOps.insert(PromOps.begin(), PromOp);
7793 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7794 PromOp.getNode()->op_end());
7796 // If this node has constant inputs, then they'll need to be promoted here.
7797 for (unsigned i = 0; i < 2; ++i) {
7798 if (!isa<ConstantSDNode>(Ops[C+i]))
7800 if (Ops[C+i].getValueType() == N->getValueType(0))
7803 if (N->getOpcode() == ISD::SIGN_EXTEND)
7804 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7805 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7806 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7808 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7811 DAG.ReplaceAllUsesOfValueWith(PromOp,
7812 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
7815 // Now we're left with the initial extension itself.
7816 if (!ReallyNeedsExt)
7817 return N->getOperand(0);
7819 // To zero extend, just mask off everything except for the first bit (in the
7821 if (N->getOpcode() == ISD::ZERO_EXTEND)
7822 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7823 DAG.getConstant(APInt::getLowBitsSet(
7824 N->getValueSizeInBits(0), PromBits),
7825 N->getValueType(0)));
7827 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7828 "Invalid extension type");
7829 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7831 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7832 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7833 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7834 N->getOperand(0), ShiftCst), ShiftCst);
7837 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7838 DAGCombinerInfo &DCI) const {
7839 const TargetMachine &TM = getTargetMachine();
7840 SelectionDAG &DAG = DCI.DAG;
7842 switch (N->getOpcode()) {
7845 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7846 if (C->isNullValue()) // 0 << V -> 0.
7847 return N->getOperand(0);
7851 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7852 if (C->isNullValue()) // 0 >>u V -> 0.
7853 return N->getOperand(0);
7857 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7858 if (C->isNullValue() || // 0 >>s V -> 0.
7859 C->isAllOnesValue()) // -1 >>s V -> -1.
7860 return N->getOperand(0);
7863 case ISD::SIGN_EXTEND:
7864 case ISD::ZERO_EXTEND:
7865 case ISD::ANY_EXTEND:
7866 return DAGCombineExtBoolTrunc(N, DCI);
7869 case ISD::SELECT_CC:
7870 return DAGCombineTruncBoolExt(N, DCI);
7872 assert(TM.Options.UnsafeFPMath &&
7873 "Reciprocal estimates require UnsafeFPMath");
7875 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7877 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7879 DCI.AddToWorklist(RV.getNode());
7880 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7881 N->getOperand(0), RV);
7883 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7884 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7886 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7889 DCI.AddToWorklist(RV.getNode());
7890 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7891 N->getValueType(0), RV);
7892 DCI.AddToWorklist(RV.getNode());
7893 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7894 N->getOperand(0), RV);
7896 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7897 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7899 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7902 DCI.AddToWorklist(RV.getNode());
7903 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7904 N->getValueType(0), RV,
7905 N->getOperand(1).getOperand(1));
7906 DCI.AddToWorklist(RV.getNode());
7907 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7908 N->getOperand(0), RV);
7912 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7914 DCI.AddToWorklist(RV.getNode());
7915 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7916 N->getOperand(0), RV);
7922 assert(TM.Options.UnsafeFPMath &&
7923 "Reciprocal estimates require UnsafeFPMath");
7925 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7927 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7929 DCI.AddToWorklist(RV.getNode());
7930 RV = DAGCombineFastRecip(RV, DCI);
7932 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7933 // this case and force the answer to 0.
7935 EVT VT = RV.getValueType();
7937 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7938 if (VT.isVector()) {
7939 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7940 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7944 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7945 N->getOperand(0), Zero, ISD::SETEQ);
7946 DCI.AddToWorklist(ZeroCmp.getNode());
7947 DCI.AddToWorklist(RV.getNode());
7949 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7957 case ISD::SINT_TO_FP:
7958 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7959 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7960 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7961 // We allow the src/dst to be either f32/f64, but the intermediate
7962 // type must be i64.
7963 if (N->getOperand(0).getValueType() == MVT::i64 &&
7964 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7965 SDValue Val = N->getOperand(0).getOperand(0);
7966 if (Val.getValueType() == MVT::f32) {
7967 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7968 DCI.AddToWorklist(Val.getNode());
7971 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7972 DCI.AddToWorklist(Val.getNode());
7973 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7974 DCI.AddToWorklist(Val.getNode());
7975 if (N->getValueType(0) == MVT::f32) {
7976 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7977 DAG.getIntPtrConstant(0));
7978 DCI.AddToWorklist(Val.getNode());
7981 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7982 // If the intermediate type is i32, we can avoid the load/store here
7989 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7990 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7991 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7992 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7993 N->getOperand(1).getValueType() == MVT::i32 &&
7994 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7995 SDValue Val = N->getOperand(1).getOperand(0);
7996 if (Val.getValueType() == MVT::f32) {
7997 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7998 DCI.AddToWorklist(Val.getNode());
8000 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8001 DCI.AddToWorklist(Val.getNode());
8004 N->getOperand(0), Val, N->getOperand(2),
8005 DAG.getValueType(N->getOperand(1).getValueType())
8008 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8009 DAG.getVTList(MVT::Other), Ops,
8010 cast<StoreSDNode>(N)->getMemoryVT(),
8011 cast<StoreSDNode>(N)->getMemOperand());
8012 DCI.AddToWorklist(Val.getNode());
8016 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8017 if (cast<StoreSDNode>(N)->isUnindexed() &&
8018 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8019 N->getOperand(1).getNode()->hasOneUse() &&
8020 (N->getOperand(1).getValueType() == MVT::i32 ||
8021 N->getOperand(1).getValueType() == MVT::i16 ||
8022 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8023 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8024 N->getOperand(1).getValueType() == MVT::i64))) {
8025 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8026 // Do an any-extend to 32-bits if this is a half-word input.
8027 if (BSwapOp.getValueType() == MVT::i16)
8028 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8031 N->getOperand(0), BSwapOp, N->getOperand(2),
8032 DAG.getValueType(N->getOperand(1).getValueType())
8035 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8036 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8037 cast<StoreSDNode>(N)->getMemOperand());
8041 LoadSDNode *LD = cast<LoadSDNode>(N);
8042 EVT VT = LD->getValueType(0);
8043 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8044 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8045 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8046 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8047 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8048 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8049 LD->getAlignment() < ABIAlignment) {
8050 // This is a type-legal unaligned Altivec load.
8051 SDValue Chain = LD->getChain();
8052 SDValue Ptr = LD->getBasePtr();
8054 // This implements the loading of unaligned vectors as described in
8055 // the venerable Apple Velocity Engine overview. Specifically:
8056 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8057 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8059 // The general idea is to expand a sequence of one or more unaligned
8060 // loads into a alignment-based permutation-control instruction (lvsl),
8061 // a series of regular vector loads (which always truncate their
8062 // input address to an aligned address), and a series of permutations.
8063 // The results of these permutations are the requested loaded values.
8064 // The trick is that the last "extra" load is not taken from the address
8065 // you might suspect (sizeof(vector) bytes after the last requested
8066 // load), but rather sizeof(vector) - 1 bytes after the last
8067 // requested vector. The point of this is to avoid a page fault if the
8068 // base address happened to be aligned. This works because if the base
8069 // address is aligned, then adding less than a full vector length will
8070 // cause the last vector in the sequence to be (re)loaded. Otherwise,
8071 // the next vector will be fetched as you might suspect was necessary.
8073 // We might be able to reuse the permutation generation from
8074 // a different base address offset from this one by an aligned amount.
8075 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8076 // optimization later.
8077 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
8078 DAG, dl, MVT::v16i8);
8080 // Refine the alignment of the original load (a "new" load created here
8081 // which was identical to the first except for the alignment would be
8082 // merged with the existing node regardless).
8083 MachineFunction &MF = DAG.getMachineFunction();
8084 MachineMemOperand *MMO =
8085 MF.getMachineMemOperand(LD->getPointerInfo(),
8086 LD->getMemOperand()->getFlags(),
8087 LD->getMemoryVT().getStoreSize(),
8089 LD->refineAlignment(MMO);
8090 SDValue BaseLoad = SDValue(LD, 0);
8092 // Note that the value of IncOffset (which is provided to the next
8093 // load's pointer info offset value, and thus used to calculate the
8094 // alignment), and the value of IncValue (which is actually used to
8095 // increment the pointer value) are different! This is because we
8096 // require the next load to appear to be aligned, even though it
8097 // is actually offset from the base pointer by a lesser amount.
8098 int IncOffset = VT.getSizeInBits() / 8;
8099 int IncValue = IncOffset;
8101 // Walk (both up and down) the chain looking for another load at the real
8102 // (aligned) offset (the alignment of the other load does not matter in
8103 // this case). If found, then do not use the offset reduction trick, as
8104 // that will prevent the loads from being later combined (as they would
8105 // otherwise be duplicates).
8106 if (!findConsecutiveLoad(LD, DAG))
8109 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8110 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8113 DAG.getLoad(VT, dl, Chain, Ptr,
8114 LD->getPointerInfo().getWithOffset(IncOffset),
8115 LD->isVolatile(), LD->isNonTemporal(),
8116 LD->isInvariant(), ABIAlignment);
8118 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8119 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8121 if (BaseLoad.getValueType() != MVT::v4i32)
8122 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8124 if (ExtraLoad.getValueType() != MVT::v4i32)
8125 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8127 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8128 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8130 if (VT != MVT::v4i32)
8131 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8133 // Now we need to be really careful about how we update the users of the
8134 // original load. We cannot just call DCI.CombineTo (or
8135 // DAG.ReplaceAllUsesWith for that matter), because the load still has
8136 // uses created here (the permutation for example) that need to stay.
8137 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8139 SDUse &Use = UI.getUse();
8141 // Note: BaseLoad is checked here because it might not be N, but a
8143 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8144 User == TF.getNode() || Use.getResNo() > 1) {
8149 SDValue To = Use.getResNo() ? TF : Perm;
8152 SmallVector<SDValue, 8> Ops;
8153 for (SDNode::op_iterator O = User->op_begin(),
8154 OE = User->op_end(); O != OE; ++O) {
8161 DAG.UpdateNodeOperands(User, Ops);
8164 return SDValue(N, 0);
8168 case ISD::INTRINSIC_WO_CHAIN:
8169 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8170 Intrinsic::ppc_altivec_lvsl &&
8171 N->getOperand(1)->getOpcode() == ISD::ADD) {
8172 SDValue Add = N->getOperand(1);
8174 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8175 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8176 Add.getValueType().getScalarType().getSizeInBits()))) {
8177 SDNode *BasePtr = Add->getOperand(0).getNode();
8178 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8179 UE = BasePtr->use_end(); UI != UE; ++UI) {
8180 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8181 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8182 Intrinsic::ppc_altivec_lvsl) {
8183 // We've found another LVSL, and this address if an aligned
8184 // multiple of that one. The results will be the same, so use the
8185 // one we've just found instead.
8187 return SDValue(*UI, 0);
8195 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8196 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8197 N->getOperand(0).hasOneUse() &&
8198 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8199 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8200 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8201 N->getValueType(0) == MVT::i64))) {
8202 SDValue Load = N->getOperand(0);
8203 LoadSDNode *LD = cast<LoadSDNode>(Load);
8204 // Create the byte-swapping load.
8206 LD->getChain(), // Chain
8207 LD->getBasePtr(), // Ptr
8208 DAG.getValueType(N->getValueType(0)) // VT
8211 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8212 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8213 MVT::i64 : MVT::i32, MVT::Other),
8214 Ops, LD->getMemoryVT(), LD->getMemOperand());
8216 // If this is an i16 load, insert the truncate.
8217 SDValue ResVal = BSLoad;
8218 if (N->getValueType(0) == MVT::i16)
8219 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8221 // First, combine the bswap away. This makes the value produced by the
8223 DCI.CombineTo(N, ResVal);
8225 // Next, combine the load away, we give it a bogus result value but a real
8226 // chain result. The result value is dead because the bswap is dead.
8227 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8229 // Return N so it doesn't get rechecked!
8230 return SDValue(N, 0);
8234 case PPCISD::VCMP: {
8235 // If a VCMPo node already exists with exactly the same operands as this
8236 // node, use its result instead of this node (VCMPo computes both a CR6 and
8237 // a normal output).
8239 if (!N->getOperand(0).hasOneUse() &&
8240 !N->getOperand(1).hasOneUse() &&
8241 !N->getOperand(2).hasOneUse()) {
8243 // Scan all of the users of the LHS, looking for VCMPo's that match.
8244 SDNode *VCMPoNode = nullptr;
8246 SDNode *LHSN = N->getOperand(0).getNode();
8247 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8249 if (UI->getOpcode() == PPCISD::VCMPo &&
8250 UI->getOperand(1) == N->getOperand(1) &&
8251 UI->getOperand(2) == N->getOperand(2) &&
8252 UI->getOperand(0) == N->getOperand(0)) {
8257 // If there is no VCMPo node, or if the flag value has a single use, don't
8259 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8262 // Look at the (necessarily single) use of the flag value. If it has a
8263 // chain, this transformation is more complex. Note that multiple things
8264 // could use the value result, which we should ignore.
8265 SDNode *FlagUser = nullptr;
8266 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8267 FlagUser == nullptr; ++UI) {
8268 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8270 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8271 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8278 // If the user is a MFOCRF instruction, we know this is safe.
8279 // Otherwise we give up for right now.
8280 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8281 return SDValue(VCMPoNode, 0);
8286 SDValue Cond = N->getOperand(1);
8287 SDValue Target = N->getOperand(2);
8289 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8290 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8291 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8293 // We now need to make the intrinsic dead (it cannot be instruction
8295 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8296 assert(Cond.getNode()->hasOneUse() &&
8297 "Counter decrement has more than one use");
8299 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8300 N->getOperand(0), Target);
8305 // If this is a branch on an altivec predicate comparison, lower this so
8306 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8307 // lowering is done pre-legalize, because the legalizer lowers the predicate
8308 // compare down to code that is difficult to reassemble.
8309 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8310 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8312 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8313 // value. If so, pass-through the AND to get to the intrinsic.
8314 if (LHS.getOpcode() == ISD::AND &&
8315 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8316 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8317 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8318 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8319 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8321 LHS = LHS.getOperand(0);
8323 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8324 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8325 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8326 isa<ConstantSDNode>(RHS)) {
8327 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8328 "Counter decrement comparison is not EQ or NE");
8330 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8331 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8332 (CC == ISD::SETNE && !Val);
8334 // We now need to make the intrinsic dead (it cannot be instruction
8336 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8337 assert(LHS.getNode()->hasOneUse() &&
8338 "Counter decrement has more than one use");
8340 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8341 N->getOperand(0), N->getOperand(4));
8347 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8348 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8349 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8350 assert(isDot && "Can't compare against a vector result!");
8352 // If this is a comparison against something other than 0/1, then we know
8353 // that the condition is never/always true.
8354 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8355 if (Val != 0 && Val != 1) {
8356 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8357 return N->getOperand(0);
8358 // Always !=, turn it into an unconditional branch.
8359 return DAG.getNode(ISD::BR, dl, MVT::Other,
8360 N->getOperand(0), N->getOperand(4));
8363 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8365 // Create the PPCISD altivec 'dot' comparison node.
8367 LHS.getOperand(2), // LHS of compare
8368 LHS.getOperand(3), // RHS of compare
8369 DAG.getConstant(CompareOpc, MVT::i32)
8371 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8372 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8374 // Unpack the result based on how the target uses it.
8375 PPC::Predicate CompOpc;
8376 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8377 default: // Can't happen, don't crash on invalid number though.
8378 case 0: // Branch on the value of the EQ bit of CR6.
8379 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8381 case 1: // Branch on the inverted value of the EQ bit of CR6.
8382 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8384 case 2: // Branch on the value of the LT bit of CR6.
8385 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8387 case 3: // Branch on the inverted value of the LT bit of CR6.
8388 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8392 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8393 DAG.getConstant(CompOpc, MVT::i32),
8394 DAG.getRegister(PPC::CR6, MVT::i32),
8395 N->getOperand(4), CompNode.getValue(1));
8404 //===----------------------------------------------------------------------===//
8405 // Inline Assembly Support
8406 //===----------------------------------------------------------------------===//
8408 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8411 const SelectionDAG &DAG,
8412 unsigned Depth) const {
8413 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8414 switch (Op.getOpcode()) {
8416 case PPCISD::LBRX: {
8417 // lhbrx is known to have the top bits cleared out.
8418 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8419 KnownZero = 0xFFFF0000;
8422 case ISD::INTRINSIC_WO_CHAIN: {
8423 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8425 case Intrinsic::ppc_altivec_vcmpbfp_p:
8426 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8427 case Intrinsic::ppc_altivec_vcmpequb_p:
8428 case Intrinsic::ppc_altivec_vcmpequh_p:
8429 case Intrinsic::ppc_altivec_vcmpequw_p:
8430 case Intrinsic::ppc_altivec_vcmpgefp_p:
8431 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8432 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8433 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8434 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8435 case Intrinsic::ppc_altivec_vcmpgtub_p:
8436 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8437 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8438 KnownZero = ~1U; // All bits but the low one are known to be zero.
8446 /// getConstraintType - Given a constraint, return the type of
8447 /// constraint it is for this target.
8448 PPCTargetLowering::ConstraintType
8449 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8450 if (Constraint.size() == 1) {
8451 switch (Constraint[0]) {
8458 return C_RegisterClass;
8460 // FIXME: While Z does indicate a memory constraint, it specifically
8461 // indicates an r+r address (used in conjunction with the 'y' modifier
8462 // in the replacement string). Currently, we're forcing the base
8463 // register to be r0 in the asm printer (which is interpreted as zero)
8464 // and forming the complete address in the second register. This is
8468 } else if (Constraint == "wc") { // individual CR bits.
8469 return C_RegisterClass;
8470 } else if (Constraint == "wa" || Constraint == "wd" ||
8471 Constraint == "wf" || Constraint == "ws") {
8472 return C_RegisterClass; // VSX registers.
8474 return TargetLowering::getConstraintType(Constraint);
8477 /// Examine constraint type and operand type and determine a weight value.
8478 /// This object must already have been set up with the operand type
8479 /// and the current alternative constraint selected.
8480 TargetLowering::ConstraintWeight
8481 PPCTargetLowering::getSingleConstraintMatchWeight(
8482 AsmOperandInfo &info, const char *constraint) const {
8483 ConstraintWeight weight = CW_Invalid;
8484 Value *CallOperandVal = info.CallOperandVal;
8485 // If we don't have a value, we can't do a match,
8486 // but allow it at the lowest weight.
8487 if (!CallOperandVal)
8489 Type *type = CallOperandVal->getType();
8491 // Look at the constraint type.
8492 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8493 return CW_Register; // an individual CR bit.
8494 else if ((StringRef(constraint) == "wa" ||
8495 StringRef(constraint) == "wd" ||
8496 StringRef(constraint) == "wf") &&
8499 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8502 switch (*constraint) {
8504 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8507 if (type->isIntegerTy())
8508 weight = CW_Register;
8511 if (type->isFloatTy())
8512 weight = CW_Register;
8515 if (type->isDoubleTy())
8516 weight = CW_Register;
8519 if (type->isVectorTy())
8520 weight = CW_Register;
8523 weight = CW_Register;
8532 std::pair<unsigned, const TargetRegisterClass*>
8533 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8535 if (Constraint.size() == 1) {
8536 // GCC RS6000 Constraint Letters
8537 switch (Constraint[0]) {
8539 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8540 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8541 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8543 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8544 return std::make_pair(0U, &PPC::G8RCRegClass);
8545 return std::make_pair(0U, &PPC::GPRCRegClass);
8547 if (VT == MVT::f32 || VT == MVT::i32)
8548 return std::make_pair(0U, &PPC::F4RCRegClass);
8549 if (VT == MVT::f64 || VT == MVT::i64)
8550 return std::make_pair(0U, &PPC::F8RCRegClass);
8553 return std::make_pair(0U, &PPC::VRRCRegClass);
8555 return std::make_pair(0U, &PPC::CRRCRegClass);
8557 } else if (Constraint == "wc") { // an individual CR bit.
8558 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8559 } else if (Constraint == "wa" || Constraint == "wd" ||
8560 Constraint == "wf") {
8561 return std::make_pair(0U, &PPC::VSRCRegClass);
8562 } else if (Constraint == "ws") {
8563 return std::make_pair(0U, &PPC::VSFRCRegClass);
8566 std::pair<unsigned, const TargetRegisterClass*> R =
8567 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8569 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8570 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8571 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8573 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8574 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8575 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8576 PPC::GPRCRegClass.contains(R.first)) {
8577 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8578 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8579 PPC::sub_32, &PPC::G8RCRegClass),
8580 &PPC::G8RCRegClass);
8587 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8588 /// vector. If it is invalid, don't add anything to Ops.
8589 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8590 std::string &Constraint,
8591 std::vector<SDValue>&Ops,
8592 SelectionDAG &DAG) const {
8595 // Only support length 1 constraints.
8596 if (Constraint.length() > 1) return;
8598 char Letter = Constraint[0];
8609 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8610 if (!CST) return; // Must be an immediate to match.
8611 unsigned Value = CST->getZExtValue();
8613 default: llvm_unreachable("Unknown constraint letter!");
8614 case 'I': // "I" is a signed 16-bit constant.
8615 if ((short)Value == (int)Value)
8616 Result = DAG.getTargetConstant(Value, Op.getValueType());
8618 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8619 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8620 if ((short)Value == 0)
8621 Result = DAG.getTargetConstant(Value, Op.getValueType());
8623 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8624 if ((Value >> 16) == 0)
8625 Result = DAG.getTargetConstant(Value, Op.getValueType());
8627 case 'M': // "M" is a constant that is greater than 31.
8629 Result = DAG.getTargetConstant(Value, Op.getValueType());
8631 case 'N': // "N" is a positive constant that is an exact power of two.
8632 if ((int)Value > 0 && isPowerOf2_32(Value))
8633 Result = DAG.getTargetConstant(Value, Op.getValueType());
8635 case 'O': // "O" is the constant zero.
8637 Result = DAG.getTargetConstant(Value, Op.getValueType());
8639 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8640 if ((short)-Value == (int)-Value)
8641 Result = DAG.getTargetConstant(Value, Op.getValueType());
8648 if (Result.getNode()) {
8649 Ops.push_back(Result);
8653 // Handle standard constraint letters.
8654 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8657 // isLegalAddressingMode - Return true if the addressing mode represented
8658 // by AM is legal for this target, for a load/store of the specified type.
8659 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8661 // FIXME: PPC does not allow r+i addressing modes for vectors!
8663 // PPC allows a sign-extended 16-bit immediate field.
8664 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8667 // No global is ever allowed as a base.
8671 // PPC only support r+r,
8673 case 0: // "r+i" or just "i", depending on HasBaseReg.
8676 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8678 // Otherwise we have r+r or r+i.
8681 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8683 // Allow 2*r as r+r.
8686 // No other scales are supported.
8693 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8694 SelectionDAG &DAG) const {
8695 MachineFunction &MF = DAG.getMachineFunction();
8696 MachineFrameInfo *MFI = MF.getFrameInfo();
8697 MFI->setReturnAddressIsTaken(true);
8699 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8703 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8705 // Make sure the function does not optimize away the store of the RA to
8707 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8708 FuncInfo->setLRStoreRequired();
8709 bool isPPC64 = PPCSubTarget.isPPC64();
8710 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8713 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8716 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8717 isPPC64? MVT::i64 : MVT::i32);
8718 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8719 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8721 MachinePointerInfo(), false, false, false, 0);
8724 // Just load the return address off the stack.
8725 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8726 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8727 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8730 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8731 SelectionDAG &DAG) const {
8733 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8735 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8736 bool isPPC64 = PtrVT == MVT::i64;
8738 MachineFunction &MF = DAG.getMachineFunction();
8739 MachineFrameInfo *MFI = MF.getFrameInfo();
8740 MFI->setFrameAddressIsTaken(true);
8742 // Naked functions never have a frame pointer, and so we use r1. For all
8743 // other functions, this decision must be delayed until during PEI.
8745 if (MF.getFunction()->getAttributes().hasAttribute(
8746 AttributeSet::FunctionIndex, Attribute::Naked))
8747 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8749 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8751 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8754 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8755 FrameAddr, MachinePointerInfo(), false, false,
8760 // FIXME? Maybe this could be a TableGen attribute on some registers and
8761 // this table could be generated automatically from RegInfo.
8762 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
8764 bool isPPC64 = PPCSubTarget.isPPC64();
8765 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8767 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
8768 (!isPPC64 && VT != MVT::i32))
8769 report_fatal_error("Invalid register global variable type");
8771 bool is64Bit = isPPC64 && VT == MVT::i64;
8772 unsigned Reg = StringSwitch<unsigned>(RegName)
8773 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
8774 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
8775 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
8776 (is64Bit ? PPC::X13 : PPC::R13))
8781 report_fatal_error("Invalid register name global variable");
8785 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8786 // The PowerPC target isn't yet aware of offsets.
8790 /// getOptimalMemOpType - Returns the target specific optimal type for load
8791 /// and store operations as a result of memset, memcpy, and memmove
8792 /// lowering. If DstAlign is zero that means it's safe to destination
8793 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8794 /// means there isn't a need to check it against alignment requirement,
8795 /// probably because the source does not need to be loaded. If 'IsMemset' is
8796 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8797 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8798 /// source is constant so it does not need to be loaded.
8799 /// It returns EVT::Other if the type should be determined using generic
8800 /// target-independent logic.
8801 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8802 unsigned DstAlign, unsigned SrcAlign,
8803 bool IsMemset, bool ZeroMemset,
8805 MachineFunction &MF) const {
8806 if (this->PPCSubTarget.isPPC64()) {
8813 /// \brief Returns true if it is beneficial to convert a load of a constant
8814 /// to just the constant itself.
8815 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8817 assert(Ty->isIntegerTy());
8819 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8820 if (BitSize == 0 || BitSize > 64)
8825 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8826 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8828 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8829 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8830 return NumBits1 == 64 && NumBits2 == 32;
8833 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8834 if (!VT1.isInteger() || !VT2.isInteger())
8836 unsigned NumBits1 = VT1.getSizeInBits();
8837 unsigned NumBits2 = VT2.getSizeInBits();
8838 return NumBits1 == 64 && NumBits2 == 32;
8841 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8842 return isInt<16>(Imm) || isUInt<16>(Imm);
8845 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8846 return isInt<16>(Imm) || isUInt<16>(Imm);
8849 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8852 if (DisablePPCUnaligned)
8855 // PowerPC supports unaligned memory access for simple non-vector types.
8856 // Although accessing unaligned addresses is not as efficient as accessing
8857 // aligned addresses, it is generally more efficient than manual expansion,
8858 // and generally only traps for software emulation when crossing page
8864 if (VT.getSimpleVT().isVector()) {
8865 if (PPCSubTarget.hasVSX()) {
8866 if (VT != MVT::v2f64 && VT != MVT::v2i64)
8873 if (VT == MVT::ppcf128)
8882 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8883 VT = VT.getScalarType();
8888 switch (VT.getSimpleVT().SimpleTy) {
8900 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
8901 EVT VT , unsigned DefinedValues) const {
8902 if (VT == MVT::v2i64)
8905 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
8908 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8909 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8910 return TargetLowering::getSchedulingPreference(N);
8915 // Create a fast isel object.
8917 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8918 const TargetLibraryInfo *LibInfo) const {
8919 return PPC::createFastISel(FuncInfo, LibInfo);