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"
17 #include "PPCCCState.h"
18 #include "PPCCallingConv.h"
19 #include "PPCFrameLowering.h"
20 #include "PPCInstrInfo.h"
21 #include "PPCMachineFunctionInfo.h"
22 #include "PPCPerfectShuffle.h"
23 #include "PPCRegisterInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/CodeGen/CallingConvLower.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineLoopInfo.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/MachineValueType.h"
51 #include "llvm/CodeGen/RuntimeLibcalls.h"
52 #include "llvm/CodeGen/SelectionDAG.h"
53 #include "llvm/CodeGen/SelectionDAGNodes.h"
54 #include "llvm/CodeGen/TargetInstrInfo.h"
55 #include "llvm/CodeGen/TargetLowering.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallSite.h"
59 #include "llvm/IR/CallingConv.h"
60 #include "llvm/IR/Constant.h"
61 #include "llvm/IR/Constants.h"
62 #include "llvm/IR/DataLayout.h"
63 #include "llvm/IR/DebugLoc.h"
64 #include "llvm/IR/DerivedTypes.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/GlobalValue.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Intrinsics.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCExpr.h"
75 #include "llvm/MC/MCRegisterInfo.h"
76 #include "llvm/Support/AtomicOrdering.h"
77 #include "llvm/Support/BranchProbability.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CodeGen.h"
80 #include "llvm/Support/CommandLine.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetMachine.h"
89 #include "llvm/Target/TargetOptions.h"
100 #define DEBUG_TYPE "ppc-lowering"
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
114 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumSiblingCalls, "Number of sibling calls");
117 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
119 // FIXME: Remove this once the bug has been fixed!
120 extern cl::opt<bool> ANDIGlueBug;
122 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
123 const PPCSubtarget &STI)
124 : TargetLowering(TM), Subtarget(STI) {
125 // Use _setjmp/_longjmp instead of setjmp/longjmp.
126 setUseUnderscoreSetJmp(true);
127 setUseUnderscoreLongJmp(true);
129 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
130 // arguments are at least 4/8 bytes aligned.
131 bool isPPC64 = Subtarget.isPPC64();
132 setMinStackArgumentAlignment(isPPC64 ? 8:4);
134 // Set up the register classes.
135 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
136 if (!useSoftFloat()) {
137 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
138 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
141 // Match BITREVERSE to customized fast code sequence in the td file.
142 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
143 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
145 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
146 for (MVT VT : MVT::integer_valuetypes()) {
147 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
148 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
151 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
153 // PowerPC has pre-inc load and store's.
154 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
155 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
156 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
157 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
158 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
159 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
160 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
161 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
162 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
163 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
164 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
165 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
166 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
167 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
169 if (Subtarget.useCRBits()) {
170 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
172 if (isPPC64 || Subtarget.hasFPCVT()) {
173 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
174 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
175 isPPC64 ? MVT::i64 : MVT::i32);
176 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
177 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
178 isPPC64 ? MVT::i64 : MVT::i32);
180 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
181 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
184 // PowerPC does not support direct load/store of condition registers.
185 setOperationAction(ISD::LOAD, MVT::i1, Custom);
186 setOperationAction(ISD::STORE, MVT::i1, Custom);
188 // FIXME: Remove this once the ANDI glue bug is fixed:
190 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
192 for (MVT VT : MVT::integer_valuetypes()) {
193 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
194 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
195 setTruncStoreAction(VT, MVT::i1, Expand);
198 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
201 // This is used in the ppcf128->int sequence. Note it has different semantics
202 // from FP_ROUND: that rounds to nearest, this rounds to zero.
203 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
205 // We do not currently implement these libm ops for PowerPC.
206 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
207 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
208 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
209 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
210 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
211 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
213 // PowerPC has no SREM/UREM instructions unless we are on P9
214 // On P9 we may use a hardware instruction to compute the remainder.
215 // The instructions are not legalized directly because in the cases where the
216 // result of both the remainder and the division is required it is more
217 // efficient to compute the remainder from the result of the division rather
218 // than use the remainder instruction.
219 if (Subtarget.isISA3_0()) {
220 setOperationAction(ISD::SREM, MVT::i32, Custom);
221 setOperationAction(ISD::UREM, MVT::i32, Custom);
222 setOperationAction(ISD::SREM, MVT::i64, Custom);
223 setOperationAction(ISD::UREM, MVT::i64, Custom);
225 setOperationAction(ISD::SREM, MVT::i32, Expand);
226 setOperationAction(ISD::UREM, MVT::i32, Expand);
227 setOperationAction(ISD::SREM, MVT::i64, Expand);
228 setOperationAction(ISD::UREM, MVT::i64, Expand);
231 if (Subtarget.hasP9Vector()) {
232 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
233 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
234 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
237 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
238 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
239 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
240 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
241 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
242 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
243 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
244 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
245 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
247 // We don't support sin/cos/sqrt/fmod/pow
248 setOperationAction(ISD::FSIN , MVT::f64, Expand);
249 setOperationAction(ISD::FCOS , MVT::f64, Expand);
250 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
251 setOperationAction(ISD::FREM , MVT::f64, Expand);
252 setOperationAction(ISD::FPOW , MVT::f64, Expand);
253 setOperationAction(ISD::FMA , MVT::f64, Legal);
254 setOperationAction(ISD::FSIN , MVT::f32, Expand);
255 setOperationAction(ISD::FCOS , MVT::f32, Expand);
256 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
257 setOperationAction(ISD::FREM , MVT::f32, Expand);
258 setOperationAction(ISD::FPOW , MVT::f32, Expand);
259 setOperationAction(ISD::FMA , MVT::f32, Legal);
261 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
263 // If we're enabling GP optimizations, use hardware square root
264 if (!Subtarget.hasFSQRT() &&
265 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
267 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
269 if (!Subtarget.hasFSQRT() &&
270 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
271 Subtarget.hasFRES()))
272 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
274 if (Subtarget.hasFCPSGN()) {
275 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
276 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
278 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
279 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
282 if (Subtarget.hasFPRND()) {
283 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
284 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
285 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
286 setOperationAction(ISD::FROUND, MVT::f64, Legal);
288 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
289 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
290 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
291 setOperationAction(ISD::FROUND, MVT::f32, Legal);
294 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
295 // to speed up scalar BSWAP64.
296 // CTPOP or CTTZ were introduced in P8/P9 respectivelly
297 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
298 if (Subtarget.isISA3_0()) {
299 setOperationAction(ISD::BSWAP, MVT::i64 , Custom);
300 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
301 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
303 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
304 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
305 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
308 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
309 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
310 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
312 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
313 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
316 // PowerPC does not have ROTR
317 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
318 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
320 if (!Subtarget.useCRBits()) {
321 // PowerPC does not have Select
322 setOperationAction(ISD::SELECT, MVT::i32, Expand);
323 setOperationAction(ISD::SELECT, MVT::i64, Expand);
324 setOperationAction(ISD::SELECT, MVT::f32, Expand);
325 setOperationAction(ISD::SELECT, MVT::f64, Expand);
328 // PowerPC wants to turn select_cc of FP into fsel when possible.
329 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
330 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
332 // PowerPC wants to optimize integer setcc a bit
333 if (!Subtarget.useCRBits())
334 setOperationAction(ISD::SETCC, MVT::i32, Custom);
336 // PowerPC does not have BRCOND which requires SetCC
337 if (!Subtarget.useCRBits())
338 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
340 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
342 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
343 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
345 // PowerPC does not have [U|S]INT_TO_FP
346 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
347 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
349 if (Subtarget.hasDirectMove() && isPPC64) {
350 setOperationAction(ISD::BITCAST, MVT::f32, Legal);
351 setOperationAction(ISD::BITCAST, MVT::i32, Legal);
352 setOperationAction(ISD::BITCAST, MVT::i64, Legal);
353 setOperationAction(ISD::BITCAST, MVT::f64, Legal);
355 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
356 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
357 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
358 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
361 // We cannot sextinreg(i1). Expand to shifts.
362 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
364 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
365 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
366 // support continuation, user-level threading, and etc.. As a result, no
367 // other SjLj exception interfaces are implemented and please don't build
368 // your own exception handling based on them.
369 // LLVM/Clang supports zero-cost DWARF exception handling.
370 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
371 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
373 // We want to legalize GlobalAddress and ConstantPool nodes into the
374 // appropriate instructions to materialize the address.
375 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
376 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
377 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
378 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
379 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
380 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
381 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
382 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
383 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
384 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
387 setOperationAction(ISD::TRAP, MVT::Other, Legal);
389 // TRAMPOLINE is custom lowered.
390 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
391 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
393 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
394 setOperationAction(ISD::VASTART , MVT::Other, Custom);
396 if (Subtarget.isSVR4ABI()) {
398 // VAARG always uses double-word chunks, so promote anything smaller.
399 setOperationAction(ISD::VAARG, MVT::i1, Promote);
400 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
401 setOperationAction(ISD::VAARG, MVT::i8, Promote);
402 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
403 setOperationAction(ISD::VAARG, MVT::i16, Promote);
404 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
405 setOperationAction(ISD::VAARG, MVT::i32, Promote);
406 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
407 setOperationAction(ISD::VAARG, MVT::Other, Expand);
409 // VAARG is custom lowered with the 32-bit SVR4 ABI.
410 setOperationAction(ISD::VAARG, MVT::Other, Custom);
411 setOperationAction(ISD::VAARG, MVT::i64, Custom);
414 setOperationAction(ISD::VAARG, MVT::Other, Expand);
416 if (Subtarget.isSVR4ABI() && !isPPC64)
417 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
418 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
420 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
422 // Use the default implementation.
423 setOperationAction(ISD::VAEND , MVT::Other, Expand);
424 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
425 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
426 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
427 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
428 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
429 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
430 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
431 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
433 // We want to custom lower some of our intrinsics.
434 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
436 // To handle counter-based loop conditions.
437 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
439 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
440 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
441 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
442 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
444 // Comparisons that require checking two conditions.
445 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
446 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
447 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
448 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
449 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
450 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
451 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
452 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
453 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
454 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
455 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
456 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
458 if (Subtarget.has64BitSupport()) {
459 // They also have instructions for converting between i64 and fp.
460 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
461 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
462 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
463 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
464 // This is just the low 32 bits of a (signed) fp->i64 conversion.
465 // We cannot do this with Promote because i64 is not a legal type.
466 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
468 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
469 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
471 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
472 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
475 // With the instructions enabled under FPCVT, we can do everything.
476 if (Subtarget.hasFPCVT()) {
477 if (Subtarget.has64BitSupport()) {
478 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
479 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
480 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
481 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
484 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
485 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
486 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
487 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
490 if (Subtarget.use64BitRegs()) {
491 // 64-bit PowerPC implementations can support i64 types directly
492 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
493 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
494 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
495 // 64-bit PowerPC wants to expand i128 shifts itself.
496 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
497 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
498 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
500 // 32-bit PowerPC wants to expand i64 shifts itself.
501 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
502 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
503 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
506 if (Subtarget.hasAltivec()) {
507 // First set operation action for all vector types to expand. Then we
508 // will selectively turn on ones that can be effectively codegen'd.
509 for (MVT VT : MVT::vector_valuetypes()) {
510 // add/sub are legal for all supported vector VT's.
511 setOperationAction(ISD::ADD, VT, Legal);
512 setOperationAction(ISD::SUB, VT, Legal);
514 // Vector instructions introduced in P8
515 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
516 setOperationAction(ISD::CTPOP, VT, Legal);
517 setOperationAction(ISD::CTLZ, VT, Legal);
520 setOperationAction(ISD::CTPOP, VT, Expand);
521 setOperationAction(ISD::CTLZ, VT, Expand);
524 // Vector instructions introduced in P9
525 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
526 setOperationAction(ISD::CTTZ, VT, Legal);
528 setOperationAction(ISD::CTTZ, VT, Expand);
530 // We promote all shuffles to v16i8.
531 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
532 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
534 // We promote all non-typed operations to v4i32.
535 setOperationAction(ISD::AND , VT, Promote);
536 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
537 setOperationAction(ISD::OR , VT, Promote);
538 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
539 setOperationAction(ISD::XOR , VT, Promote);
540 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
541 setOperationAction(ISD::LOAD , VT, Promote);
542 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
543 setOperationAction(ISD::SELECT, VT, Promote);
544 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
545 setOperationAction(ISD::SELECT_CC, VT, Promote);
546 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
547 setOperationAction(ISD::STORE, VT, Promote);
548 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
550 // No other operations are legal.
551 setOperationAction(ISD::MUL , VT, Expand);
552 setOperationAction(ISD::SDIV, VT, Expand);
553 setOperationAction(ISD::SREM, VT, Expand);
554 setOperationAction(ISD::UDIV, VT, Expand);
555 setOperationAction(ISD::UREM, VT, Expand);
556 setOperationAction(ISD::FDIV, VT, Expand);
557 setOperationAction(ISD::FREM, VT, Expand);
558 setOperationAction(ISD::FNEG, VT, Expand);
559 setOperationAction(ISD::FSQRT, VT, Expand);
560 setOperationAction(ISD::FLOG, VT, Expand);
561 setOperationAction(ISD::FLOG10, VT, Expand);
562 setOperationAction(ISD::FLOG2, VT, Expand);
563 setOperationAction(ISD::FEXP, VT, Expand);
564 setOperationAction(ISD::FEXP2, VT, Expand);
565 setOperationAction(ISD::FSIN, VT, Expand);
566 setOperationAction(ISD::FCOS, VT, Expand);
567 setOperationAction(ISD::FABS, VT, Expand);
568 setOperationAction(ISD::FFLOOR, VT, Expand);
569 setOperationAction(ISD::FCEIL, VT, Expand);
570 setOperationAction(ISD::FTRUNC, VT, Expand);
571 setOperationAction(ISD::FRINT, VT, Expand);
572 setOperationAction(ISD::FNEARBYINT, VT, Expand);
573 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
574 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
575 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
576 setOperationAction(ISD::MULHU, VT, Expand);
577 setOperationAction(ISD::MULHS, VT, Expand);
578 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
579 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
580 setOperationAction(ISD::UDIVREM, VT, Expand);
581 setOperationAction(ISD::SDIVREM, VT, Expand);
582 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
583 setOperationAction(ISD::FPOW, VT, Expand);
584 setOperationAction(ISD::BSWAP, VT, Expand);
585 setOperationAction(ISD::VSELECT, VT, Expand);
586 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
587 setOperationAction(ISD::ROTL, VT, Expand);
588 setOperationAction(ISD::ROTR, VT, Expand);
590 for (MVT InnerVT : MVT::vector_valuetypes()) {
591 setTruncStoreAction(VT, InnerVT, Expand);
592 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
593 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
594 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
598 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
599 // with merges, splats, etc.
600 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
602 setOperationAction(ISD::AND , MVT::v4i32, Legal);
603 setOperationAction(ISD::OR , MVT::v4i32, Legal);
604 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
605 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
606 setOperationAction(ISD::SELECT, MVT::v4i32,
607 Subtarget.useCRBits() ? Legal : Expand);
608 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
609 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
610 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
611 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
612 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
613 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
614 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
615 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
616 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
618 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
619 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
620 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
621 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
623 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
624 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
626 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
627 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
628 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
631 if (Subtarget.hasP8Altivec())
632 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
634 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
636 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
637 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
639 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
640 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
642 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
643 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
644 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
645 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
647 // Altivec does not contain unordered floating-point compare instructions
648 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
649 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
650 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
651 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
653 if (Subtarget.hasVSX()) {
654 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
655 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
656 if (Subtarget.hasP8Vector()) {
657 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
658 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
660 if (Subtarget.hasDirectMove() && isPPC64) {
661 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
662 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
663 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
664 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
665 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
666 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
667 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
668 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
670 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
672 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
673 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
674 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
675 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
676 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
678 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
680 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
681 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
683 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
684 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
686 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
687 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
688 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
689 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
690 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
692 // Share the Altivec comparison restrictions.
693 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
694 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
695 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
696 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
698 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
699 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
701 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
703 if (Subtarget.hasP8Vector())
704 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
706 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
708 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
709 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
710 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
712 if (Subtarget.hasP8Altivec()) {
713 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
714 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
715 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
717 // 128 bit shifts can be accomplished via 3 instructions for SHL and
718 // SRL, but not for SRA because of the instructions available:
719 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
721 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
722 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
723 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
725 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
728 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
729 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
730 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
732 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
734 // VSX v2i64 only supports non-arithmetic operations.
735 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
736 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
739 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
740 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
741 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
742 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
744 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
746 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
747 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
748 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
749 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
751 // Vector operation legalization checks the result type of
752 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
753 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
754 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
755 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
756 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
758 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
759 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
760 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
761 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
763 if (Subtarget.hasDirectMove())
764 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
765 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
767 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
770 if (Subtarget.hasP8Altivec()) {
771 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
772 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
775 if (Subtarget.hasP9Vector()) {
776 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
777 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
779 // 128 bit shifts can be accomplished via 3 instructions for SHL and
780 // SRL, but not for SRA because of the instructions available:
781 // VS{RL} and VS{RL}O.
782 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
783 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
784 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
787 if (Subtarget.hasP9Altivec()) {
788 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
789 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
793 if (Subtarget.hasQPX()) {
794 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
795 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
796 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
797 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
799 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
800 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
802 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
803 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
805 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
806 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
808 if (!Subtarget.useCRBits())
809 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
810 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
812 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
813 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
814 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
815 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
816 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
818 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
820 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
821 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
823 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
824 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
825 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
827 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
828 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
829 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
830 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
831 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
832 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
833 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
834 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
835 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
836 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
838 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
839 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
841 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
842 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
844 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
846 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
847 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
848 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
849 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
851 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
852 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
854 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
855 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
857 if (!Subtarget.useCRBits())
858 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
859 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
861 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
862 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
863 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
864 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
865 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
866 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
869 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
870 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
872 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
873 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
874 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
875 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
876 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
877 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
878 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
879 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
880 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
881 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
883 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
884 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
886 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
887 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
889 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
891 setOperationAction(ISD::AND , MVT::v4i1, Legal);
892 setOperationAction(ISD::OR , MVT::v4i1, Legal);
893 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
895 if (!Subtarget.useCRBits())
896 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
897 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
899 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
900 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
902 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
903 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
904 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
905 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
906 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
907 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
908 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
910 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
911 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
913 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
915 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
916 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
917 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
918 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
920 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
921 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
922 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
923 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
925 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
926 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
928 // These need to set FE_INEXACT, and so cannot be vectorized here.
929 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
930 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
932 if (TM.Options.UnsafeFPMath) {
933 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
934 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
936 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
937 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
939 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
940 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
942 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
943 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
947 if (Subtarget.has64BitSupport())
948 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
950 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
953 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
954 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
957 setBooleanContents(ZeroOrOneBooleanContent);
959 if (Subtarget.hasAltivec()) {
960 // Altivec instructions set fields to all zeros or all ones.
961 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
965 // These libcalls are not available in 32-bit.
966 setLibcallName(RTLIB::SHL_I128, nullptr);
967 setLibcallName(RTLIB::SRL_I128, nullptr);
968 setLibcallName(RTLIB::SRA_I128, nullptr);
971 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
973 // We have target-specific dag combine patterns for the following nodes:
974 setTargetDAGCombine(ISD::SHL);
975 setTargetDAGCombine(ISD::SRA);
976 setTargetDAGCombine(ISD::SRL);
977 setTargetDAGCombine(ISD::SINT_TO_FP);
978 setTargetDAGCombine(ISD::BUILD_VECTOR);
979 if (Subtarget.hasFPCVT())
980 setTargetDAGCombine(ISD::UINT_TO_FP);
981 setTargetDAGCombine(ISD::LOAD);
982 setTargetDAGCombine(ISD::STORE);
983 setTargetDAGCombine(ISD::BR_CC);
984 if (Subtarget.useCRBits())
985 setTargetDAGCombine(ISD::BRCOND);
986 setTargetDAGCombine(ISD::BSWAP);
987 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
988 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
989 setTargetDAGCombine(ISD::INTRINSIC_VOID);
991 setTargetDAGCombine(ISD::SIGN_EXTEND);
992 setTargetDAGCombine(ISD::ZERO_EXTEND);
993 setTargetDAGCombine(ISD::ANY_EXTEND);
995 if (Subtarget.useCRBits()) {
996 setTargetDAGCombine(ISD::TRUNCATE);
997 setTargetDAGCombine(ISD::SETCC);
998 setTargetDAGCombine(ISD::SELECT_CC);
1001 // Use reciprocal estimates.
1002 if (TM.Options.UnsafeFPMath) {
1003 setTargetDAGCombine(ISD::FDIV);
1004 setTargetDAGCombine(ISD::FSQRT);
1007 // Darwin long double math library functions have $LDBL128 appended.
1008 if (Subtarget.isDarwin()) {
1009 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1010 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1011 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1012 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1013 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1014 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1015 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1016 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1017 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1018 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1021 // With 32 condition bits, we don't need to sink (and duplicate) compares
1022 // aggressively in CodeGenPrep.
1023 if (Subtarget.useCRBits()) {
1024 setHasMultipleConditionRegisters();
1025 setJumpIsExpensive();
1028 setMinFunctionAlignment(2);
1029 if (Subtarget.isDarwin())
1030 setPrefFunctionAlignment(4);
1032 switch (Subtarget.getDarwinDirective()) {
1036 case PPC::DIR_E500mc:
1037 case PPC::DIR_E5500:
1040 case PPC::DIR_PWR5X:
1042 case PPC::DIR_PWR6X:
1046 setPrefFunctionAlignment(4);
1047 setPrefLoopAlignment(4);
1051 if (Subtarget.enableMachineScheduler())
1052 setSchedulingPreference(Sched::Source);
1054 setSchedulingPreference(Sched::Hybrid);
1056 computeRegisterProperties(STI.getRegisterInfo());
1058 // The Freescale cores do better with aggressive inlining of memcpy and
1059 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1060 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1061 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1062 MaxStoresPerMemset = 32;
1063 MaxStoresPerMemsetOptSize = 16;
1064 MaxStoresPerMemcpy = 32;
1065 MaxStoresPerMemcpyOptSize = 8;
1066 MaxStoresPerMemmove = 32;
1067 MaxStoresPerMemmoveOptSize = 8;
1068 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1069 // The A2 also benefits from (very) aggressive inlining of memcpy and
1070 // friends. The overhead of a the function call, even when warm, can be
1071 // over one hundred cycles.
1072 MaxStoresPerMemset = 128;
1073 MaxStoresPerMemcpy = 128;
1074 MaxStoresPerMemmove = 128;
1075 MaxLoadsPerMemcmp = 128;
1077 MaxLoadsPerMemcmp = 8;
1078 MaxLoadsPerMemcmpOptSize = 4;
1082 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1083 /// the desired ByVal argument alignment.
1084 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1085 unsigned MaxMaxAlign) {
1086 if (MaxAlign == MaxMaxAlign)
1088 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1089 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1091 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1093 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1094 unsigned EltAlign = 0;
1095 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1096 if (EltAlign > MaxAlign)
1097 MaxAlign = EltAlign;
1098 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1099 for (auto *EltTy : STy->elements()) {
1100 unsigned EltAlign = 0;
1101 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1102 if (EltAlign > MaxAlign)
1103 MaxAlign = EltAlign;
1104 if (MaxAlign == MaxMaxAlign)
1110 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1111 /// function arguments in the caller parameter area.
1112 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1113 const DataLayout &DL) const {
1114 // Darwin passes everything on 4 byte boundary.
1115 if (Subtarget.isDarwin())
1118 // 16byte and wider vectors are passed on 16byte boundary.
1119 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1120 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1121 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1122 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1126 bool PPCTargetLowering::useSoftFloat() const {
1127 return Subtarget.useSoftFloat();
1130 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1131 switch ((PPCISD::NodeType)Opcode) {
1132 case PPCISD::FIRST_NUMBER: break;
1133 case PPCISD::FSEL: return "PPCISD::FSEL";
1134 case PPCISD::FCFID: return "PPCISD::FCFID";
1135 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1136 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1137 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1138 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1139 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1140 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1141 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1142 case PPCISD::FRE: return "PPCISD::FRE";
1143 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1144 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1145 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
1146 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
1147 case PPCISD::VPERM: return "PPCISD::VPERM";
1148 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1149 case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1150 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE";
1151 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1152 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1153 case PPCISD::CMPB: return "PPCISD::CMPB";
1154 case PPCISD::Hi: return "PPCISD::Hi";
1155 case PPCISD::Lo: return "PPCISD::Lo";
1156 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1157 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1158 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1159 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1160 case PPCISD::SRL: return "PPCISD::SRL";
1161 case PPCISD::SRA: return "PPCISD::SRA";
1162 case PPCISD::SHL: return "PPCISD::SHL";
1163 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1164 case PPCISD::CALL: return "PPCISD::CALL";
1165 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1166 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1167 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1168 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1169 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1170 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1171 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1172 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1173 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1174 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1175 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1176 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1177 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1178 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1179 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1180 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1181 case PPCISD::VCMP: return "PPCISD::VCMP";
1182 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1183 case PPCISD::LBRX: return "PPCISD::LBRX";
1184 case PPCISD::STBRX: return "PPCISD::STBRX";
1185 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1186 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1187 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1188 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1189 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1190 case PPCISD::SExtVElems: return "PPCISD::SExtVElems";
1191 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1192 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1193 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1194 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1195 case PPCISD::BDZ: return "PPCISD::BDZ";
1196 case PPCISD::MFFS: return "PPCISD::MFFS";
1197 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1198 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1199 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1200 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1201 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1202 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1203 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1204 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1205 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1206 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1207 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1208 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1209 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1210 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1211 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1212 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1213 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1214 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1215 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1216 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1217 case PPCISD::SC: return "PPCISD::SC";
1218 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1219 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1220 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1221 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1222 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1223 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1224 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1225 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1226 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1227 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1228 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1233 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1236 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1238 if (Subtarget.hasQPX())
1239 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1241 return VT.changeVectorElementTypeToInteger();
1244 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1245 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1249 //===----------------------------------------------------------------------===//
1250 // Node matching predicates, for use by the tblgen matching code.
1251 //===----------------------------------------------------------------------===//
1253 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1254 static bool isFloatingPointZero(SDValue Op) {
1255 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1256 return CFP->getValueAPF().isZero();
1257 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1258 // Maybe this has already been legalized into the constant pool?
1259 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1260 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1261 return CFP->getValueAPF().isZero();
1266 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1267 /// true if Op is undef or if it matches the specified value.
1268 static bool isConstantOrUndef(int Op, int Val) {
1269 return Op < 0 || Op == Val;
1272 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1273 /// VPKUHUM instruction.
1274 /// The ShuffleKind distinguishes between big-endian operations with
1275 /// two different inputs (0), either-endian operations with two identical
1276 /// inputs (1), and little-endian operations with two different inputs (2).
1277 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1278 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1279 SelectionDAG &DAG) {
1280 bool IsLE = DAG.getDataLayout().isLittleEndian();
1281 if (ShuffleKind == 0) {
1284 for (unsigned i = 0; i != 16; ++i)
1285 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1287 } else if (ShuffleKind == 2) {
1290 for (unsigned i = 0; i != 16; ++i)
1291 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1293 } else if (ShuffleKind == 1) {
1294 unsigned j = IsLE ? 0 : 1;
1295 for (unsigned i = 0; i != 8; ++i)
1296 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1297 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1303 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1304 /// VPKUWUM instruction.
1305 /// The ShuffleKind distinguishes between big-endian operations with
1306 /// two different inputs (0), either-endian operations with two identical
1307 /// inputs (1), and little-endian operations with two different inputs (2).
1308 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1309 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1310 SelectionDAG &DAG) {
1311 bool IsLE = DAG.getDataLayout().isLittleEndian();
1312 if (ShuffleKind == 0) {
1315 for (unsigned i = 0; i != 16; i += 2)
1316 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1317 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1319 } else if (ShuffleKind == 2) {
1322 for (unsigned i = 0; i != 16; i += 2)
1323 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1324 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1326 } else if (ShuffleKind == 1) {
1327 unsigned j = IsLE ? 0 : 2;
1328 for (unsigned i = 0; i != 8; i += 2)
1329 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1330 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1331 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1332 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1338 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1339 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1340 /// current subtarget.
1342 /// The ShuffleKind distinguishes between big-endian operations with
1343 /// two different inputs (0), either-endian operations with two identical
1344 /// inputs (1), and little-endian operations with two different inputs (2).
1345 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1346 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1347 SelectionDAG &DAG) {
1348 const PPCSubtarget& Subtarget =
1349 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1350 if (!Subtarget.hasP8Vector())
1353 bool IsLE = DAG.getDataLayout().isLittleEndian();
1354 if (ShuffleKind == 0) {
1357 for (unsigned i = 0; i != 16; i += 4)
1358 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1359 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1360 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1361 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1363 } else if (ShuffleKind == 2) {
1366 for (unsigned i = 0; i != 16; i += 4)
1367 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1368 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1369 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1370 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1372 } else if (ShuffleKind == 1) {
1373 unsigned j = IsLE ? 0 : 4;
1374 for (unsigned i = 0; i != 8; i += 4)
1375 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1376 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1377 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1378 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1379 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1380 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1381 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1382 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1388 /// isVMerge - Common function, used to match vmrg* shuffles.
1390 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1391 unsigned LHSStart, unsigned RHSStart) {
1392 if (N->getValueType(0) != MVT::v16i8)
1394 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1395 "Unsupported merge size!");
1397 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1398 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1399 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1400 LHSStart+j+i*UnitSize) ||
1401 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1402 RHSStart+j+i*UnitSize))
1408 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1409 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1410 /// The ShuffleKind distinguishes between big-endian merges with two
1411 /// different inputs (0), either-endian merges with two identical inputs (1),
1412 /// and little-endian merges with two different inputs (2). For the latter,
1413 /// the input operands are swapped (see PPCInstrAltivec.td).
1414 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1415 unsigned ShuffleKind, SelectionDAG &DAG) {
1416 if (DAG.getDataLayout().isLittleEndian()) {
1417 if (ShuffleKind == 1) // unary
1418 return isVMerge(N, UnitSize, 0, 0);
1419 else if (ShuffleKind == 2) // swapped
1420 return isVMerge(N, UnitSize, 0, 16);
1424 if (ShuffleKind == 1) // unary
1425 return isVMerge(N, UnitSize, 8, 8);
1426 else if (ShuffleKind == 0) // normal
1427 return isVMerge(N, UnitSize, 8, 24);
1433 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1434 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1435 /// The ShuffleKind distinguishes between big-endian merges with two
1436 /// different inputs (0), either-endian merges with two identical inputs (1),
1437 /// and little-endian merges with two different inputs (2). For the latter,
1438 /// the input operands are swapped (see PPCInstrAltivec.td).
1439 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1440 unsigned ShuffleKind, SelectionDAG &DAG) {
1441 if (DAG.getDataLayout().isLittleEndian()) {
1442 if (ShuffleKind == 1) // unary
1443 return isVMerge(N, UnitSize, 8, 8);
1444 else if (ShuffleKind == 2) // swapped
1445 return isVMerge(N, UnitSize, 8, 24);
1449 if (ShuffleKind == 1) // unary
1450 return isVMerge(N, UnitSize, 0, 0);
1451 else if (ShuffleKind == 0) // normal
1452 return isVMerge(N, UnitSize, 0, 16);
1459 * \brief Common function used to match vmrgew and vmrgow shuffles
1461 * The indexOffset determines whether to look for even or odd words in
1462 * the shuffle mask. This is based on the of the endianness of the target
1465 * - Use offset of 0 to check for odd elements
1466 * - Use offset of 4 to check for even elements
1468 * - Use offset of 0 to check for even elements
1469 * - Use offset of 4 to check for odd elements
1470 * A detailed description of the vector element ordering for little endian and
1471 * big endian can be found at
1472 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1473 * Targeting your applications - what little endian and big endian IBM XL C/C++
1474 * compiler differences mean to you
1476 * The mask to the shuffle vector instruction specifies the indices of the
1477 * elements from the two input vectors to place in the result. The elements are
1478 * numbered in array-access order, starting with the first vector. These vectors
1479 * are always of type v16i8, thus each vector will contain 16 elements of size
1480 * 8. More info on the shuffle vector can be found in the
1481 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1482 * Language Reference.
1484 * The RHSStartValue indicates whether the same input vectors are used (unary)
1485 * or two different input vectors are used, based on the following:
1486 * - If the instruction uses the same vector for both inputs, the range of the
1487 * indices will be 0 to 15. In this case, the RHSStart value passed should
1489 * - If the instruction has two different vectors then the range of the
1490 * indices will be 0 to 31. In this case, the RHSStart value passed should
1491 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1492 * to 31 specify elements in the second vector).
1494 * \param[in] N The shuffle vector SD Node to analyze
1495 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1496 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1497 * vector to the shuffle_vector instruction
1498 * \return true iff this shuffle vector represents an even or odd word merge
1500 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1501 unsigned RHSStartValue) {
1502 if (N->getValueType(0) != MVT::v16i8)
1505 for (unsigned i = 0; i < 2; ++i)
1506 for (unsigned j = 0; j < 4; ++j)
1507 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1508 i*RHSStartValue+j+IndexOffset) ||
1509 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1510 i*RHSStartValue+j+IndexOffset+8))
1516 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1517 * vmrgow instructions.
1519 * \param[in] N The shuffle vector SD Node to analyze
1520 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1521 * \param[in] ShuffleKind Identify the type of merge:
1522 * - 0 = big-endian merge with two different inputs;
1523 * - 1 = either-endian merge with two identical inputs;
1524 * - 2 = little-endian merge with two different inputs (inputs are swapped for
1525 * little-endian merges).
1526 * \param[in] DAG The current SelectionDAG
1527 * \return true iff this shuffle mask
1529 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1530 unsigned ShuffleKind, SelectionDAG &DAG) {
1531 if (DAG.getDataLayout().isLittleEndian()) {
1532 unsigned indexOffset = CheckEven ? 4 : 0;
1533 if (ShuffleKind == 1) // Unary
1534 return isVMerge(N, indexOffset, 0);
1535 else if (ShuffleKind == 2) // swapped
1536 return isVMerge(N, indexOffset, 16);
1541 unsigned indexOffset = CheckEven ? 0 : 4;
1542 if (ShuffleKind == 1) // Unary
1543 return isVMerge(N, indexOffset, 0);
1544 else if (ShuffleKind == 0) // Normal
1545 return isVMerge(N, indexOffset, 16);
1552 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1553 /// amount, otherwise return -1.
1554 /// The ShuffleKind distinguishes between big-endian operations with two
1555 /// different inputs (0), either-endian operations with two identical inputs
1556 /// (1), and little-endian operations with two different inputs (2). For the
1557 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1558 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1559 SelectionDAG &DAG) {
1560 if (N->getValueType(0) != MVT::v16i8)
1563 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1565 // Find the first non-undef value in the shuffle mask.
1567 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1570 if (i == 16) return -1; // all undef.
1572 // Otherwise, check to see if the rest of the elements are consecutively
1573 // numbered from this value.
1574 unsigned ShiftAmt = SVOp->getMaskElt(i);
1575 if (ShiftAmt < i) return -1;
1578 bool isLE = DAG.getDataLayout().isLittleEndian();
1580 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1581 // Check the rest of the elements to see if they are consecutive.
1582 for (++i; i != 16; ++i)
1583 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1585 } else if (ShuffleKind == 1) {
1586 // Check the rest of the elements to see if they are consecutive.
1587 for (++i; i != 16; ++i)
1588 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1594 ShiftAmt = 16 - ShiftAmt;
1599 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1600 /// specifies a splat of a single element that is suitable for input to
1601 /// VSPLTB/VSPLTH/VSPLTW.
1602 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1603 assert(N->getValueType(0) == MVT::v16i8 &&
1604 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1606 // The consecutive indices need to specify an element, not part of two
1607 // different elements. So abandon ship early if this isn't the case.
1608 if (N->getMaskElt(0) % EltSize != 0)
1611 // This is a splat operation if each element of the permute is the same, and
1612 // if the value doesn't reference the second vector.
1613 unsigned ElementBase = N->getMaskElt(0);
1615 // FIXME: Handle UNDEF elements too!
1616 if (ElementBase >= 16)
1619 // Check that the indices are consecutive, in the case of a multi-byte element
1620 // splatted with a v16i8 mask.
1621 for (unsigned i = 1; i != EltSize; ++i)
1622 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1625 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1626 if (N->getMaskElt(i) < 0) continue;
1627 for (unsigned j = 0; j != EltSize; ++j)
1628 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1634 /// Check that the mask is shuffling N byte elements. Within each N byte
1635 /// element of the mask, the indices could be either in increasing or
1636 /// decreasing order as long as they are consecutive.
1637 /// \param[in] N the shuffle vector SD Node to analyze
1638 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1639 /// Word/DoubleWord/QuadWord).
1640 /// \param[in] StepLen the delta indices number among the N byte element, if
1641 /// the mask is in increasing/decreasing order then it is 1/-1.
1642 /// \return true iff the mask is shuffling N byte elements.
1643 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1645 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1646 "Unexpected element width.");
1647 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1649 unsigned NumOfElem = 16 / Width;
1650 unsigned MaskVal[16]; // Width is never greater than 16
1651 for (unsigned i = 0; i < NumOfElem; ++i) {
1652 MaskVal[0] = N->getMaskElt(i * Width);
1653 if ((StepLen == 1) && (MaskVal[0] % Width)) {
1655 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1659 for (unsigned int j = 1; j < Width; ++j) {
1660 MaskVal[j] = N->getMaskElt(i * Width + j);
1661 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1670 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1671 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1672 if (!isNByteElemShuffleMask(N, 4, 1))
1675 // Now we look at mask elements 0,4,8,12
1676 unsigned M0 = N->getMaskElt(0) / 4;
1677 unsigned M1 = N->getMaskElt(4) / 4;
1678 unsigned M2 = N->getMaskElt(8) / 4;
1679 unsigned M3 = N->getMaskElt(12) / 4;
1680 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1681 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1683 // Below, let H and L be arbitrary elements of the shuffle mask
1684 // where H is in the range [4,7] and L is in the range [0,3].
1685 // H, 1, 2, 3 or L, 5, 6, 7
1686 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1687 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1688 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1689 InsertAtByte = IsLE ? 12 : 0;
1693 // 0, H, 2, 3 or 4, L, 6, 7
1694 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1695 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1696 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1697 InsertAtByte = IsLE ? 8 : 4;
1701 // 0, 1, H, 3 or 4, 5, L, 7
1702 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1703 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1704 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1705 InsertAtByte = IsLE ? 4 : 8;
1709 // 0, 1, 2, H or 4, 5, 6, L
1710 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1711 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1712 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1713 InsertAtByte = IsLE ? 0 : 12;
1718 // If both vector operands for the shuffle are the same vector, the mask will
1719 // contain only elements from the first one and the second one will be undef.
1720 if (N->getOperand(1).isUndef()) {
1723 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1724 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1725 InsertAtByte = IsLE ? 12 : 0;
1728 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1729 InsertAtByte = IsLE ? 8 : 4;
1732 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1733 InsertAtByte = IsLE ? 4 : 8;
1736 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1737 InsertAtByte = IsLE ? 0 : 12;
1745 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1746 bool &Swap, bool IsLE) {
1747 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1748 // Ensure each byte index of the word is consecutive.
1749 if (!isNByteElemShuffleMask(N, 4, 1))
1752 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1753 unsigned M0 = N->getMaskElt(0) / 4;
1754 unsigned M1 = N->getMaskElt(4) / 4;
1755 unsigned M2 = N->getMaskElt(8) / 4;
1756 unsigned M3 = N->getMaskElt(12) / 4;
1758 // If both vector operands for the shuffle are the same vector, the mask will
1759 // contain only elements from the first one and the second one will be undef.
1760 if (N->getOperand(1).isUndef()) {
1761 assert(M0 < 4 && "Indexing into an undef vector?");
1762 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1765 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1770 // Ensure each word index of the ShuffleVector Mask is consecutive.
1771 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1775 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1776 // Input vectors don't need to be swapped if the leading element
1777 // of the result is one of the 3 left elements of the second vector
1778 // (or if there is no shift to be done at all).
1780 ShiftElts = (8 - M0) % 8;
1781 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1782 // Input vectors need to be swapped if the leading element
1783 // of the result is one of the 3 left elements of the first vector
1784 // (or if we're shifting by 4 - thereby simply swapping the vectors).
1786 ShiftElts = (4 - M0) % 4;
1791 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1792 // Input vectors don't need to be swapped if the leading element
1793 // of the result is one of the 4 elements of the first vector.
1796 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1797 // Input vectors need to be swapped if the leading element
1798 // of the result is one of the 4 elements of the right vector.
1807 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1808 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1810 if (!isNByteElemShuffleMask(N, Width, -1))
1813 for (int i = 0; i < 16; i += Width)
1814 if (N->getMaskElt(i) != i + Width - 1)
1820 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1821 return isXXBRShuffleMaskHelper(N, 2);
1824 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1825 return isXXBRShuffleMaskHelper(N, 4);
1828 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
1829 return isXXBRShuffleMaskHelper(N, 8);
1832 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
1833 return isXXBRShuffleMaskHelper(N, 16);
1836 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1837 /// if the inputs to the instruction should be swapped and set \p DM to the
1838 /// value for the immediate.
1839 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1840 /// AND element 0 of the result comes from the first input (LE) or second input
1841 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1842 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1844 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
1845 bool &Swap, bool IsLE) {
1846 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1848 // Ensure each byte index of the double word is consecutive.
1849 if (!isNByteElemShuffleMask(N, 8, 1))
1852 unsigned M0 = N->getMaskElt(0) / 8;
1853 unsigned M1 = N->getMaskElt(8) / 8;
1854 assert(((M0 | M1) < 4) && "A mask element out of bounds?");
1856 // If both vector operands for the shuffle are the same vector, the mask will
1857 // contain only elements from the first one and the second one will be undef.
1858 if (N->getOperand(1).isUndef()) {
1859 if ((M0 | M1) < 2) {
1860 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
1868 if (M0 > 1 && M1 < 2) {
1870 } else if (M0 < 2 && M1 > 1) {
1877 // Note: if control flow comes here that means Swap is already set above
1878 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
1881 if (M0 < 2 && M1 > 1) {
1883 } else if (M0 > 1 && M1 < 2) {
1890 // Note: if control flow comes here that means Swap is already set above
1891 DM = (M0 << 1) + (M1 & 1);
1897 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1898 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1899 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1900 SelectionDAG &DAG) {
1901 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1902 assert(isSplatShuffleMask(SVOp, EltSize));
1903 if (DAG.getDataLayout().isLittleEndian())
1904 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1906 return SVOp->getMaskElt(0) / EltSize;
1909 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1910 /// by using a vspltis[bhw] instruction of the specified element size, return
1911 /// the constant being splatted. The ByteSize field indicates the number of
1912 /// bytes of each element [124] -> [bhw].
1913 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1914 SDValue OpVal(nullptr, 0);
1916 // If ByteSize of the splat is bigger than the element size of the
1917 // build_vector, then we have a case where we are checking for a splat where
1918 // multiple elements of the buildvector are folded together into a single
1919 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1920 unsigned EltSize = 16/N->getNumOperands();
1921 if (EltSize < ByteSize) {
1922 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1923 SDValue UniquedVals[4];
1924 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1926 // See if all of the elements in the buildvector agree across.
1927 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1928 if (N->getOperand(i).isUndef()) continue;
1929 // If the element isn't a constant, bail fully out.
1930 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1932 if (!UniquedVals[i&(Multiple-1)].getNode())
1933 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1934 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1935 return SDValue(); // no match.
1938 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1939 // either constant or undef values that are identical for each chunk. See
1940 // if these chunks can form into a larger vspltis*.
1942 // Check to see if all of the leading entries are either 0 or -1. If
1943 // neither, then this won't fit into the immediate field.
1944 bool LeadingZero = true;
1945 bool LeadingOnes = true;
1946 for (unsigned i = 0; i != Multiple-1; ++i) {
1947 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1949 LeadingZero &= isNullConstant(UniquedVals[i]);
1950 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1952 // Finally, check the least significant entry.
1954 if (!UniquedVals[Multiple-1].getNode())
1955 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
1956 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1957 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
1958 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1961 if (!UniquedVals[Multiple-1].getNode())
1962 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1963 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1964 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1965 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1971 // Check to see if this buildvec has a single non-undef value in its elements.
1972 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1973 if (N->getOperand(i).isUndef()) continue;
1974 if (!OpVal.getNode())
1975 OpVal = N->getOperand(i);
1976 else if (OpVal != N->getOperand(i))
1980 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1982 unsigned ValSizeInBytes = EltSize;
1984 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1985 Value = CN->getZExtValue();
1986 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1987 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1988 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1991 // If the splat value is larger than the element value, then we can never do
1992 // this splat. The only case that we could fit the replicated bits into our
1993 // immediate field for would be zero, and we prefer to use vxor for it.
1994 if (ValSizeInBytes < ByteSize) return SDValue();
1996 // If the element value is larger than the splat value, check if it consists
1997 // of a repeated bit pattern of size ByteSize.
1998 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2001 // Properly sign extend the value.
2002 int MaskVal = SignExtend32(Value, ByteSize * 8);
2004 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2005 if (MaskVal == 0) return SDValue();
2007 // Finally, if this value fits in a 5 bit sext field, return it
2008 if (SignExtend32<5>(MaskVal) == MaskVal)
2009 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2013 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2014 /// amount, otherwise return -1.
2015 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2016 EVT VT = N->getValueType(0);
2017 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2020 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2022 // Find the first non-undef value in the shuffle mask.
2024 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2027 if (i == 4) return -1; // all undef.
2029 // Otherwise, check to see if the rest of the elements are consecutively
2030 // numbered from this value.
2031 unsigned ShiftAmt = SVOp->getMaskElt(i);
2032 if (ShiftAmt < i) return -1;
2035 // Check the rest of the elements to see if they are consecutive.
2036 for (++i; i != 4; ++i)
2037 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2043 //===----------------------------------------------------------------------===//
2044 // Addressing Mode Selection
2045 //===----------------------------------------------------------------------===//
2047 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2048 /// or 64-bit immediate, and if the value can be accurately represented as a
2049 /// sign extension from a 16-bit value. If so, this returns true and the
2051 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2052 if (!isa<ConstantSDNode>(N))
2055 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2056 if (N->getValueType(0) == MVT::i32)
2057 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2059 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2061 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2062 return isIntS16Immediate(Op.getNode(), Imm);
2065 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2066 /// can be represented as an indexed [r+r] operation. Returns false if it
2067 /// can be more efficiently represented with [r+imm].
2068 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2070 SelectionDAG &DAG) const {
2072 if (N.getOpcode() == ISD::ADD) {
2073 if (isIntS16Immediate(N.getOperand(1), imm))
2074 return false; // r+i
2075 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2076 return false; // r+i
2078 Base = N.getOperand(0);
2079 Index = N.getOperand(1);
2081 } else if (N.getOpcode() == ISD::OR) {
2082 if (isIntS16Immediate(N.getOperand(1), imm))
2083 return false; // r+i can fold it if we can.
2085 // If this is an or of disjoint bitfields, we can codegen this as an add
2086 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2088 KnownBits LHSKnown, RHSKnown;
2089 DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2091 if (LHSKnown.Zero.getBoolValue()) {
2092 DAG.computeKnownBits(N.getOperand(1), RHSKnown);
2093 // If all of the bits are known zero on the LHS or RHS, the add won't
2095 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2096 Base = N.getOperand(0);
2097 Index = N.getOperand(1);
2106 // If we happen to be doing an i64 load or store into a stack slot that has
2107 // less than a 4-byte alignment, then the frame-index elimination may need to
2108 // use an indexed load or store instruction (because the offset may not be a
2109 // multiple of 4). The extra register needed to hold the offset comes from the
2110 // register scavenger, and it is possible that the scavenger will need to use
2111 // an emergency spill slot. As a result, we need to make sure that a spill slot
2112 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2114 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2115 // FIXME: This does not handle the LWA case.
2119 // NOTE: We'll exclude negative FIs here, which come from argument
2120 // lowering, because there are no known test cases triggering this problem
2121 // using packed structures (or similar). We can remove this exclusion if
2122 // we find such a test case. The reason why this is so test-case driven is
2123 // because this entire 'fixup' is only to prevent crashes (from the
2124 // register scavenger) on not-really-valid inputs. For example, if we have:
2126 // %b = bitcast i1* %a to i64*
2127 // store i64* a, i64 b
2128 // then the store should really be marked as 'align 1', but is not. If it
2129 // were marked as 'align 1' then the indexed form would have been
2130 // instruction-selected initially, and the problem this 'fixup' is preventing
2131 // won't happen regardless.
2135 MachineFunction &MF = DAG.getMachineFunction();
2136 MachineFrameInfo &MFI = MF.getFrameInfo();
2138 unsigned Align = MFI.getObjectAlignment(FrameIdx);
2142 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2143 FuncInfo->setHasNonRISpills();
2146 /// Returns true if the address N can be represented by a base register plus
2147 /// a signed 16-bit displacement [r+imm], and if it is not better
2148 /// represented as reg+reg. If \p Alignment is non-zero, only accept
2149 /// displacements that are multiples of that value.
2150 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2153 unsigned Alignment) const {
2154 // FIXME dl should come from parent load or store, not from address
2156 // If this can be more profitably realized as r+r, fail.
2157 if (SelectAddressRegReg(N, Disp, Base, DAG))
2160 if (N.getOpcode() == ISD::ADD) {
2162 if (isIntS16Immediate(N.getOperand(1), imm) &&
2163 (!Alignment || (imm % Alignment) == 0)) {
2164 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2165 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2166 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2167 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2169 Base = N.getOperand(0);
2171 return true; // [r+i]
2172 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2173 // Match LOAD (ADD (X, Lo(G))).
2174 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2175 && "Cannot handle constant offsets yet!");
2176 Disp = N.getOperand(1).getOperand(0); // The global address.
2177 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2178 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2179 Disp.getOpcode() == ISD::TargetConstantPool ||
2180 Disp.getOpcode() == ISD::TargetJumpTable);
2181 Base = N.getOperand(0);
2182 return true; // [&g+r]
2184 } else if (N.getOpcode() == ISD::OR) {
2186 if (isIntS16Immediate(N.getOperand(1), imm) &&
2187 (!Alignment || (imm % Alignment) == 0)) {
2188 // If this is an or of disjoint bitfields, we can codegen this as an add
2189 // (for better address arithmetic) if the LHS and RHS of the OR are
2190 // provably disjoint.
2192 DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2194 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2195 // If all of the bits are known zero on the LHS or RHS, the add won't
2197 if (FrameIndexSDNode *FI =
2198 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2199 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2200 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2202 Base = N.getOperand(0);
2204 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2208 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2209 // Loading from a constant address.
2211 // If this address fits entirely in a 16-bit sext immediate field, codegen
2214 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2215 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2216 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2217 CN->getValueType(0));
2221 // Handle 32-bit sext immediates with LIS + addr mode.
2222 if ((CN->getValueType(0) == MVT::i32 ||
2223 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2224 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2225 int Addr = (int)CN->getZExtValue();
2227 // Otherwise, break this down into an LIS + disp.
2228 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2230 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2232 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2233 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2238 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2239 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2240 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2241 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2244 return true; // [r+0]
2247 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2248 /// represented as an indexed [r+r] operation.
2249 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2251 SelectionDAG &DAG) const {
2252 // Check to see if we can easily represent this as an [r+r] address. This
2253 // will fail if it thinks that the address is more profitably represented as
2254 // reg+imm, e.g. where imm = 0.
2255 if (SelectAddressRegReg(N, Base, Index, DAG))
2258 // If the address is the result of an add, we will utilize the fact that the
2259 // address calculation includes an implicit add. However, we can reduce
2260 // register pressure if we do not materialize a constant just for use as the
2261 // index register. We only get rid of the add if it is not an add of a
2262 // value and a 16-bit signed constant and both have a single use.
2264 if (N.getOpcode() == ISD::ADD &&
2265 (!isIntS16Immediate(N.getOperand(1), imm) ||
2266 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2267 Base = N.getOperand(0);
2268 Index = N.getOperand(1);
2272 // Otherwise, do it the hard way, using R0 as the base register.
2273 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2279 /// getPreIndexedAddressParts - returns true by value, base pointer and
2280 /// offset pointer and addressing mode by reference if the node's address
2281 /// can be legally represented as pre-indexed load / store address.
2282 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2284 ISD::MemIndexedMode &AM,
2285 SelectionDAG &DAG) const {
2286 if (DisablePPCPreinc) return false;
2292 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2293 Ptr = LD->getBasePtr();
2294 VT = LD->getMemoryVT();
2295 Alignment = LD->getAlignment();
2296 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2297 Ptr = ST->getBasePtr();
2298 VT = ST->getMemoryVT();
2299 Alignment = ST->getAlignment();
2304 // PowerPC doesn't have preinc load/store instructions for vectors (except
2305 // for QPX, which does have preinc r+r forms).
2306 if (VT.isVector()) {
2307 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2309 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2315 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2316 // Common code will reject creating a pre-inc form if the base pointer
2317 // is a frame index, or if N is a store and the base pointer is either
2318 // the same as or a predecessor of the value being stored. Check for
2319 // those situations here, and try with swapped Base/Offset instead.
2322 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2325 SDValue Val = cast<StoreSDNode>(N)->getValue();
2326 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2331 std::swap(Base, Offset);
2337 // LDU/STU can only handle immediates that are a multiple of 4.
2338 if (VT != MVT::i64) {
2339 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2342 // LDU/STU need an address with at least 4-byte alignment.
2346 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2350 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2351 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2352 // sext i32 to i64 when addr mode is r+i.
2353 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2354 LD->getExtensionType() == ISD::SEXTLOAD &&
2355 isa<ConstantSDNode>(Offset))
2363 //===----------------------------------------------------------------------===//
2364 // LowerOperation implementation
2365 //===----------------------------------------------------------------------===//
2367 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2368 /// and LoOpFlags to the target MO flags.
2369 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2370 unsigned &HiOpFlags, unsigned &LoOpFlags,
2371 const GlobalValue *GV = nullptr) {
2372 HiOpFlags = PPCII::MO_HA;
2373 LoOpFlags = PPCII::MO_LO;
2375 // Don't use the pic base if not in PIC relocation model.
2377 HiOpFlags |= PPCII::MO_PIC_FLAG;
2378 LoOpFlags |= PPCII::MO_PIC_FLAG;
2381 // If this is a reference to a global value that requires a non-lazy-ptr, make
2382 // sure that instruction lowering adds it.
2383 if (GV && Subtarget.hasLazyResolverStub(GV)) {
2384 HiOpFlags |= PPCII::MO_NLP_FLAG;
2385 LoOpFlags |= PPCII::MO_NLP_FLAG;
2387 if (GV->hasHiddenVisibility()) {
2388 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2389 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2394 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2395 SelectionDAG &DAG) {
2397 EVT PtrVT = HiPart.getValueType();
2398 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2400 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2401 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2403 // With PIC, the first instruction is actually "GR+hi(&G)".
2405 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2406 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2408 // Generate non-pic code that has direct accesses to the constant pool.
2409 // The address of the global is just (hi(&g)+lo(&g)).
2410 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2413 static void setUsesTOCBasePtr(MachineFunction &MF) {
2414 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2415 FuncInfo->setUsesTOCBasePtr();
2418 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2419 setUsesTOCBasePtr(DAG.getMachineFunction());
2422 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2424 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2425 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2426 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2428 SDValue Ops[] = { GA, Reg };
2429 return DAG.getMemIntrinsicNode(
2430 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2431 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2432 MachineMemOperand::MOLoad);
2435 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2436 SelectionDAG &DAG) const {
2437 EVT PtrVT = Op.getValueType();
2438 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2439 const Constant *C = CP->getConstVal();
2441 // 64-bit SVR4 ABI code is always position-independent.
2442 // The actual address of the GlobalValue is stored in the TOC.
2443 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2444 setUsesTOCBasePtr(DAG);
2445 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2446 return getTOCEntry(DAG, SDLoc(CP), true, GA);
2449 unsigned MOHiFlag, MOLoFlag;
2450 bool IsPIC = isPositionIndependent();
2451 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2453 if (IsPIC && Subtarget.isSVR4ABI()) {
2454 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2455 PPCII::MO_PIC_FLAG);
2456 return getTOCEntry(DAG, SDLoc(CP), false, GA);
2460 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2462 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2463 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2466 // For 64-bit PowerPC, prefer the more compact relative encodings.
2467 // This trades 32 bits per jump table entry for one or two instructions
2468 // on the jump site.
2469 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2470 if (isJumpTableRelative())
2471 return MachineJumpTableInfo::EK_LabelDifference32;
2473 return TargetLowering::getJumpTableEncoding();
2476 bool PPCTargetLowering::isJumpTableRelative() const {
2477 if (Subtarget.isPPC64())
2479 return TargetLowering::isJumpTableRelative();
2482 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2483 SelectionDAG &DAG) const {
2484 if (!Subtarget.isPPC64())
2485 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2487 switch (getTargetMachine().getCodeModel()) {
2488 case CodeModel::Small:
2489 case CodeModel::Medium:
2490 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2492 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2493 getPointerTy(DAG.getDataLayout()));
2498 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2500 MCContext &Ctx) const {
2501 if (!Subtarget.isPPC64())
2502 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2504 switch (getTargetMachine().getCodeModel()) {
2505 case CodeModel::Small:
2506 case CodeModel::Medium:
2507 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2509 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2513 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2514 EVT PtrVT = Op.getValueType();
2515 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2517 // 64-bit SVR4 ABI code is always position-independent.
2518 // The actual address of the GlobalValue is stored in the TOC.
2519 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2520 setUsesTOCBasePtr(DAG);
2521 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2522 return getTOCEntry(DAG, SDLoc(JT), true, GA);
2525 unsigned MOHiFlag, MOLoFlag;
2526 bool IsPIC = isPositionIndependent();
2527 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2529 if (IsPIC && Subtarget.isSVR4ABI()) {
2530 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2531 PPCII::MO_PIC_FLAG);
2532 return getTOCEntry(DAG, SDLoc(GA), false, GA);
2535 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2536 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2537 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2540 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2541 SelectionDAG &DAG) const {
2542 EVT PtrVT = Op.getValueType();
2543 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2544 const BlockAddress *BA = BASDN->getBlockAddress();
2546 // 64-bit SVR4 ABI code is always position-independent.
2547 // The actual BlockAddress is stored in the TOC.
2548 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2549 setUsesTOCBasePtr(DAG);
2550 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2551 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2554 unsigned MOHiFlag, MOLoFlag;
2555 bool IsPIC = isPositionIndependent();
2556 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2557 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2558 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2559 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2562 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2563 SelectionDAG &DAG) const {
2564 // FIXME: TLS addresses currently use medium model code sequences,
2565 // which is the most useful form. Eventually support for small and
2566 // large models could be added if users need it, at the cost of
2567 // additional complexity.
2568 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2569 if (DAG.getTarget().Options.EmulatedTLS)
2570 return LowerToTLSEmulatedModel(GA, DAG);
2573 const GlobalValue *GV = GA->getGlobal();
2574 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2575 bool is64bit = Subtarget.isPPC64();
2576 const Module *M = DAG.getMachineFunction().getFunction().getParent();
2577 PICLevel::Level picLevel = M->getPICLevel();
2579 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2581 if (Model == TLSModel::LocalExec) {
2582 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2583 PPCII::MO_TPREL_HA);
2584 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2585 PPCII::MO_TPREL_LO);
2586 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2587 : DAG.getRegister(PPC::R2, MVT::i32);
2589 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2590 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2593 if (Model == TLSModel::InitialExec) {
2594 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2595 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2599 setUsesTOCBasePtr(DAG);
2600 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2601 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2602 PtrVT, GOTReg, TGA);
2604 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2605 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2606 PtrVT, TGA, GOTPtr);
2607 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2610 if (Model == TLSModel::GeneralDynamic) {
2611 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2614 setUsesTOCBasePtr(DAG);
2615 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2616 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2619 if (picLevel == PICLevel::SmallPIC)
2620 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2622 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2624 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2628 if (Model == TLSModel::LocalDynamic) {
2629 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2632 setUsesTOCBasePtr(DAG);
2633 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2634 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2637 if (picLevel == PICLevel::SmallPIC)
2638 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2640 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2642 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2643 PtrVT, GOTPtr, TGA, TGA);
2644 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2645 PtrVT, TLSAddr, TGA);
2646 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2649 llvm_unreachable("Unknown TLS model!");
2652 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2653 SelectionDAG &DAG) const {
2654 EVT PtrVT = Op.getValueType();
2655 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2657 const GlobalValue *GV = GSDN->getGlobal();
2659 // 64-bit SVR4 ABI code is always position-independent.
2660 // The actual address of the GlobalValue is stored in the TOC.
2661 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2662 setUsesTOCBasePtr(DAG);
2663 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2664 return getTOCEntry(DAG, DL, true, GA);
2667 unsigned MOHiFlag, MOLoFlag;
2668 bool IsPIC = isPositionIndependent();
2669 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2671 if (IsPIC && Subtarget.isSVR4ABI()) {
2672 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2674 PPCII::MO_PIC_FLAG);
2675 return getTOCEntry(DAG, DL, false, GA);
2679 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2681 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2683 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2685 // If the global reference is actually to a non-lazy-pointer, we have to do an
2686 // extra load to get the address of the global.
2687 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2688 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2692 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2693 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2696 if (Op.getValueType() == MVT::v2i64) {
2697 // When the operands themselves are v2i64 values, we need to do something
2698 // special because VSX has no underlying comparison operations for these.
2699 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2700 // Equality can be handled by casting to the legal type for Altivec
2701 // comparisons, everything else needs to be expanded.
2702 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2703 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2704 DAG.getSetCC(dl, MVT::v4i32,
2705 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2706 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2713 // We handle most of these in the usual way.
2717 // If we're comparing for equality to zero, expose the fact that this is
2718 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2719 // fold the new nodes.
2720 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2723 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2724 // Leave comparisons against 0 and -1 alone for now, since they're usually
2725 // optimized. FIXME: revisit this when we can custom lower all setcc
2727 if (C->isAllOnesValue() || C->isNullValue())
2731 // If we have an integer seteq/setne, turn it into a compare against zero
2732 // by xor'ing the rhs with the lhs, which is faster than setting a
2733 // condition register, reading it back out, and masking the correct bit. The
2734 // normal approach here uses sub to do this instead of xor. Using xor exposes
2735 // the result to other bit-twiddling opportunities.
2736 EVT LHSVT = Op.getOperand(0).getValueType();
2737 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2738 EVT VT = Op.getValueType();
2739 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2741 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2746 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2747 SDNode *Node = Op.getNode();
2748 EVT VT = Node->getValueType(0);
2749 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2750 SDValue InChain = Node->getOperand(0);
2751 SDValue VAListPtr = Node->getOperand(1);
2752 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2755 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2758 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2759 VAListPtr, MachinePointerInfo(SV), MVT::i8);
2760 InChain = GprIndex.getValue(1);
2762 if (VT == MVT::i64) {
2763 // Check if GprIndex is even
2764 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2765 DAG.getConstant(1, dl, MVT::i32));
2766 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2767 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2768 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2769 DAG.getConstant(1, dl, MVT::i32));
2770 // Align GprIndex to be even if it isn't
2771 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2775 // fpr index is 1 byte after gpr
2776 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2777 DAG.getConstant(1, dl, MVT::i32));
2780 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2781 FprPtr, MachinePointerInfo(SV), MVT::i8);
2782 InChain = FprIndex.getValue(1);
2784 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2785 DAG.getConstant(8, dl, MVT::i32));
2787 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2788 DAG.getConstant(4, dl, MVT::i32));
2791 SDValue OverflowArea =
2792 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2793 InChain = OverflowArea.getValue(1);
2795 SDValue RegSaveArea =
2796 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2797 InChain = RegSaveArea.getValue(1);
2799 // select overflow_area if index > 8
2800 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2801 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2803 // adjustment constant gpr_index * 4/8
2804 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2805 VT.isInteger() ? GprIndex : FprIndex,
2806 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2809 // OurReg = RegSaveArea + RegConstant
2810 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2813 // Floating types are 32 bytes into RegSaveArea
2814 if (VT.isFloatingPoint())
2815 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2816 DAG.getConstant(32, dl, MVT::i32));
2818 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2819 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2820 VT.isInteger() ? GprIndex : FprIndex,
2821 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2824 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2825 VT.isInteger() ? VAListPtr : FprPtr,
2826 MachinePointerInfo(SV), MVT::i8);
2828 // determine if we should load from reg_save_area or overflow_area
2829 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2831 // increase overflow_area by 4/8 if gpr/fpr > 8
2832 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2833 DAG.getConstant(VT.isInteger() ? 4 : 8,
2836 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2839 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2840 MachinePointerInfo(), MVT::i32);
2842 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2845 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2846 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2848 // We have to copy the entire va_list struct:
2849 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2850 return DAG.getMemcpy(Op.getOperand(0), Op,
2851 Op.getOperand(1), Op.getOperand(2),
2852 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2853 false, MachinePointerInfo(), MachinePointerInfo());
2856 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2857 SelectionDAG &DAG) const {
2858 return Op.getOperand(0);
2861 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2862 SelectionDAG &DAG) const {
2863 SDValue Chain = Op.getOperand(0);
2864 SDValue Trmp = Op.getOperand(1); // trampoline
2865 SDValue FPtr = Op.getOperand(2); // nested function
2866 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2869 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2870 bool isPPC64 = (PtrVT == MVT::i64);
2871 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2873 TargetLowering::ArgListTy Args;
2874 TargetLowering::ArgListEntry Entry;
2876 Entry.Ty = IntPtrTy;
2877 Entry.Node = Trmp; Args.push_back(Entry);
2879 // TrampSize == (isPPC64 ? 48 : 40);
2880 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2881 isPPC64 ? MVT::i64 : MVT::i32);
2882 Args.push_back(Entry);
2884 Entry.Node = FPtr; Args.push_back(Entry);
2885 Entry.Node = Nest; Args.push_back(Entry);
2887 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2888 TargetLowering::CallLoweringInfo CLI(DAG);
2889 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2890 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2891 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2893 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2894 return CallResult.second;
2897 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2898 MachineFunction &MF = DAG.getMachineFunction();
2899 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2900 EVT PtrVT = getPointerTy(MF.getDataLayout());
2904 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2905 // vastart just stores the address of the VarArgsFrameIndex slot into the
2906 // memory location argument.
2907 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2908 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2909 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2910 MachinePointerInfo(SV));
2913 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2914 // We suppose the given va_list is already allocated.
2917 // char gpr; /* index into the array of 8 GPRs
2918 // * stored in the register save area
2919 // * gpr=0 corresponds to r3,
2920 // * gpr=1 to r4, etc.
2922 // char fpr; /* index into the array of 8 FPRs
2923 // * stored in the register save area
2924 // * fpr=0 corresponds to f1,
2925 // * fpr=1 to f2, etc.
2927 // char *overflow_arg_area;
2928 // /* location on stack that holds
2929 // * the next overflow argument
2931 // char *reg_save_area;
2932 // /* where r3:r10 and f1:f8 (if saved)
2937 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2938 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2939 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2941 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2944 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2945 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2947 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2948 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2950 uint64_t FPROffset = 1;
2951 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2953 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2955 // Store first byte : number of int regs
2956 SDValue firstStore =
2957 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2958 MachinePointerInfo(SV), MVT::i8);
2959 uint64_t nextOffset = FPROffset;
2960 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2963 // Store second byte : number of float regs
2964 SDValue secondStore =
2965 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2966 MachinePointerInfo(SV, nextOffset), MVT::i8);
2967 nextOffset += StackOffset;
2968 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2970 // Store second word : arguments given on stack
2971 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2972 MachinePointerInfo(SV, nextOffset));
2973 nextOffset += FrameOffset;
2974 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2976 // Store third word : arguments given in registers
2977 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2978 MachinePointerInfo(SV, nextOffset));
2981 #include "PPCGenCallingConv.inc"
2983 // Function whose sole purpose is to kill compiler warnings
2984 // stemming from unused functions included from PPCGenCallingConv.inc.
2985 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2986 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2989 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2990 CCValAssign::LocInfo &LocInfo,
2991 ISD::ArgFlagsTy &ArgFlags,
2996 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2998 CCValAssign::LocInfo &LocInfo,
2999 ISD::ArgFlagsTy &ArgFlags,
3001 static const MCPhysReg ArgRegs[] = {
3002 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3003 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3005 const unsigned NumArgRegs = array_lengthof(ArgRegs);
3007 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3009 // Skip one register if the first unallocated register has an even register
3010 // number and there are still argument registers available which have not been
3011 // allocated yet. RegNum is actually an index into ArgRegs, which means we
3012 // need to skip a register if RegNum is odd.
3013 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
3014 State.AllocateReg(ArgRegs[RegNum]);
3017 // Always return false here, as this function only makes sure that the first
3018 // unallocated register has an odd register number and does not actually
3019 // allocate a register for the current argument.
3024 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
3026 CCValAssign::LocInfo &LocInfo,
3027 ISD::ArgFlagsTy &ArgFlags,
3029 static const MCPhysReg ArgRegs[] = {
3030 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3031 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3033 const unsigned NumArgRegs = array_lengthof(ArgRegs);
3035 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3036 int RegsLeft = NumArgRegs - RegNum;
3038 // Skip if there is not enough registers left for long double type (4 gpr regs
3039 // in soft float mode) and put long double argument on the stack.
3040 if (RegNum != NumArgRegs && RegsLeft < 4) {
3041 for (int i = 0; i < RegsLeft; i++) {
3042 State.AllocateReg(ArgRegs[RegNum + i]);
3049 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
3051 CCValAssign::LocInfo &LocInfo,
3052 ISD::ArgFlagsTy &ArgFlags,
3054 static const MCPhysReg ArgRegs[] = {
3055 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3059 const unsigned NumArgRegs = array_lengthof(ArgRegs);
3061 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3063 // If there is only one Floating-point register left we need to put both f64
3064 // values of a split ppc_fp128 value on the stack.
3065 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
3066 State.AllocateReg(ArgRegs[RegNum]);
3069 // Always return false here, as this function only makes sure that the two f64
3070 // values a ppc_fp128 value is split into are both passed in registers or both
3071 // passed on the stack and does not actually allocate a register for the
3072 // current argument.
3076 /// FPR - The set of FP registers that should be allocated for arguments,
3078 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
3079 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
3080 PPC::F11, PPC::F12, PPC::F13};
3082 /// QFPR - The set of QPX registers that should be allocated for arguments.
3083 static const MCPhysReg QFPR[] = {
3084 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
3085 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3087 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3089 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3090 unsigned PtrByteSize) {
3091 unsigned ArgSize = ArgVT.getStoreSize();
3092 if (Flags.isByVal())
3093 ArgSize = Flags.getByValSize();
3095 // Round up to multiples of the pointer size, except for array members,
3096 // which are always packed.
3097 if (!Flags.isInConsecutiveRegs())
3098 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3103 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3105 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3106 ISD::ArgFlagsTy Flags,
3107 unsigned PtrByteSize) {
3108 unsigned Align = PtrByteSize;
3110 // Altivec parameters are padded to a 16 byte boundary.
3111 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3112 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3113 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3114 ArgVT == MVT::v1i128)
3116 // QPX vector types stored in double-precision are padded to a 32 byte
3118 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3121 // ByVal parameters are aligned as requested.
3122 if (Flags.isByVal()) {
3123 unsigned BVAlign = Flags.getByValAlign();
3124 if (BVAlign > PtrByteSize) {
3125 if (BVAlign % PtrByteSize != 0)
3127 "ByVal alignment is not a multiple of the pointer size");
3133 // Array members are always packed to their original alignment.
3134 if (Flags.isInConsecutiveRegs()) {
3135 // If the array member was split into multiple registers, the first
3136 // needs to be aligned to the size of the full type. (Except for
3137 // ppcf128, which is only aligned as its f64 components.)
3138 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3139 Align = OrigVT.getStoreSize();
3141 Align = ArgVT.getStoreSize();
3147 /// CalculateStackSlotUsed - Return whether this argument will use its
3148 /// stack slot (instead of being passed in registers). ArgOffset,
3149 /// AvailableFPRs, and AvailableVRs must hold the current argument
3150 /// position, and will be updated to account for this argument.
3151 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3152 ISD::ArgFlagsTy Flags,
3153 unsigned PtrByteSize,
3154 unsigned LinkageSize,
3155 unsigned ParamAreaSize,
3156 unsigned &ArgOffset,
3157 unsigned &AvailableFPRs,
3158 unsigned &AvailableVRs, bool HasQPX) {
3159 bool UseMemory = false;
3161 // Respect alignment of argument on the stack.
3163 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3164 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3165 // If there's no space left in the argument save area, we must
3166 // use memory (this check also catches zero-sized arguments).
3167 if (ArgOffset >= LinkageSize + ParamAreaSize)
3170 // Allocate argument on the stack.
3171 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3172 if (Flags.isInConsecutiveRegsLast())
3173 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3174 // If we overran the argument save area, we must use memory
3175 // (this check catches arguments passed partially in memory)
3176 if (ArgOffset > LinkageSize + ParamAreaSize)
3179 // However, if the argument is actually passed in an FPR or a VR,
3180 // we don't use memory after all.
3181 if (!Flags.isByVal()) {
3182 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3183 // QPX registers overlap with the scalar FP registers.
3184 (HasQPX && (ArgVT == MVT::v4f32 ||
3185 ArgVT == MVT::v4f64 ||
3186 ArgVT == MVT::v4i1)))
3187 if (AvailableFPRs > 0) {
3191 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3192 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3193 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3194 ArgVT == MVT::v1i128)
3195 if (AvailableVRs > 0) {
3204 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3205 /// ensure minimum alignment required for target.
3206 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3207 unsigned NumBytes) {
3208 unsigned TargetAlign = Lowering->getStackAlignment();
3209 unsigned AlignMask = TargetAlign - 1;
3210 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3214 SDValue PPCTargetLowering::LowerFormalArguments(
3215 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3216 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3217 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3218 if (Subtarget.isSVR4ABI()) {
3219 if (Subtarget.isPPC64())
3220 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3223 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3226 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3231 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3232 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3233 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3234 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3236 // 32-bit SVR4 ABI Stack Frame Layout:
3237 // +-----------------------------------+
3238 // +--> | Back chain |
3239 // | +-----------------------------------+
3240 // | | Floating-point register save area |
3241 // | +-----------------------------------+
3242 // | | General register save area |
3243 // | +-----------------------------------+
3244 // | | CR save word |
3245 // | +-----------------------------------+
3246 // | | VRSAVE save word |
3247 // | +-----------------------------------+
3248 // | | Alignment padding |
3249 // | +-----------------------------------+
3250 // | | Vector register save area |
3251 // | +-----------------------------------+
3252 // | | Local variable space |
3253 // | +-----------------------------------+
3254 // | | Parameter list area |
3255 // | +-----------------------------------+
3256 // | | LR save word |
3257 // | +-----------------------------------+
3258 // SP--> +--- | Back chain |
3259 // +-----------------------------------+
3262 // System V Application Binary Interface PowerPC Processor Supplement
3263 // AltiVec Technology Programming Interface Manual
3265 MachineFunction &MF = DAG.getMachineFunction();
3266 MachineFrameInfo &MFI = MF.getFrameInfo();
3267 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3269 EVT PtrVT = getPointerTy(MF.getDataLayout());
3270 // Potential tail calls could cause overwriting of argument stack slots.
3271 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3272 (CallConv == CallingConv::Fast));
3273 unsigned PtrByteSize = 4;
3275 // Assign locations to all of the incoming arguments.
3276 SmallVector<CCValAssign, 16> ArgLocs;
3277 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3280 // Reserve space for the linkage area on the stack.
3281 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3282 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3284 CCInfo.PreAnalyzeFormalArguments(Ins);
3286 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3287 CCInfo.clearWasPPCF128();
3289 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3290 CCValAssign &VA = ArgLocs[i];
3292 // Arguments stored in registers.
3293 if (VA.isRegLoc()) {
3294 const TargetRegisterClass *RC;
3295 EVT ValVT = VA.getValVT();
3297 switch (ValVT.getSimpleVT().SimpleTy) {
3299 llvm_unreachable("ValVT not supported by formal arguments Lowering");
3302 RC = &PPC::GPRCRegClass;
3305 if (Subtarget.hasP8Vector())
3306 RC = &PPC::VSSRCRegClass;
3308 RC = &PPC::F4RCRegClass;
3311 if (Subtarget.hasVSX())
3312 RC = &PPC::VSFRCRegClass;
3314 RC = &PPC::F8RCRegClass;
3319 RC = &PPC::VRRCRegClass;
3322 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3326 RC = &PPC::VRRCRegClass;
3329 RC = &PPC::QFRCRegClass;
3332 RC = &PPC::QBRCRegClass;
3336 // Transform the arguments stored in physical registers into virtual ones.
3337 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3338 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3339 ValVT == MVT::i1 ? MVT::i32 : ValVT);
3341 if (ValVT == MVT::i1)
3342 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3344 InVals.push_back(ArgValue);
3346 // Argument stored in memory.
3347 assert(VA.isMemLoc());
3349 unsigned ArgSize = VA.getLocVT().getStoreSize();
3350 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3353 // Create load nodes to retrieve arguments from the stack.
3354 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3356 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3360 // Assign locations to all of the incoming aggregate by value arguments.
3361 // Aggregates passed by value are stored in the local variable space of the
3362 // caller's stack frame, right above the parameter list area.
3363 SmallVector<CCValAssign, 16> ByValArgLocs;
3364 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3365 ByValArgLocs, *DAG.getContext());
3367 // Reserve stack space for the allocations in CCInfo.
3368 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3370 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3372 // Area that is at least reserved in the caller of this function.
3373 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3374 MinReservedArea = std::max(MinReservedArea, LinkageSize);
3376 // Set the size that is at least reserved in caller of this function. Tail
3377 // call optimized function's reserved stack space needs to be aligned so that
3378 // taking the difference between two stack areas will result in an aligned
3381 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3382 FuncInfo->setMinReservedArea(MinReservedArea);
3384 SmallVector<SDValue, 8> MemOps;
3386 // If the function takes variable number of arguments, make a frame index for
3387 // the start of the first vararg value... for expansion of llvm.va_start.
3389 static const MCPhysReg GPArgRegs[] = {
3390 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3391 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3393 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3395 static const MCPhysReg FPArgRegs[] = {
3396 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3399 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3404 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3405 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3407 // Make room for NumGPArgRegs and NumFPArgRegs.
3408 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3409 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3411 FuncInfo->setVarArgsStackOffset(
3412 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3413 CCInfo.getNextStackOffset(), true));
3415 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3416 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3418 // The fixed integer arguments of a variadic function are stored to the
3419 // VarArgsFrameIndex on the stack so that they may be loaded by
3420 // dereferencing the result of va_next.
3421 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3422 // Get an existing live-in vreg, or add a new one.
3423 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3425 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3427 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3429 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3430 MemOps.push_back(Store);
3431 // Increment the address by four for the next argument to store
3432 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3433 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3436 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3438 // The double arguments are stored to the VarArgsFrameIndex
3440 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3441 // Get an existing live-in vreg, or add a new one.
3442 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3444 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3446 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3448 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3449 MemOps.push_back(Store);
3450 // Increment the address by eight for the next argument to store
3451 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3453 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3457 if (!MemOps.empty())
3458 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3463 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3464 // value to MVT::i64 and then truncate to the correct register size.
3465 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3466 EVT ObjectVT, SelectionDAG &DAG,
3468 const SDLoc &dl) const {
3470 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3471 DAG.getValueType(ObjectVT));
3472 else if (Flags.isZExt())
3473 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3474 DAG.getValueType(ObjectVT));
3476 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3479 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3480 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3481 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3482 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3483 // TODO: add description of PPC stack frame format, or at least some docs.
3485 bool isELFv2ABI = Subtarget.isELFv2ABI();
3486 bool isLittleEndian = Subtarget.isLittleEndian();
3487 MachineFunction &MF = DAG.getMachineFunction();
3488 MachineFrameInfo &MFI = MF.getFrameInfo();
3489 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3491 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3492 "fastcc not supported on varargs functions");
3494 EVT PtrVT = getPointerTy(MF.getDataLayout());
3495 // Potential tail calls could cause overwriting of argument stack slots.
3496 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3497 (CallConv == CallingConv::Fast));
3498 unsigned PtrByteSize = 8;
3499 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3501 static const MCPhysReg GPR[] = {
3502 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3503 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3505 static const MCPhysReg VR[] = {
3506 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3507 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3510 const unsigned Num_GPR_Regs = array_lengthof(GPR);
3511 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3512 const unsigned Num_VR_Regs = array_lengthof(VR);
3513 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3515 // Do a first pass over the arguments to determine whether the ABI
3516 // guarantees that our caller has allocated the parameter save area
3517 // on its stack frame. In the ELFv1 ABI, this is always the case;
3518 // in the ELFv2 ABI, it is true if this is a vararg function or if
3519 // any parameter is located in a stack slot.
3521 bool HasParameterArea = !isELFv2ABI || isVarArg;
3522 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3523 unsigned NumBytes = LinkageSize;
3524 unsigned AvailableFPRs = Num_FPR_Regs;
3525 unsigned AvailableVRs = Num_VR_Regs;
3526 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3527 if (Ins[i].Flags.isNest())
3530 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3531 PtrByteSize, LinkageSize, ParamAreaSize,
3532 NumBytes, AvailableFPRs, AvailableVRs,
3533 Subtarget.hasQPX()))
3534 HasParameterArea = true;
3537 // Add DAG nodes to load the arguments or copy them out of registers. On
3538 // entry to a function on PPC, the arguments start after the linkage area,
3539 // although the first ones are often in registers.
3541 unsigned ArgOffset = LinkageSize;
3542 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3543 unsigned &QFPR_idx = FPR_idx;
3544 SmallVector<SDValue, 8> MemOps;
3545 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3546 unsigned CurArgIdx = 0;
3547 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3549 bool needsLoad = false;
3550 EVT ObjectVT = Ins[ArgNo].VT;
3551 EVT OrigVT = Ins[ArgNo].ArgVT;
3552 unsigned ObjSize = ObjectVT.getStoreSize();
3553 unsigned ArgSize = ObjSize;
3554 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3555 if (Ins[ArgNo].isOrigArg()) {
3556 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3557 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3559 // We re-align the argument offset for each argument, except when using the
3560 // fast calling convention, when we need to make sure we do that only when
3561 // we'll actually use a stack slot.
3562 unsigned CurArgOffset, Align;
3563 auto ComputeArgOffset = [&]() {
3564 /* Respect alignment of argument on the stack. */
3565 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3566 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3567 CurArgOffset = ArgOffset;
3570 if (CallConv != CallingConv::Fast) {
3573 /* Compute GPR index associated with argument offset. */
3574 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3575 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3578 // FIXME the codegen can be much improved in some cases.
3579 // We do not have to keep everything in memory.
3580 if (Flags.isByVal()) {
3581 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3583 if (CallConv == CallingConv::Fast)
3586 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3587 ObjSize = Flags.getByValSize();
3588 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3589 // Empty aggregate parameters do not take up registers. Examples:
3593 // etc. However, we have to provide a place-holder in InVals, so
3594 // pretend we have an 8-byte item at the current address for that
3597 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3598 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3599 InVals.push_back(FIN);
3603 // Create a stack object covering all stack doublewords occupied
3604 // by the argument. If the argument is (fully or partially) on
3605 // the stack, or if the argument is fully in registers but the
3606 // caller has allocated the parameter save anyway, we can refer
3607 // directly to the caller's stack frame. Otherwise, create a
3608 // local copy in our own frame.
3610 if (HasParameterArea ||
3611 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3612 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3614 FI = MFI.CreateStackObject(ArgSize, Align, false);
3615 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3617 // Handle aggregates smaller than 8 bytes.
3618 if (ObjSize < PtrByteSize) {
3619 // The value of the object is its address, which differs from the
3620 // address of the enclosing doubleword on big-endian systems.
3622 if (!isLittleEndian) {
3623 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3624 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3626 InVals.push_back(Arg);
3628 if (GPR_idx != Num_GPR_Regs) {
3629 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3630 FuncInfo->addLiveInAttr(VReg, Flags);
3631 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3634 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3635 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3636 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3637 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3638 MachinePointerInfo(&*FuncArg), ObjType);
3640 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3641 // store the whole register as-is to the parameter save area
3643 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3644 MachinePointerInfo(&*FuncArg));
3647 MemOps.push_back(Store);
3649 // Whether we copied from a register or not, advance the offset
3650 // into the parameter save area by a full doubleword.
3651 ArgOffset += PtrByteSize;
3655 // The value of the object is its address, which is the address of
3656 // its first stack doubleword.
3657 InVals.push_back(FIN);
3659 // Store whatever pieces of the object are in registers to memory.
3660 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3661 if (GPR_idx == Num_GPR_Regs)
3664 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3665 FuncInfo->addLiveInAttr(VReg, Flags);
3666 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3669 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3670 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3672 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3673 MachinePointerInfo(&*FuncArg, j));
3674 MemOps.push_back(Store);
3677 ArgOffset += ArgSize;
3681 switch (ObjectVT.getSimpleVT().SimpleTy) {
3682 default: llvm_unreachable("Unhandled argument type!");
3686 if (Flags.isNest()) {
3687 // The 'nest' parameter, if any, is passed in R11.
3688 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3689 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3691 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3692 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3697 // These can be scalar arguments or elements of an integer array type
3698 // passed directly. Clang may use those instead of "byval" aggregate
3699 // types to avoid forcing arguments to memory unnecessarily.
3700 if (GPR_idx != Num_GPR_Regs) {
3701 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3702 FuncInfo->addLiveInAttr(VReg, Flags);
3703 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3705 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3706 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3707 // value to MVT::i64 and then truncate to the correct register size.
3708 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3710 if (CallConv == CallingConv::Fast)
3714 ArgSize = PtrByteSize;
3716 if (CallConv != CallingConv::Fast || needsLoad)
3722 // These can be scalar arguments or elements of a float array type
3723 // passed directly. The latter are used to implement ELFv2 homogenous
3724 // float aggregates.
3725 if (FPR_idx != Num_FPR_Regs) {
3728 if (ObjectVT == MVT::f32)
3729 VReg = MF.addLiveIn(FPR[FPR_idx],
3730 Subtarget.hasP8Vector()
3731 ? &PPC::VSSRCRegClass
3732 : &PPC::F4RCRegClass);
3734 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3735 ? &PPC::VSFRCRegClass
3736 : &PPC::F8RCRegClass);
3738 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3740 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3741 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3742 // once we support fp <-> gpr moves.
3744 // This can only ever happen in the presence of f32 array types,
3745 // since otherwise we never run out of FPRs before running out
3747 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3748 FuncInfo->addLiveInAttr(VReg, Flags);
3749 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3751 if (ObjectVT == MVT::f32) {
3752 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3753 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3754 DAG.getConstant(32, dl, MVT::i32));
3755 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3758 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3760 if (CallConv == CallingConv::Fast)
3766 // When passing an array of floats, the array occupies consecutive
3767 // space in the argument area; only round up to the next doubleword
3768 // at the end of the array. Otherwise, each float takes 8 bytes.
3769 if (CallConv != CallingConv::Fast || needsLoad) {
3770 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3771 ArgOffset += ArgSize;
3772 if (Flags.isInConsecutiveRegsLast())
3773 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3783 if (!Subtarget.hasQPX()) {
3784 // These can be scalar arguments or elements of a vector array type
3785 // passed directly. The latter are used to implement ELFv2 homogenous
3786 // vector aggregates.
3787 if (VR_idx != Num_VR_Regs) {
3788 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3789 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3792 if (CallConv == CallingConv::Fast)
3797 if (CallConv != CallingConv::Fast || needsLoad)
3802 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3803 "Invalid QPX parameter type");
3808 // QPX vectors are treated like their scalar floating-point subregisters
3809 // (except that they're larger).
3810 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3811 if (QFPR_idx != Num_QFPR_Regs) {
3812 const TargetRegisterClass *RC;
3813 switch (ObjectVT.getSimpleVT().SimpleTy) {
3814 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3815 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3816 default: RC = &PPC::QBRCRegClass; break;
3819 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3820 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3823 if (CallConv == CallingConv::Fast)
3827 if (CallConv != CallingConv::Fast || needsLoad)
3832 // We need to load the argument to a virtual register if we determined
3833 // above that we ran out of physical registers of the appropriate type.
3835 if (ObjSize < ArgSize && !isLittleEndian)
3836 CurArgOffset += ArgSize - ObjSize;
3837 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3838 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3839 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3842 InVals.push_back(ArgVal);
3845 // Area that is at least reserved in the caller of this function.
3846 unsigned MinReservedArea;
3847 if (HasParameterArea)
3848 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3850 MinReservedArea = LinkageSize;
3852 // Set the size that is at least reserved in caller of this function. Tail
3853 // call optimized functions' reserved stack space needs to be aligned so that
3854 // taking the difference between two stack areas will result in an aligned
3857 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3858 FuncInfo->setMinReservedArea(MinReservedArea);
3860 // If the function takes variable number of arguments, make a frame index for
3861 // the start of the first vararg value... for expansion of llvm.va_start.
3863 int Depth = ArgOffset;
3865 FuncInfo->setVarArgsFrameIndex(
3866 MFI.CreateFixedObject(PtrByteSize, Depth, true));
3867 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3869 // If this function is vararg, store any remaining integer argument regs
3870 // to their spots on the stack so that they may be loaded by dereferencing
3871 // the result of va_next.
3872 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3873 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3874 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3875 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3877 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3878 MemOps.push_back(Store);
3879 // Increment the address by four for the next argument to store
3880 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3881 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3885 if (!MemOps.empty())
3886 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3891 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3892 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3893 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3894 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3895 // TODO: add description of PPC stack frame format, or at least some docs.
3897 MachineFunction &MF = DAG.getMachineFunction();
3898 MachineFrameInfo &MFI = MF.getFrameInfo();
3899 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3901 EVT PtrVT = getPointerTy(MF.getDataLayout());
3902 bool isPPC64 = PtrVT == MVT::i64;
3903 // Potential tail calls could cause overwriting of argument stack slots.
3904 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3905 (CallConv == CallingConv::Fast));
3906 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3907 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3908 unsigned ArgOffset = LinkageSize;
3909 // Area that is at least reserved in caller of this function.
3910 unsigned MinReservedArea = ArgOffset;
3912 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3913 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3914 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3916 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3917 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3918 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3920 static const MCPhysReg VR[] = {
3921 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3922 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3925 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3926 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3927 const unsigned Num_VR_Regs = array_lengthof( VR);
3929 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3931 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3933 // In 32-bit non-varargs functions, the stack space for vectors is after the
3934 // stack space for non-vectors. We do not use this space unless we have
3935 // too many vectors to fit in registers, something that only occurs in
3936 // constructed examples:), but we have to walk the arglist to figure
3937 // that out...for the pathological case, compute VecArgOffset as the
3938 // start of the vector parameter area. Computing VecArgOffset is the
3939 // entire point of the following loop.
3940 unsigned VecArgOffset = ArgOffset;
3941 if (!isVarArg && !isPPC64) {
3942 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3944 EVT ObjectVT = Ins[ArgNo].VT;
3945 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3947 if (Flags.isByVal()) {
3948 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3949 unsigned ObjSize = Flags.getByValSize();
3951 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3952 VecArgOffset += ArgSize;
3956 switch(ObjectVT.getSimpleVT().SimpleTy) {
3957 default: llvm_unreachable("Unhandled argument type!");
3963 case MVT::i64: // PPC64
3965 // FIXME: We are guaranteed to be !isPPC64 at this point.
3966 // Does MVT::i64 apply?
3973 // Nothing to do, we're only looking at Nonvector args here.
3978 // We've found where the vector parameter area in memory is. Skip the
3979 // first 12 parameters; these don't use that memory.
3980 VecArgOffset = ((VecArgOffset+15)/16)*16;
3981 VecArgOffset += 12*16;
3983 // Add DAG nodes to load the arguments or copy them out of registers. On
3984 // entry to a function on PPC, the arguments start after the linkage area,
3985 // although the first ones are often in registers.
3987 SmallVector<SDValue, 8> MemOps;
3988 unsigned nAltivecParamsAtEnd = 0;
3989 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3990 unsigned CurArgIdx = 0;
3991 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3993 bool needsLoad = false;
3994 EVT ObjectVT = Ins[ArgNo].VT;
3995 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3996 unsigned ArgSize = ObjSize;
3997 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3998 if (Ins[ArgNo].isOrigArg()) {
3999 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4000 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4002 unsigned CurArgOffset = ArgOffset;
4004 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4005 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4006 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4007 if (isVarArg || isPPC64) {
4008 MinReservedArea = ((MinReservedArea+15)/16)*16;
4009 MinReservedArea += CalculateStackSlotSize(ObjectVT,
4012 } else nAltivecParamsAtEnd++;
4014 // Calculate min reserved area.
4015 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4019 // FIXME the codegen can be much improved in some cases.
4020 // We do not have to keep everything in memory.
4021 if (Flags.isByVal()) {
4022 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4024 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4025 ObjSize = Flags.getByValSize();
4026 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4027 // Objects of size 1 and 2 are right justified, everything else is
4028 // left justified. This means the memory address is adjusted forwards.
4029 if (ObjSize==1 || ObjSize==2) {
4030 CurArgOffset = CurArgOffset + (4 - ObjSize);
4032 // The value of the object is its address.
4033 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4034 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4035 InVals.push_back(FIN);
4036 if (ObjSize==1 || ObjSize==2) {
4037 if (GPR_idx != Num_GPR_Regs) {
4040 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4042 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4043 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4044 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4046 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4047 MachinePointerInfo(&*FuncArg), ObjType);
4048 MemOps.push_back(Store);
4052 ArgOffset += PtrByteSize;
4056 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4057 // Store whatever pieces of the object are in registers
4058 // to memory. ArgOffset will be the address of the beginning
4060 if (GPR_idx != Num_GPR_Regs) {
4063 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4065 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4066 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4067 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4068 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4069 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4070 MachinePointerInfo(&*FuncArg, j));
4071 MemOps.push_back(Store);
4073 ArgOffset += PtrByteSize;
4075 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4082 switch (ObjectVT.getSimpleVT().SimpleTy) {
4083 default: llvm_unreachable("Unhandled argument type!");
4087 if (GPR_idx != Num_GPR_Regs) {
4088 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4089 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4091 if (ObjectVT == MVT::i1)
4092 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4097 ArgSize = PtrByteSize;
4099 // All int arguments reserve stack space in the Darwin ABI.
4100 ArgOffset += PtrByteSize;
4104 case MVT::i64: // PPC64
4105 if (GPR_idx != Num_GPR_Regs) {
4106 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4107 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4109 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4110 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4111 // value to MVT::i64 and then truncate to the correct register size.
4112 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4117 ArgSize = PtrByteSize;
4119 // All int arguments reserve stack space in the Darwin ABI.
4125 // Every 4 bytes of argument space consumes one of the GPRs available for
4126 // argument passing.
4127 if (GPR_idx != Num_GPR_Regs) {
4129 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4132 if (FPR_idx != Num_FPR_Regs) {
4135 if (ObjectVT == MVT::f32)
4136 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4138 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4140 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4146 // All FP arguments reserve stack space in the Darwin ABI.
4147 ArgOffset += isPPC64 ? 8 : ObjSize;
4153 // Note that vector arguments in registers don't reserve stack space,
4154 // except in varargs functions.
4155 if (VR_idx != Num_VR_Regs) {
4156 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4157 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4159 while ((ArgOffset % 16) != 0) {
4160 ArgOffset += PtrByteSize;
4161 if (GPR_idx != Num_GPR_Regs)
4165 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4169 if (!isVarArg && !isPPC64) {
4170 // Vectors go after all the nonvectors.
4171 CurArgOffset = VecArgOffset;
4174 // Vectors are aligned.
4175 ArgOffset = ((ArgOffset+15)/16)*16;
4176 CurArgOffset = ArgOffset;
4184 // We need to load the argument to a virtual register if we determined above
4185 // that we ran out of physical registers of the appropriate type.
4187 int FI = MFI.CreateFixedObject(ObjSize,
4188 CurArgOffset + (ArgSize - ObjSize),
4190 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4191 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4194 InVals.push_back(ArgVal);
4197 // Allow for Altivec parameters at the end, if needed.
4198 if (nAltivecParamsAtEnd) {
4199 MinReservedArea = ((MinReservedArea+15)/16)*16;
4200 MinReservedArea += 16*nAltivecParamsAtEnd;
4203 // Area that is at least reserved in the caller of this function.
4204 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4206 // Set the size that is at least reserved in caller of this function. Tail
4207 // call optimized functions' reserved stack space needs to be aligned so that
4208 // taking the difference between two stack areas will result in an aligned
4211 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4212 FuncInfo->setMinReservedArea(MinReservedArea);
4214 // If the function takes variable number of arguments, make a frame index for
4215 // the start of the first vararg value... for expansion of llvm.va_start.
4217 int Depth = ArgOffset;
4219 FuncInfo->setVarArgsFrameIndex(
4220 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4222 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4224 // If this function is vararg, store any remaining integer argument regs
4225 // to their spots on the stack so that they may be loaded by dereferencing
4226 // the result of va_next.
4227 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4231 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4233 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4235 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4237 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4238 MemOps.push_back(Store);
4239 // Increment the address by four for the next argument to store
4240 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4241 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4245 if (!MemOps.empty())
4246 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4251 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4252 /// adjusted to accommodate the arguments for the tailcall.
4253 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4254 unsigned ParamSize) {
4256 if (!isTailCall) return 0;
4258 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4259 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4260 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4261 // Remember only if the new adjustement is bigger.
4262 if (SPDiff < FI->getTailCallSPDelta())
4263 FI->setTailCallSPDelta(SPDiff);
4268 static bool isFunctionGlobalAddress(SDValue Callee);
4271 callsShareTOCBase(const Function *Caller, SDValue Callee,
4272 const TargetMachine &TM) {
4273 // If !G, Callee can be an external symbol.
4274 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4278 // The medium and large code models are expected to provide a sufficiently
4279 // large TOC to provide all data addressing needs of a module with a
4280 // single TOC. Since each module will be addressed with a single TOC then we
4281 // only need to check that caller and callee don't cross dso boundaries.
4282 if (CodeModel::Medium == TM.getCodeModel() ||
4283 CodeModel::Large == TM.getCodeModel())
4284 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal());
4286 // Otherwise we need to ensure callee and caller are in the same section,
4287 // since the linker may allocate multiple TOCs, and we don't know which
4288 // sections will belong to the same TOC base.
4290 const GlobalValue *GV = G->getGlobal();
4291 if (!GV->isStrongDefinitionForLinker())
4294 // Any explicitly-specified sections and section prefixes must also match.
4295 // Also, if we're using -ffunction-sections, then each function is always in
4296 // a different section (the same is true for COMDAT functions).
4297 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4298 GV->getSection() != Caller->getSection())
4300 if (const auto *F = dyn_cast<Function>(GV)) {
4301 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4305 // If the callee might be interposed, then we can't assume the ultimate call
4306 // target will be in the same section. Even in cases where we can assume that
4307 // interposition won't happen, in any case where the linker might insert a
4308 // stub to allow for interposition, we must generate code as though
4309 // interposition might occur. To understand why this matters, consider a
4310 // situation where: a -> b -> c where the arrows indicate calls. b and c are
4311 // in the same section, but a is in a different module (i.e. has a different
4312 // TOC base pointer). If the linker allows for interposition between b and c,
4313 // then it will generate a stub for the call edge between b and c which will
4314 // save the TOC pointer into the designated stack slot allocated by b. If we
4315 // return true here, and therefore allow a tail call between b and c, that
4316 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4317 // pointer into the stack slot allocated by a (where the a -> b stub saved
4318 // a's TOC base pointer). If we're not considering a tail call, but rather,
4319 // whether a nop is needed after the call instruction in b, because the linker
4320 // will insert a stub, it might complain about a missing nop if we omit it
4321 // (although many don't complain in this case).
4322 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4329 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4330 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4331 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4333 const unsigned PtrByteSize = 8;
4334 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4336 static const MCPhysReg GPR[] = {
4337 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4338 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4340 static const MCPhysReg VR[] = {
4341 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4342 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4345 const unsigned NumGPRs = array_lengthof(GPR);
4346 const unsigned NumFPRs = 13;
4347 const unsigned NumVRs = array_lengthof(VR);
4348 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4350 unsigned NumBytes = LinkageSize;
4351 unsigned AvailableFPRs = NumFPRs;
4352 unsigned AvailableVRs = NumVRs;
4354 for (const ISD::OutputArg& Param : Outs) {
4355 if (Param.Flags.isNest()) continue;
4357 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4358 PtrByteSize, LinkageSize, ParamAreaSize,
4359 NumBytes, AvailableFPRs, AvailableVRs,
4360 Subtarget.hasQPX()))
4367 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4368 if (CS.arg_size() != CallerFn->arg_size())
4371 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4372 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4373 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4375 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4376 const Value* CalleeArg = *CalleeArgIter;
4377 const Value* CallerArg = &(*CallerArgIter);
4378 if (CalleeArg == CallerArg)
4381 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4382 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4384 // 1st argument of callee is undef and has the same type as caller.
4385 if (CalleeArg->getType() == CallerArg->getType() &&
4386 isa<UndefValue>(CalleeArg))
4395 // Returns true if TCO is possible between the callers and callees
4396 // calling conventions.
4398 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4399 CallingConv::ID CalleeCC) {
4400 // Tail calls are possible with fastcc and ccc.
4401 auto isTailCallableCC = [] (CallingConv::ID CC){
4402 return CC == CallingConv::C || CC == CallingConv::Fast;
4404 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4407 // We can safely tail call both fastcc and ccc callees from a c calling
4408 // convention caller. If the caller is fastcc, we may have less stack space
4409 // than a non-fastcc caller with the same signature so disable tail-calls in
4411 return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4415 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4417 CallingConv::ID CalleeCC,
4418 ImmutableCallSite CS,
4420 const SmallVectorImpl<ISD::OutputArg> &Outs,
4421 const SmallVectorImpl<ISD::InputArg> &Ins,
4422 SelectionDAG& DAG) const {
4423 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4425 if (DisableSCO && !TailCallOpt) return false;
4427 // Variadic argument functions are not supported.
4428 if (isVarArg) return false;
4430 auto &Caller = DAG.getMachineFunction().getFunction();
4431 // Check that the calling conventions are compatible for tco.
4432 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4435 // Caller contains any byval parameter is not supported.
4436 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4439 // Callee contains any byval parameter is not supported, too.
4440 // Note: This is a quick work around, because in some cases, e.g.
4441 // caller's stack size > callee's stack size, we are still able to apply
4442 // sibling call optimization. For example, gcc is able to do SCO for caller1
4443 // in the following example, but not for caller2.
4448 // __attribute__((noinline)) int callee(struct test v, struct test *b) {
4452 // void caller1(struct test a, struct test c, struct test *b) {
4453 // callee(gTest, b); }
4454 // void caller2(struct test *b) { callee(gTest, b); }
4455 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4458 // If callee and caller use different calling conventions, we cannot pass
4459 // parameters on stack since offsets for the parameter area may be different.
4460 if (Caller.getCallingConv() != CalleeCC &&
4461 needStackSlotPassParameters(Subtarget, Outs))
4464 // No TCO/SCO on indirect call because Caller have to restore its TOC
4465 if (!isFunctionGlobalAddress(Callee) &&
4466 !isa<ExternalSymbolSDNode>(Callee))
4469 // If the caller and callee potentially have different TOC bases then we
4470 // cannot tail call since we need to restore the TOC pointer after the call.
4471 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4472 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4475 // TCO allows altering callee ABI, so we don't have to check further.
4476 if (CalleeCC == CallingConv::Fast && TailCallOpt)
4479 if (DisableSCO) return false;
4481 // If callee use the same argument list that caller is using, then we can
4482 // apply SCO on this case. If it is not, then we need to check if callee needs
4483 // stack for passing arguments.
4484 if (!hasSameArgumentList(&Caller, CS) &&
4485 needStackSlotPassParameters(Subtarget, Outs)) {
4492 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4493 /// for tail call optimization. Targets which want to do tail call
4494 /// optimization should implement this function.
4496 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4497 CallingConv::ID CalleeCC,
4499 const SmallVectorImpl<ISD::InputArg> &Ins,
4500 SelectionDAG& DAG) const {
4501 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4504 // Variable argument functions are not supported.
4508 MachineFunction &MF = DAG.getMachineFunction();
4509 CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4510 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4511 // Functions containing by val parameters are not supported.
4512 for (unsigned i = 0; i != Ins.size(); i++) {
4513 ISD::ArgFlagsTy Flags = Ins[i].Flags;
4514 if (Flags.isByVal()) return false;
4517 // Non-PIC/GOT tail calls are supported.
4518 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4521 // At the moment we can only do local tail calls (in same module, hidden
4522 // or protected) if we are generating PIC.
4523 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4524 return G->getGlobal()->hasHiddenVisibility()
4525 || G->getGlobal()->hasProtectedVisibility();
4531 /// isCallCompatibleAddress - Return the immediate to use if the specified
4532 /// 32-bit value is representable in the immediate field of a BxA instruction.
4533 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4534 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4535 if (!C) return nullptr;
4537 int Addr = C->getZExtValue();
4538 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
4539 SignExtend32<26>(Addr) != Addr)
4540 return nullptr; // Top 6 bits have to be sext of immediate.
4544 (int)C->getZExtValue() >> 2, SDLoc(Op),
4545 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4551 struct TailCallArgumentInfo {
4556 TailCallArgumentInfo() = default;
4559 } // end anonymous namespace
4561 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4562 static void StoreTailCallArgumentsToStackSlot(
4563 SelectionDAG &DAG, SDValue Chain,
4564 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4565 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4566 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4567 SDValue Arg = TailCallArgs[i].Arg;
4568 SDValue FIN = TailCallArgs[i].FrameIdxOp;
4569 int FI = TailCallArgs[i].FrameIdx;
4570 // Store relative to framepointer.
4571 MemOpChains.push_back(DAG.getStore(
4572 Chain, dl, Arg, FIN,
4573 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4577 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4578 /// the appropriate stack slot for the tail call optimized function call.
4579 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4580 SDValue OldRetAddr, SDValue OldFP,
4581 int SPDiff, const SDLoc &dl) {
4583 // Calculate the new stack slot for the return address.
4584 MachineFunction &MF = DAG.getMachineFunction();
4585 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4586 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4587 bool isPPC64 = Subtarget.isPPC64();
4588 int SlotSize = isPPC64 ? 8 : 4;
4589 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4590 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4591 NewRetAddrLoc, true);
4592 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4593 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4594 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4595 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4597 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4598 // slot as the FP is never overwritten.
4599 if (Subtarget.isDarwinABI()) {
4600 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4601 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4603 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4604 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4605 MachinePointerInfo::getFixedStack(
4606 DAG.getMachineFunction(), NewFPIdx));
4612 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4613 /// the position of the argument.
4615 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4616 SDValue Arg, int SPDiff, unsigned ArgOffset,
4617 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4618 int Offset = ArgOffset + SPDiff;
4619 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4620 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4621 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4622 SDValue FIN = DAG.getFrameIndex(FI, VT);
4623 TailCallArgumentInfo Info;
4625 Info.FrameIdxOp = FIN;
4627 TailCallArguments.push_back(Info);
4630 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4631 /// stack slot. Returns the chain as result and the loaded frame pointers in
4632 /// LROpOut/FPOpout. Used when tail calling.
4633 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4634 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4635 SDValue &FPOpOut, const SDLoc &dl) const {
4637 // Load the LR and FP stack slot for later adjusting.
4638 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4639 LROpOut = getReturnAddrFrameIndex(DAG);
4640 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4641 Chain = SDValue(LROpOut.getNode(), 1);
4643 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4644 // slot as the FP is never overwritten.
4645 if (Subtarget.isDarwinABI()) {
4646 FPOpOut = getFramePointerFrameIndex(DAG);
4647 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4648 Chain = SDValue(FPOpOut.getNode(), 1);
4654 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4655 /// by "Src" to address "Dst" of size "Size". Alignment information is
4656 /// specified by the specific parameter attribute. The copy will be passed as
4657 /// a byval function parameter.
4658 /// Sometimes what we are copying is the end of a larger object, the part that
4659 /// does not fit in registers.
4660 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4661 SDValue Chain, ISD::ArgFlagsTy Flags,
4662 SelectionDAG &DAG, const SDLoc &dl) {
4663 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4664 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4665 false, false, false, MachinePointerInfo(),
4666 MachinePointerInfo());
4669 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4671 static void LowerMemOpCallTo(
4672 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4673 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4674 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4675 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4676 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4681 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4683 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4684 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4685 DAG.getConstant(ArgOffset, dl, PtrVT));
4687 MemOpChains.push_back(
4688 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4689 // Calculate and remember argument location.
4690 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4695 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4696 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4698 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4699 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4700 // might overwrite each other in case of tail call optimization.
4701 SmallVector<SDValue, 8> MemOpChains2;
4702 // Do not flag preceding copytoreg stuff together with the following stuff.
4704 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4706 if (!MemOpChains2.empty())
4707 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4709 // Store the return address to the appropriate stack slot.
4710 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4712 // Emit callseq_end just before tailcall node.
4713 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4714 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4715 InFlag = Chain.getValue(1);
4718 // Is this global address that of a function that can be called by name? (as
4719 // opposed to something that must hold a descriptor for an indirect call).
4720 static bool isFunctionGlobalAddress(SDValue Callee) {
4721 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4722 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4723 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4726 return G->getGlobal()->getValueType()->isFunctionTy();
4733 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4734 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4735 bool isPatchPoint, bool hasNest,
4736 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4737 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4738 ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4739 bool isPPC64 = Subtarget.isPPC64();
4740 bool isSVR4ABI = Subtarget.isSVR4ABI();
4741 bool isELFv2ABI = Subtarget.isELFv2ABI();
4743 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4744 NodeTys.push_back(MVT::Other); // Returns a chain
4745 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
4747 unsigned CallOpc = PPCISD::CALL;
4749 bool needIndirectCall = true;
4750 if (!isSVR4ABI || !isPPC64)
4751 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4752 // If this is an absolute destination address, use the munged value.
4753 Callee = SDValue(Dest, 0);
4754 needIndirectCall = false;
4757 // PC-relative references to external symbols should go through $stub, unless
4758 // we're building with the leopard linker or later, which automatically
4759 // synthesizes these stubs.
4760 const TargetMachine &TM = DAG.getTarget();
4761 const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
4762 const GlobalValue *GV = nullptr;
4763 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4764 GV = G->getGlobal();
4765 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4766 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4768 if (isFunctionGlobalAddress(Callee)) {
4769 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4770 // A call to a TLS address is actually an indirect call to a
4771 // thread-specific pointer.
4772 unsigned OpFlags = 0;
4774 OpFlags = PPCII::MO_PLT;
4776 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4777 // every direct call is) turn it into a TargetGlobalAddress /
4778 // TargetExternalSymbol node so that legalize doesn't hack it.
4779 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4780 Callee.getValueType(), 0, OpFlags);
4781 needIndirectCall = false;
4784 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4785 unsigned char OpFlags = 0;
4788 OpFlags = PPCII::MO_PLT;
4790 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4792 needIndirectCall = false;
4796 // We'll form an invalid direct call when lowering a patchpoint; the full
4797 // sequence for an indirect call is complicated, and many of the
4798 // instructions introduced might have side effects (and, thus, can't be
4799 // removed later). The call itself will be removed as soon as the
4800 // argument/return lowering is complete, so the fact that it has the wrong
4801 // kind of operands should not really matter.
4802 needIndirectCall = false;
4805 if (needIndirectCall) {
4806 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
4807 // to do the call, we can't use PPCISD::CALL.
4808 SDValue MTCTROps[] = {Chain, Callee, InFlag};
4810 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4811 // Function pointers in the 64-bit SVR4 ABI do not point to the function
4812 // entry point, but to the function descriptor (the function entry point
4813 // address is part of the function descriptor though).
4814 // The function descriptor is a three doubleword structure with the
4815 // following fields: function entry point, TOC base address and
4816 // environment pointer.
4817 // Thus for a call through a function pointer, the following actions need
4819 // 1. Save the TOC of the caller in the TOC save area of its stack
4820 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4821 // 2. Load the address of the function entry point from the function
4823 // 3. Load the TOC of the callee from the function descriptor into r2.
4824 // 4. Load the environment pointer from the function descriptor into
4826 // 5. Branch to the function entry point address.
4827 // 6. On return of the callee, the TOC of the caller needs to be
4828 // restored (this is done in FinishCall()).
4830 // The loads are scheduled at the beginning of the call sequence, and the
4831 // register copies are flagged together to ensure that no other
4832 // operations can be scheduled in between. E.g. without flagging the
4833 // copies together, a TOC access in the caller could be scheduled between
4834 // the assignment of the callee TOC and the branch to the callee, which
4835 // results in the TOC access going through the TOC of the callee instead
4836 // of going through the TOC of the caller, which leads to incorrect code.
4838 // Load the address of the function entry point from the function
4840 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4841 if (LDChain.getValueType() == MVT::Glue)
4842 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4844 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4845 ? (MachineMemOperand::MODereferenceable |
4846 MachineMemOperand::MOInvariant)
4847 : MachineMemOperand::MONone;
4849 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
4850 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4851 /* Alignment = */ 8, MMOFlags);
4853 // Load environment pointer into r11.
4854 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4855 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4856 SDValue LoadEnvPtr =
4857 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4858 /* Alignment = */ 8, MMOFlags);
4860 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4861 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4863 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4864 /* Alignment = */ 8, MMOFlags);
4866 setUsesTOCBasePtr(DAG);
4867 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4869 Chain = TOCVal.getValue(0);
4870 InFlag = TOCVal.getValue(1);
4872 // If the function call has an explicit 'nest' parameter, it takes the
4873 // place of the environment pointer.
4875 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4878 Chain = EnvVal.getValue(0);
4879 InFlag = EnvVal.getValue(1);
4882 MTCTROps[0] = Chain;
4883 MTCTROps[1] = LoadFuncPtr;
4884 MTCTROps[2] = InFlag;
4887 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4888 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4889 InFlag = Chain.getValue(1);
4892 NodeTys.push_back(MVT::Other);
4893 NodeTys.push_back(MVT::Glue);
4894 Ops.push_back(Chain);
4895 CallOpc = PPCISD::BCTRL;
4896 Callee.setNode(nullptr);
4897 // Add use of X11 (holding environment pointer)
4898 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4899 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4900 // Add CTR register as callee so a bctr can be emitted later.
4902 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4905 // If this is a direct call, pass the chain and the callee.
4906 if (Callee.getNode()) {
4907 Ops.push_back(Chain);
4908 Ops.push_back(Callee);
4910 // If this is a tail call add stack pointer delta.
4912 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4914 // Add argument registers to the end of the list so that they are known live
4916 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4917 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4918 RegsToPass[i].second.getValueType()));
4920 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4922 if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4923 setUsesTOCBasePtr(DAG);
4924 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4930 SDValue PPCTargetLowering::LowerCallResult(
4931 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4932 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4933 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4934 SmallVector<CCValAssign, 16> RVLocs;
4935 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4937 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4939 // Copy all of the result registers out of their specified physreg.
4940 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4941 CCValAssign &VA = RVLocs[i];
4942 assert(VA.isRegLoc() && "Can only return in registers!");
4944 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4945 VA.getLocReg(), VA.getLocVT(), InFlag);
4946 Chain = Val.getValue(1);
4947 InFlag = Val.getValue(2);
4949 switch (VA.getLocInfo()) {
4950 default: llvm_unreachable("Unknown loc info!");
4951 case CCValAssign::Full: break;
4952 case CCValAssign::AExt:
4953 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4955 case CCValAssign::ZExt:
4956 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4957 DAG.getValueType(VA.getValVT()));
4958 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4960 case CCValAssign::SExt:
4961 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4962 DAG.getValueType(VA.getValVT()));
4963 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4967 InVals.push_back(Val);
4973 SDValue PPCTargetLowering::FinishCall(
4974 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4975 bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4976 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4977 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4978 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4979 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
4980 std::vector<EVT> NodeTys;
4981 SmallVector<SDValue, 8> Ops;
4982 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4983 SPDiff, isTailCall, isPatchPoint, hasNest,
4984 RegsToPass, Ops, NodeTys, CS, Subtarget);
4986 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4987 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4988 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4990 // When performing tail call optimization the callee pops its arguments off
4991 // the stack. Account for this here so these bytes can be pushed back on in
4992 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4993 int BytesCalleePops =
4994 (CallConv == CallingConv::Fast &&
4995 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4997 // Add a register mask operand representing the call-preserved registers.
4998 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4999 const uint32_t *Mask =
5000 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5001 assert(Mask && "Missing call preserved mask for calling convention");
5002 Ops.push_back(DAG.getRegisterMask(Mask));
5004 if (InFlag.getNode())
5005 Ops.push_back(InFlag);
5009 assert(((Callee.getOpcode() == ISD::Register &&
5010 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5011 Callee.getOpcode() == ISD::TargetExternalSymbol ||
5012 Callee.getOpcode() == ISD::TargetGlobalAddress ||
5013 isa<ConstantSDNode>(Callee)) &&
5014 "Expecting an global address, external symbol, absolute value or register");
5016 DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5017 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5020 // Add a NOP immediately after the branch instruction when using the 64-bit
5021 // SVR4 ABI. At link time, if caller and callee are in a different module and
5022 // thus have a different TOC, the call will be replaced with a call to a stub
5023 // function which saves the current TOC, loads the TOC of the callee and
5024 // branches to the callee. The NOP will be replaced with a load instruction
5025 // which restores the TOC of the caller from the TOC save slot of the current
5026 // stack frame. If caller and callee belong to the same module (and have the
5027 // same TOC), the NOP will remain unchanged.
5029 MachineFunction &MF = DAG.getMachineFunction();
5030 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
5032 if (CallOpc == PPCISD::BCTRL) {
5033 // This is a call through a function pointer.
5034 // Restore the caller TOC from the save area into R2.
5035 // See PrepareCall() for more information about calls through function
5036 // pointers in the 64-bit SVR4 ABI.
5037 // We are using a target-specific load with r2 hard coded, because the
5038 // result of a target-independent load would never go directly into r2,
5039 // since r2 is a reserved register (which prevents the register allocator
5040 // from allocating it), resulting in an additional register being
5041 // allocated and an unnecessary move instruction being generated.
5042 CallOpc = PPCISD::BCTRL_LOAD_TOC;
5044 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5045 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5046 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5047 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5048 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5050 // The address needs to go after the chain input but before the flag (or
5051 // any other variadic arguments).
5052 Ops.insert(std::next(Ops.begin()), AddTOC);
5053 } else if (CallOpc == PPCISD::CALL &&
5054 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5055 // Otherwise insert NOP for non-local calls.
5056 CallOpc = PPCISD::CALL_NOP;
5060 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5061 InFlag = Chain.getValue(1);
5063 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5064 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5067 InFlag = Chain.getValue(1);
5069 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5070 Ins, dl, DAG, InVals);
5074 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5075 SmallVectorImpl<SDValue> &InVals) const {
5076 SelectionDAG &DAG = CLI.DAG;
5078 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5079 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5080 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
5081 SDValue Chain = CLI.Chain;
5082 SDValue Callee = CLI.Callee;
5083 bool &isTailCall = CLI.IsTailCall;
5084 CallingConv::ID CallConv = CLI.CallConv;
5085 bool isVarArg = CLI.IsVarArg;
5086 bool isPatchPoint = CLI.IsPatchPoint;
5087 ImmutableCallSite CS = CLI.CS;
5090 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5092 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5094 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5095 isVarArg, Outs, Ins, DAG);
5097 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5101 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5104 assert(isa<GlobalAddressSDNode>(Callee) &&
5105 "Callee should be an llvm::Function object.");
5107 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5108 const unsigned Width = 80 - strlen("TCO caller: ")
5109 - strlen(", callee linkage: 0, 0");
5110 dbgs() << "TCO caller: "
5111 << left_justify(DAG.getMachineFunction().getName(), Width)
5112 << ", callee linkage: "
5113 << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
5118 if (!isTailCall && CS && CS.isMustTailCall())
5119 report_fatal_error("failed to perform tail call elimination on a call "
5120 "site marked musttail");
5122 // When long calls (i.e. indirect calls) are always used, calls are always
5123 // made via function pointer. If we have a function name, first translate it
5125 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5127 Callee = LowerGlobalAddress(Callee, DAG);
5129 if (Subtarget.isSVR4ABI()) {
5130 if (Subtarget.isPPC64())
5131 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5132 isTailCall, isPatchPoint, Outs, OutVals, Ins,
5133 dl, DAG, InVals, CS);
5135 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5136 isTailCall, isPatchPoint, Outs, OutVals, Ins,
5137 dl, DAG, InVals, CS);
5140 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5141 isTailCall, isPatchPoint, Outs, OutVals, Ins,
5142 dl, DAG, InVals, CS);
5145 SDValue PPCTargetLowering::LowerCall_32SVR4(
5146 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5147 bool isTailCall, bool isPatchPoint,
5148 const SmallVectorImpl<ISD::OutputArg> &Outs,
5149 const SmallVectorImpl<SDValue> &OutVals,
5150 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5151 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5152 ImmutableCallSite CS) const {
5153 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5154 // of the 32-bit SVR4 ABI stack frame layout.
5156 assert((CallConv == CallingConv::C ||
5157 CallConv == CallingConv::Fast) && "Unknown calling convention!");
5159 unsigned PtrByteSize = 4;
5161 MachineFunction &MF = DAG.getMachineFunction();
5163 // Mark this function as potentially containing a function that contains a
5164 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5165 // and restoring the callers stack pointer in this functions epilog. This is
5166 // done because by tail calling the called function might overwrite the value
5167 // in this function's (MF) stack pointer stack slot 0(SP).
5168 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5169 CallConv == CallingConv::Fast)
5170 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5172 // Count how many bytes are to be pushed on the stack, including the linkage
5173 // area, parameter list area and the part of the local variable space which
5174 // contains copies of aggregates which are passed by value.
5176 // Assign locations to all of the outgoing arguments.
5177 SmallVector<CCValAssign, 16> ArgLocs;
5178 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5180 // Reserve space for the linkage area on the stack.
5181 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5184 CCInfo.PreAnalyzeCallOperands(Outs);
5187 // Handle fixed and variable vector arguments differently.
5188 // Fixed vector arguments go into registers as long as registers are
5189 // available. Variable vector arguments always go into memory.
5190 unsigned NumArgs = Outs.size();
5192 for (unsigned i = 0; i != NumArgs; ++i) {
5193 MVT ArgVT = Outs[i].VT;
5194 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5197 if (Outs[i].IsFixed) {
5198 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5201 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5207 errs() << "Call operand #" << i << " has unhandled type "
5208 << EVT(ArgVT).getEVTString() << "\n";
5210 llvm_unreachable(nullptr);
5214 // All arguments are treated the same.
5215 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5217 CCInfo.clearWasPPCF128();
5219 // Assign locations to all of the outgoing aggregate by value arguments.
5220 SmallVector<CCValAssign, 16> ByValArgLocs;
5221 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5223 // Reserve stack space for the allocations in CCInfo.
5224 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5226 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5228 // Size of the linkage area, parameter list area and the part of the local
5229 // space variable where copies of aggregates which are passed by value are
5231 unsigned NumBytes = CCByValInfo.getNextStackOffset();
5233 // Calculate by how many bytes the stack has to be adjusted in case of tail
5234 // call optimization.
5235 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5237 // Adjust the stack pointer for the new arguments...
5238 // These operations are automatically eliminated by the prolog/epilog pass
5239 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5240 SDValue CallSeqStart = Chain;
5242 // Load the return address and frame pointer so it can be moved somewhere else
5245 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5247 // Set up a copy of the stack pointer for use loading and storing any
5248 // arguments that may not fit in the registers available for argument
5250 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5252 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5253 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5254 SmallVector<SDValue, 8> MemOpChains;
5256 bool seenFloatArg = false;
5257 // Walk the register/memloc assignments, inserting copies/loads.
5258 for (unsigned i = 0, j = 0, e = ArgLocs.size();
5261 CCValAssign &VA = ArgLocs[i];
5262 SDValue Arg = OutVals[i];
5263 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5265 if (Flags.isByVal()) {
5266 // Argument is an aggregate which is passed by value, thus we need to
5267 // create a copy of it in the local variable space of the current stack
5268 // frame (which is the stack frame of the caller) and pass the address of
5269 // this copy to the callee.
5270 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5271 CCValAssign &ByValVA = ByValArgLocs[j++];
5272 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5274 // Memory reserved in the local variable space of the callers stack frame.
5275 unsigned LocMemOffset = ByValVA.getLocMemOffset();
5277 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5278 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5281 // Create a copy of the argument in the local area of the current
5283 SDValue MemcpyCall =
5284 CreateCopyOfByValArgument(Arg, PtrOff,
5285 CallSeqStart.getNode()->getOperand(0),
5288 // This must go outside the CALLSEQ_START..END.
5289 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5291 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5292 NewCallSeqStart.getNode());
5293 Chain = CallSeqStart = NewCallSeqStart;
5295 // Pass the address of the aggregate copy on the stack either in a
5296 // physical register or in the parameter list area of the current stack
5297 // frame to the callee.
5301 if (VA.isRegLoc()) {
5302 if (Arg.getValueType() == MVT::i1)
5303 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5305 seenFloatArg |= VA.getLocVT().isFloatingPoint();
5306 // Put argument in a physical register.
5307 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5309 // Put argument in the parameter list area of the current stack frame.
5310 assert(VA.isMemLoc());
5311 unsigned LocMemOffset = VA.getLocMemOffset();
5314 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5315 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5318 MemOpChains.push_back(
5319 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5321 // Calculate and remember argument location.
5322 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5328 if (!MemOpChains.empty())
5329 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5331 // Build a sequence of copy-to-reg nodes chained together with token chain
5332 // and flag operands which copy the outgoing args into the appropriate regs.
5334 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5335 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5336 RegsToPass[i].second, InFlag);
5337 InFlag = Chain.getValue(1);
5340 // Set CR bit 6 to true if this is a vararg call with floating args passed in
5343 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5344 SDValue Ops[] = { Chain, InFlag };
5346 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5347 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5349 InFlag = Chain.getValue(1);
5353 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5356 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5357 /* unused except on PPC64 ELFv1 */ false, DAG,
5358 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5359 NumBytes, Ins, InVals, CS);
5362 // Copy an argument into memory, being careful to do this outside the
5363 // call sequence for the call to which the argument belongs.
5364 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5365 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5366 SelectionDAG &DAG, const SDLoc &dl) const {
5367 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5368 CallSeqStart.getNode()->getOperand(0),
5370 // The MEMCPY must go outside the CALLSEQ_START..END.
5371 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5372 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5374 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5375 NewCallSeqStart.getNode());
5376 return NewCallSeqStart;
5379 SDValue PPCTargetLowering::LowerCall_64SVR4(
5380 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5381 bool isTailCall, bool isPatchPoint,
5382 const SmallVectorImpl<ISD::OutputArg> &Outs,
5383 const SmallVectorImpl<SDValue> &OutVals,
5384 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5385 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5386 ImmutableCallSite CS) const {
5387 bool isELFv2ABI = Subtarget.isELFv2ABI();
5388 bool isLittleEndian = Subtarget.isLittleEndian();
5389 unsigned NumOps = Outs.size();
5390 bool hasNest = false;
5391 bool IsSibCall = false;
5393 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5394 unsigned PtrByteSize = 8;
5396 MachineFunction &MF = DAG.getMachineFunction();
5398 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5401 // Mark this function as potentially containing a function that contains a
5402 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5403 // and restoring the callers stack pointer in this functions epilog. This is
5404 // done because by tail calling the called function might overwrite the value
5405 // in this function's (MF) stack pointer stack slot 0(SP).
5406 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5407 CallConv == CallingConv::Fast)
5408 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5410 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5411 "fastcc not supported on varargs functions");
5413 // Count how many bytes are to be pushed on the stack, including the linkage
5414 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
5415 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5416 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5417 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5418 unsigned NumBytes = LinkageSize;
5419 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5420 unsigned &QFPR_idx = FPR_idx;
5422 static const MCPhysReg GPR[] = {
5423 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5424 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5426 static const MCPhysReg VR[] = {
5427 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5428 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5431 const unsigned NumGPRs = array_lengthof(GPR);
5432 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5433 const unsigned NumVRs = array_lengthof(VR);
5434 const unsigned NumQFPRs = NumFPRs;
5436 // On ELFv2, we can avoid allocating the parameter area if all the arguments
5437 // can be passed to the callee in registers.
5438 // For the fast calling convention, there is another check below.
5439 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5440 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5441 if (!HasParameterArea) {
5442 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5443 unsigned AvailableFPRs = NumFPRs;
5444 unsigned AvailableVRs = NumVRs;
5445 unsigned NumBytesTmp = NumBytes;
5446 for (unsigned i = 0; i != NumOps; ++i) {
5447 if (Outs[i].Flags.isNest()) continue;
5448 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5449 PtrByteSize, LinkageSize, ParamAreaSize,
5450 NumBytesTmp, AvailableFPRs, AvailableVRs,
5451 Subtarget.hasQPX()))
5452 HasParameterArea = true;
5456 // When using the fast calling convention, we don't provide backing for
5457 // arguments that will be in registers.
5458 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5460 // Add up all the space actually used.
5461 for (unsigned i = 0; i != NumOps; ++i) {
5462 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5463 EVT ArgVT = Outs[i].VT;
5464 EVT OrigVT = Outs[i].ArgVT;
5469 if (CallConv == CallingConv::Fast) {
5470 if (Flags.isByVal())
5471 NumGPRsUsed += (Flags.getByValSize()+7)/8;
5473 switch (ArgVT.getSimpleVT().SimpleTy) {
5474 default: llvm_unreachable("Unexpected ValueType for argument!");
5478 if (++NumGPRsUsed <= NumGPRs)
5487 if (++NumVRsUsed <= NumVRs)
5491 // When using QPX, this is handled like a FP register, otherwise, it
5492 // is an Altivec register.
5493 if (Subtarget.hasQPX()) {
5494 if (++NumFPRsUsed <= NumFPRs)
5497 if (++NumVRsUsed <= NumVRs)
5503 case MVT::v4f64: // QPX
5504 case MVT::v4i1: // QPX
5505 if (++NumFPRsUsed <= NumFPRs)
5511 /* Respect alignment of argument on the stack. */
5513 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5514 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5516 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5517 if (Flags.isInConsecutiveRegsLast())
5518 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5521 unsigned NumBytesActuallyUsed = NumBytes;
5523 // In the old ELFv1 ABI,
5524 // the prolog code of the callee may store up to 8 GPR argument registers to
5525 // the stack, allowing va_start to index over them in memory if its varargs.
5526 // Because we cannot tell if this is needed on the caller side, we have to
5527 // conservatively assume that it is needed. As such, make sure we have at
5528 // least enough stack space for the caller to store the 8 GPRs.
5529 // In the ELFv2 ABI, we allocate the parameter area iff a callee
5530 // really requires memory operands, e.g. a vararg function.
5531 if (HasParameterArea)
5532 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5534 NumBytes = LinkageSize;
5536 // Tail call needs the stack to be aligned.
5537 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5538 CallConv == CallingConv::Fast)
5539 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5543 // Calculate by how many bytes the stack has to be adjusted in case of tail
5544 // call optimization.
5546 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5548 // To protect arguments on the stack from being clobbered in a tail call,
5549 // force all the loads to happen before doing any other lowering.
5551 Chain = DAG.getStackArgumentTokenFactor(Chain);
5553 // Adjust the stack pointer for the new arguments...
5554 // These operations are automatically eliminated by the prolog/epilog pass
5556 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5557 SDValue CallSeqStart = Chain;
5559 // Load the return address and frame pointer so it can be move somewhere else
5562 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5564 // Set up a copy of the stack pointer for use loading and storing any
5565 // arguments that may not fit in the registers available for argument
5567 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5569 // Figure out which arguments are going to go in registers, and which in
5570 // memory. Also, if this is a vararg function, floating point operations
5571 // must be stored to our stack, and loaded into integer regs as well, if
5572 // any integer regs are available for argument passing.
5573 unsigned ArgOffset = LinkageSize;
5575 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5576 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5578 SmallVector<SDValue, 8> MemOpChains;
5579 for (unsigned i = 0; i != NumOps; ++i) {
5580 SDValue Arg = OutVals[i];
5581 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5582 EVT ArgVT = Outs[i].VT;
5583 EVT OrigVT = Outs[i].ArgVT;
5585 // PtrOff will be used to store the current argument to the stack if a
5586 // register cannot be found for it.
5589 // We re-align the argument offset for each argument, except when using the
5590 // fast calling convention, when we need to make sure we do that only when
5591 // we'll actually use a stack slot.
5592 auto ComputePtrOff = [&]() {
5593 /* Respect alignment of argument on the stack. */
5595 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5596 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5598 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5600 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5603 if (CallConv != CallingConv::Fast) {
5606 /* Compute GPR index associated with argument offset. */
5607 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5608 GPR_idx = std::min(GPR_idx, NumGPRs);
5611 // Promote integers to 64-bit values.
5612 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5613 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5614 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5615 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5618 // FIXME memcpy is used way more than necessary. Correctness first.
5619 // Note: "by value" is code for passing a structure by value, not
5621 if (Flags.isByVal()) {
5622 // Note: Size includes alignment padding, so
5623 // struct x { short a; char b; }
5624 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
5625 // These are the proper values we need for right-justifying the
5626 // aggregate in a parameter register.
5627 unsigned Size = Flags.getByValSize();
5629 // An empty aggregate parameter takes up no storage and no
5634 if (CallConv == CallingConv::Fast)
5637 // All aggregates smaller than 8 bytes must be passed right-justified.
5638 if (Size==1 || Size==2 || Size==4) {
5639 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5640 if (GPR_idx != NumGPRs) {
5641 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5642 MachinePointerInfo(), VT);
5643 MemOpChains.push_back(Load.getValue(1));
5644 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5646 ArgOffset += PtrByteSize;
5651 if (GPR_idx == NumGPRs && Size < 8) {
5652 SDValue AddPtr = PtrOff;
5653 if (!isLittleEndian) {
5654 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5655 PtrOff.getValueType());
5656 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5658 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5661 ArgOffset += PtrByteSize;
5664 // Copy entire object into memory. There are cases where gcc-generated
5665 // code assumes it is there, even if it could be put entirely into
5666 // registers. (This is not what the doc says.)
5668 // FIXME: The above statement is likely due to a misunderstanding of the
5669 // documents. All arguments must be copied into the parameter area BY
5670 // THE CALLEE in the event that the callee takes the address of any
5671 // formal argument. That has not yet been implemented. However, it is
5672 // reasonable to use the stack area as a staging area for the register
5675 // Skip this for small aggregates, as we will use the same slot for a
5676 // right-justified copy, below.
5678 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5682 // When a register is available, pass a small aggregate right-justified.
5683 if (Size < 8 && GPR_idx != NumGPRs) {
5684 // The easiest way to get this right-justified in a register
5685 // is to copy the structure into the rightmost portion of a
5686 // local variable slot, then load the whole slot into the
5688 // FIXME: The memcpy seems to produce pretty awful code for
5689 // small aggregates, particularly for packed ones.
5690 // FIXME: It would be preferable to use the slot in the
5691 // parameter save area instead of a new local variable.
5692 SDValue AddPtr = PtrOff;
5693 if (!isLittleEndian) {
5694 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5695 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5697 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5701 // Load the slot into the register.
5703 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5704 MemOpChains.push_back(Load.getValue(1));
5705 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5707 // Done with this argument.
5708 ArgOffset += PtrByteSize;
5712 // For aggregates larger than PtrByteSize, copy the pieces of the
5713 // object that fit into registers from the parameter save area.
5714 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5715 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5716 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5717 if (GPR_idx != NumGPRs) {
5719 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5720 MemOpChains.push_back(Load.getValue(1));
5721 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5722 ArgOffset += PtrByteSize;
5724 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5731 switch (Arg.getSimpleValueType().SimpleTy) {
5732 default: llvm_unreachable("Unexpected ValueType for argument!");
5736 if (Flags.isNest()) {
5737 // The 'nest' parameter, if any, is passed in R11.
5738 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5743 // These can be scalar arguments or elements of an integer array type
5744 // passed directly. Clang may use those instead of "byval" aggregate
5745 // types to avoid forcing arguments to memory unnecessarily.
5746 if (GPR_idx != NumGPRs) {
5747 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5749 if (CallConv == CallingConv::Fast)
5752 assert(HasParameterArea &&
5753 "Parameter area must exist to pass an argument in memory.");
5754 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5755 true, isTailCall, false, MemOpChains,
5756 TailCallArguments, dl);
5757 if (CallConv == CallingConv::Fast)
5758 ArgOffset += PtrByteSize;
5760 if (CallConv != CallingConv::Fast)
5761 ArgOffset += PtrByteSize;
5765 // These can be scalar arguments or elements of a float array type
5766 // passed directly. The latter are used to implement ELFv2 homogenous
5767 // float aggregates.
5769 // Named arguments go into FPRs first, and once they overflow, the
5770 // remaining arguments go into GPRs and then the parameter save area.
5771 // Unnamed arguments for vararg functions always go to GPRs and
5772 // then the parameter save area. For now, put all arguments to vararg
5773 // routines always in both locations (FPR *and* GPR or stack slot).
5774 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5775 bool NeededLoad = false;
5777 // First load the argument into the next available FPR.
5778 if (FPR_idx != NumFPRs)
5779 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5781 // Next, load the argument into GPR or stack slot if needed.
5782 if (!NeedGPROrStack)
5784 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5785 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5786 // once we support fp <-> gpr moves.
5788 // In the non-vararg case, this can only ever happen in the
5789 // presence of f32 array types, since otherwise we never run
5790 // out of FPRs before running out of GPRs.
5793 // Double values are always passed in a single GPR.
5794 if (Arg.getValueType() != MVT::f32) {
5795 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5797 // Non-array float values are extended and passed in a GPR.
5798 } else if (!Flags.isInConsecutiveRegs()) {
5799 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5800 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5802 // If we have an array of floats, we collect every odd element
5803 // together with its predecessor into one GPR.
5804 } else if (ArgOffset % PtrByteSize != 0) {
5806 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5807 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5808 if (!isLittleEndian)
5810 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5812 // The final element, if even, goes into the first half of a GPR.
5813 } else if (Flags.isInConsecutiveRegsLast()) {
5814 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5815 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5816 if (!isLittleEndian)
5817 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5818 DAG.getConstant(32, dl, MVT::i32));
5820 // Non-final even elements are skipped; they will be handled
5821 // together the with subsequent argument on the next go-around.
5825 if (ArgVal.getNode())
5826 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5828 if (CallConv == CallingConv::Fast)
5831 // Single-precision floating-point values are mapped to the
5832 // second (rightmost) word of the stack doubleword.
5833 if (Arg.getValueType() == MVT::f32 &&
5834 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5835 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5836 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5839 assert(HasParameterArea &&
5840 "Parameter area must exist to pass an argument in memory.");
5841 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5842 true, isTailCall, false, MemOpChains,
5843 TailCallArguments, dl);
5847 // When passing an array of floats, the array occupies consecutive
5848 // space in the argument area; only round up to the next doubleword
5849 // at the end of the array. Otherwise, each float takes 8 bytes.
5850 if (CallConv != CallingConv::Fast || NeededLoad) {
5851 ArgOffset += (Arg.getValueType() == MVT::f32 &&
5852 Flags.isInConsecutiveRegs()) ? 4 : 8;
5853 if (Flags.isInConsecutiveRegsLast())
5854 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5865 if (!Subtarget.hasQPX()) {
5866 // These can be scalar arguments or elements of a vector array type
5867 // passed directly. The latter are used to implement ELFv2 homogenous
5868 // vector aggregates.
5870 // For a varargs call, named arguments go into VRs or on the stack as
5871 // usual; unnamed arguments always go to the stack or the corresponding
5872 // GPRs when within range. For now, we always put the value in both
5873 // locations (or even all three).
5875 assert(HasParameterArea &&
5876 "Parameter area must exist if we have a varargs call.");
5877 // We could elide this store in the case where the object fits
5878 // entirely in R registers. Maybe later.
5880 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5881 MemOpChains.push_back(Store);
5882 if (VR_idx != NumVRs) {
5884 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5885 MemOpChains.push_back(Load.getValue(1));
5886 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5889 for (unsigned i=0; i<16; i+=PtrByteSize) {
5890 if (GPR_idx == NumGPRs)
5892 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5893 DAG.getConstant(i, dl, PtrVT));
5895 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5896 MemOpChains.push_back(Load.getValue(1));
5897 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5902 // Non-varargs Altivec params go into VRs or on the stack.
5903 if (VR_idx != NumVRs) {
5904 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5906 if (CallConv == CallingConv::Fast)
5909 assert(HasParameterArea &&
5910 "Parameter area must exist to pass an argument in memory.");
5911 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5912 true, isTailCall, true, MemOpChains,
5913 TailCallArguments, dl);
5914 if (CallConv == CallingConv::Fast)
5918 if (CallConv != CallingConv::Fast)
5923 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5924 "Invalid QPX parameter type");
5929 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5931 assert(HasParameterArea &&
5932 "Parameter area must exist if we have a varargs call.");
5933 // We could elide this store in the case where the object fits
5934 // entirely in R registers. Maybe later.
5936 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5937 MemOpChains.push_back(Store);
5938 if (QFPR_idx != NumQFPRs) {
5939 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5940 PtrOff, MachinePointerInfo());
5941 MemOpChains.push_back(Load.getValue(1));
5942 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5944 ArgOffset += (IsF32 ? 16 : 32);
5945 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5946 if (GPR_idx == NumGPRs)
5948 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5949 DAG.getConstant(i, dl, PtrVT));
5951 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5952 MemOpChains.push_back(Load.getValue(1));
5953 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5958 // Non-varargs QPX params go into registers or on the stack.
5959 if (QFPR_idx != NumQFPRs) {
5960 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5962 if (CallConv == CallingConv::Fast)
5965 assert(HasParameterArea &&
5966 "Parameter area must exist to pass an argument in memory.");
5967 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5968 true, isTailCall, true, MemOpChains,
5969 TailCallArguments, dl);
5970 if (CallConv == CallingConv::Fast)
5971 ArgOffset += (IsF32 ? 16 : 32);
5974 if (CallConv != CallingConv::Fast)
5975 ArgOffset += (IsF32 ? 16 : 32);
5981 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5982 "mismatch in size of parameter area");
5983 (void)NumBytesActuallyUsed;
5985 if (!MemOpChains.empty())
5986 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5988 // Check if this is an indirect call (MTCTR/BCTRL).
5989 // See PrepareCall() for more information about calls through function
5990 // pointers in the 64-bit SVR4 ABI.
5991 if (!isTailCall && !isPatchPoint &&
5992 !isFunctionGlobalAddress(Callee) &&
5993 !isa<ExternalSymbolSDNode>(Callee)) {
5994 // Load r2 into a virtual register and store it to the TOC save area.
5995 setUsesTOCBasePtr(DAG);
5996 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5997 // TOC save area offset.
5998 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5999 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6000 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6001 Chain = DAG.getStore(
6002 Val.getValue(1), dl, Val, AddPtr,
6003 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6004 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6005 // This does not mean the MTCTR instruction must use R12; it's easier
6006 // to model this as an extra parameter, so do that.
6007 if (isELFv2ABI && !isPatchPoint)
6008 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6011 // Build a sequence of copy-to-reg nodes chained together with token chain
6012 // and flag operands which copy the outgoing args into the appropriate regs.
6014 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6015 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6016 RegsToPass[i].second, InFlag);
6017 InFlag = Chain.getValue(1);
6020 if (isTailCall && !IsSibCall)
6021 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6024 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6025 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6026 SPDiff, NumBytes, Ins, InVals, CS);
6029 SDValue PPCTargetLowering::LowerCall_Darwin(
6030 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6031 bool isTailCall, bool isPatchPoint,
6032 const SmallVectorImpl<ISD::OutputArg> &Outs,
6033 const SmallVectorImpl<SDValue> &OutVals,
6034 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6035 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6036 ImmutableCallSite CS) const {
6037 unsigned NumOps = Outs.size();
6039 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6040 bool isPPC64 = PtrVT == MVT::i64;
6041 unsigned PtrByteSize = isPPC64 ? 8 : 4;
6043 MachineFunction &MF = DAG.getMachineFunction();
6045 // Mark this function as potentially containing a function that contains a
6046 // tail call. As a consequence the frame pointer will be used for dynamicalloc
6047 // and restoring the callers stack pointer in this functions epilog. This is
6048 // done because by tail calling the called function might overwrite the value
6049 // in this function's (MF) stack pointer stack slot 0(SP).
6050 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6051 CallConv == CallingConv::Fast)
6052 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6054 // Count how many bytes are to be pushed on the stack, including the linkage
6055 // area, and parameter passing area. We start with 24/48 bytes, which is
6056 // prereserved space for [SP][CR][LR][3 x unused].
6057 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6058 unsigned NumBytes = LinkageSize;
6060 // Add up all the space actually used.
6061 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6062 // they all go in registers, but we must reserve stack space for them for
6063 // possible use by the caller. In varargs or 64-bit calls, parameters are
6064 // assigned stack space in order, with padding so Altivec parameters are
6066 unsigned nAltivecParamsAtEnd = 0;
6067 for (unsigned i = 0; i != NumOps; ++i) {
6068 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6069 EVT ArgVT = Outs[i].VT;
6070 // Varargs Altivec parameters are padded to a 16 byte boundary.
6071 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6072 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6073 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6074 if (!isVarArg && !isPPC64) {
6075 // Non-varargs Altivec parameters go after all the non-Altivec
6076 // parameters; handle those later so we know how much padding we need.
6077 nAltivecParamsAtEnd++;
6080 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6081 NumBytes = ((NumBytes+15)/16)*16;
6083 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6086 // Allow for Altivec parameters at the end, if needed.
6087 if (nAltivecParamsAtEnd) {
6088 NumBytes = ((NumBytes+15)/16)*16;
6089 NumBytes += 16*nAltivecParamsAtEnd;
6092 // The prolog code of the callee may store up to 8 GPR argument registers to
6093 // the stack, allowing va_start to index over them in memory if its varargs.
6094 // Because we cannot tell if this is needed on the caller side, we have to
6095 // conservatively assume that it is needed. As such, make sure we have at
6096 // least enough stack space for the caller to store the 8 GPRs.
6097 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6099 // Tail call needs the stack to be aligned.
6100 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6101 CallConv == CallingConv::Fast)
6102 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6104 // Calculate by how many bytes the stack has to be adjusted in case of tail
6105 // call optimization.
6106 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6108 // To protect arguments on the stack from being clobbered in a tail call,
6109 // force all the loads to happen before doing any other lowering.
6111 Chain = DAG.getStackArgumentTokenFactor(Chain);
6113 // Adjust the stack pointer for the new arguments...
6114 // These operations are automatically eliminated by the prolog/epilog pass
6115 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6116 SDValue CallSeqStart = Chain;
6118 // Load the return address and frame pointer so it can be move somewhere else
6121 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6123 // Set up a copy of the stack pointer for use loading and storing any
6124 // arguments that may not fit in the registers available for argument
6128 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6130 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6132 // Figure out which arguments are going to go in registers, and which in
6133 // memory. Also, if this is a vararg function, floating point operations
6134 // must be stored to our stack, and loaded into integer regs as well, if
6135 // any integer regs are available for argument passing.
6136 unsigned ArgOffset = LinkageSize;
6137 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6139 static const MCPhysReg GPR_32[] = { // 32-bit registers.
6140 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6141 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6143 static const MCPhysReg GPR_64[] = { // 64-bit registers.
6144 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6145 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6147 static const MCPhysReg VR[] = {
6148 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6149 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6151 const unsigned NumGPRs = array_lengthof(GPR_32);
6152 const unsigned NumFPRs = 13;
6153 const unsigned NumVRs = array_lengthof(VR);
6155 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6157 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6158 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6160 SmallVector<SDValue, 8> MemOpChains;
6161 for (unsigned i = 0; i != NumOps; ++i) {
6162 SDValue Arg = OutVals[i];
6163 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6165 // PtrOff will be used to store the current argument to the stack if a
6166 // register cannot be found for it.
6169 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6171 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6173 // On PPC64, promote integers to 64-bit values.
6174 if (isPPC64 && Arg.getValueType() == MVT::i32) {
6175 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6176 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6177 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6180 // FIXME memcpy is used way more than necessary. Correctness first.
6181 // Note: "by value" is code for passing a structure by value, not
6183 if (Flags.isByVal()) {
6184 unsigned Size = Flags.getByValSize();
6185 // Very small objects are passed right-justified. Everything else is
6186 // passed left-justified.
6187 if (Size==1 || Size==2) {
6188 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6189 if (GPR_idx != NumGPRs) {
6190 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6191 MachinePointerInfo(), VT);
6192 MemOpChains.push_back(Load.getValue(1));
6193 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6195 ArgOffset += PtrByteSize;
6197 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6198 PtrOff.getValueType());
6199 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6200 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6203 ArgOffset += PtrByteSize;
6207 // Copy entire object into memory. There are cases where gcc-generated
6208 // code assumes it is there, even if it could be put entirely into
6209 // registers. (This is not what the doc says.)
6210 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6214 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6215 // copy the pieces of the object that fit into registers from the
6216 // parameter save area.
6217 for (unsigned j=0; j<Size; j+=PtrByteSize) {
6218 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6219 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6220 if (GPR_idx != NumGPRs) {
6222 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6223 MemOpChains.push_back(Load.getValue(1));
6224 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6225 ArgOffset += PtrByteSize;
6227 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6234 switch (Arg.getSimpleValueType().SimpleTy) {
6235 default: llvm_unreachable("Unexpected ValueType for argument!");
6239 if (GPR_idx != NumGPRs) {
6240 if (Arg.getValueType() == MVT::i1)
6241 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6243 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6245 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6246 isPPC64, isTailCall, false, MemOpChains,
6247 TailCallArguments, dl);
6249 ArgOffset += PtrByteSize;
6253 if (FPR_idx != NumFPRs) {
6254 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6258 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6259 MemOpChains.push_back(Store);
6261 // Float varargs are always shadowed in available integer registers
6262 if (GPR_idx != NumGPRs) {
6264 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6265 MemOpChains.push_back(Load.getValue(1));
6266 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6268 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6269 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6270 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6272 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6273 MemOpChains.push_back(Load.getValue(1));
6274 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6277 // If we have any FPRs remaining, we may also have GPRs remaining.
6278 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6280 if (GPR_idx != NumGPRs)
6282 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6283 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
6287 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6288 isPPC64, isTailCall, false, MemOpChains,
6289 TailCallArguments, dl);
6293 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6300 // These go aligned on the stack, or in the corresponding R registers
6301 // when within range. The Darwin PPC ABI doc claims they also go in
6302 // V registers; in fact gcc does this only for arguments that are
6303 // prototyped, not for those that match the ... We do it for all
6304 // arguments, seems to work.
6305 while (ArgOffset % 16 !=0) {
6306 ArgOffset += PtrByteSize;
6307 if (GPR_idx != NumGPRs)
6310 // We could elide this store in the case where the object fits
6311 // entirely in R registers. Maybe later.
6312 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6313 DAG.getConstant(ArgOffset, dl, PtrVT));
6315 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6316 MemOpChains.push_back(Store);
6317 if (VR_idx != NumVRs) {
6319 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6320 MemOpChains.push_back(Load.getValue(1));
6321 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6324 for (unsigned i=0; i<16; i+=PtrByteSize) {
6325 if (GPR_idx == NumGPRs)
6327 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6328 DAG.getConstant(i, dl, PtrVT));
6330 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6331 MemOpChains.push_back(Load.getValue(1));
6332 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6337 // Non-varargs Altivec params generally go in registers, but have
6338 // stack space allocated at the end.
6339 if (VR_idx != NumVRs) {
6340 // Doesn't have GPR space allocated.
6341 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6342 } else if (nAltivecParamsAtEnd==0) {
6343 // We are emitting Altivec params in order.
6344 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6345 isPPC64, isTailCall, true, MemOpChains,
6346 TailCallArguments, dl);
6352 // If all Altivec parameters fit in registers, as they usually do,
6353 // they get stack space following the non-Altivec parameters. We
6354 // don't track this here because nobody below needs it.
6355 // If there are more Altivec parameters than fit in registers emit
6357 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6359 // Offset is aligned; skip 1st 12 params which go in V registers.
6360 ArgOffset = ((ArgOffset+15)/16)*16;
6362 for (unsigned i = 0; i != NumOps; ++i) {
6363 SDValue Arg = OutVals[i];
6364 EVT ArgType = Outs[i].VT;
6365 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6366 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6369 // We are emitting Altivec params in order.
6370 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6371 isPPC64, isTailCall, true, MemOpChains,
6372 TailCallArguments, dl);
6379 if (!MemOpChains.empty())
6380 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6382 // On Darwin, R12 must contain the address of an indirect callee. This does
6383 // not mean the MTCTR instruction must use R12; it's easier to model this as
6384 // an extra parameter, so do that.
6386 !isFunctionGlobalAddress(Callee) &&
6387 !isa<ExternalSymbolSDNode>(Callee) &&
6388 !isBLACompatibleAddress(Callee, DAG))
6389 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6390 PPC::R12), Callee));
6392 // Build a sequence of copy-to-reg nodes chained together with token chain
6393 // and flag operands which copy the outgoing args into the appropriate regs.
6395 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6396 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6397 RegsToPass[i].second, InFlag);
6398 InFlag = Chain.getValue(1);
6402 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6405 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6406 /* unused except on PPC64 ELFv1 */ false, DAG,
6407 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6408 NumBytes, Ins, InVals, CS);
6412 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6413 MachineFunction &MF, bool isVarArg,
6414 const SmallVectorImpl<ISD::OutputArg> &Outs,
6415 LLVMContext &Context) const {
6416 SmallVector<CCValAssign, 16> RVLocs;
6417 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6418 return CCInfo.CheckReturn(Outs, RetCC_PPC);
6422 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6424 const SmallVectorImpl<ISD::OutputArg> &Outs,
6425 const SmallVectorImpl<SDValue> &OutVals,
6426 const SDLoc &dl, SelectionDAG &DAG) const {
6427 SmallVector<CCValAssign, 16> RVLocs;
6428 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6430 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6433 SmallVector<SDValue, 4> RetOps(1, Chain);
6435 // Copy the result values into the output registers.
6436 for (unsigned i = 0; i != RVLocs.size(); ++i) {
6437 CCValAssign &VA = RVLocs[i];
6438 assert(VA.isRegLoc() && "Can only return in registers!");
6440 SDValue Arg = OutVals[i];
6442 switch (VA.getLocInfo()) {
6443 default: llvm_unreachable("Unknown loc info!");
6444 case CCValAssign::Full: break;
6445 case CCValAssign::AExt:
6446 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6448 case CCValAssign::ZExt:
6449 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6451 case CCValAssign::SExt:
6452 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6456 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6457 Flag = Chain.getValue(1);
6458 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6461 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6462 const MCPhysReg *I =
6463 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6467 if (PPC::G8RCRegClass.contains(*I))
6468 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6469 else if (PPC::F8RCRegClass.contains(*I))
6470 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6471 else if (PPC::CRRCRegClass.contains(*I))
6472 RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6473 else if (PPC::VRRCRegClass.contains(*I))
6474 RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6476 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6480 RetOps[0] = Chain; // Update chain.
6482 // Add the flag if we have it.
6484 RetOps.push_back(Flag);
6486 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6490 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6491 SelectionDAG &DAG) const {
6494 // Get the correct type for integers.
6495 EVT IntVT = Op.getValueType();
6498 SDValue Chain = Op.getOperand(0);
6499 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6500 // Build a DYNAREAOFFSET node.
6501 SDValue Ops[2] = {Chain, FPSIdx};
6502 SDVTList VTs = DAG.getVTList(IntVT);
6503 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6506 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6507 SelectionDAG &DAG) const {
6508 // When we pop the dynamic allocation we need to restore the SP link.
6511 // Get the correct type for pointers.
6512 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6514 // Construct the stack pointer operand.
6515 bool isPPC64 = Subtarget.isPPC64();
6516 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6517 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6519 // Get the operands for the STACKRESTORE.
6520 SDValue Chain = Op.getOperand(0);
6521 SDValue SaveSP = Op.getOperand(1);
6523 // Load the old link SP.
6524 SDValue LoadLinkSP =
6525 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6527 // Restore the stack pointer.
6528 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6530 // Store the old link SP.
6531 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6534 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6535 MachineFunction &MF = DAG.getMachineFunction();
6536 bool isPPC64 = Subtarget.isPPC64();
6537 EVT PtrVT = getPointerTy(MF.getDataLayout());
6539 // Get current frame pointer save index. The users of this index will be
6540 // primarily DYNALLOC instructions.
6541 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6542 int RASI = FI->getReturnAddrSaveIndex();
6544 // If the frame pointer save index hasn't been defined yet.
6546 // Find out what the fix offset of the frame pointer save area.
6547 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6548 // Allocate the frame index for frame pointer save area.
6549 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6551 FI->setReturnAddrSaveIndex(RASI);
6553 return DAG.getFrameIndex(RASI, PtrVT);
6557 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6558 MachineFunction &MF = DAG.getMachineFunction();
6559 bool isPPC64 = Subtarget.isPPC64();
6560 EVT PtrVT = getPointerTy(MF.getDataLayout());
6562 // Get current frame pointer save index. The users of this index will be
6563 // primarily DYNALLOC instructions.
6564 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6565 int FPSI = FI->getFramePointerSaveIndex();
6567 // If the frame pointer save index hasn't been defined yet.
6569 // Find out what the fix offset of the frame pointer save area.
6570 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6571 // Allocate the frame index for frame pointer save area.
6572 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6574 FI->setFramePointerSaveIndex(FPSI);
6576 return DAG.getFrameIndex(FPSI, PtrVT);
6579 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6580 SelectionDAG &DAG) const {
6582 SDValue Chain = Op.getOperand(0);
6583 SDValue Size = Op.getOperand(1);
6586 // Get the correct type for pointers.
6587 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6589 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6590 DAG.getConstant(0, dl, PtrVT), Size);
6591 // Construct a node for the frame pointer save index.
6592 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6593 // Build a DYNALLOC node.
6594 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6595 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6596 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6599 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6600 SelectionDAG &DAG) const {
6601 MachineFunction &MF = DAG.getMachineFunction();
6603 bool isPPC64 = Subtarget.isPPC64();
6604 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6606 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6607 return DAG.getFrameIndex(FI, PtrVT);
6610 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6611 SelectionDAG &DAG) const {
6613 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6614 DAG.getVTList(MVT::i32, MVT::Other),
6615 Op.getOperand(0), Op.getOperand(1));
6618 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6619 SelectionDAG &DAG) const {
6621 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6622 Op.getOperand(0), Op.getOperand(1));
6625 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6626 if (Op.getValueType().isVector())
6627 return LowerVectorLoad(Op, DAG);
6629 assert(Op.getValueType() == MVT::i1 &&
6630 "Custom lowering only for i1 loads");
6632 // First, load 8 bits into 32 bits, then truncate to 1 bit.
6635 LoadSDNode *LD = cast<LoadSDNode>(Op);
6637 SDValue Chain = LD->getChain();
6638 SDValue BasePtr = LD->getBasePtr();
6639 MachineMemOperand *MMO = LD->getMemOperand();
6642 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6643 BasePtr, MVT::i8, MMO);
6644 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6646 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6647 return DAG.getMergeValues(Ops, dl);
6650 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6651 if (Op.getOperand(1).getValueType().isVector())
6652 return LowerVectorStore(Op, DAG);
6654 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6655 "Custom lowering only for i1 stores");
6657 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6660 StoreSDNode *ST = cast<StoreSDNode>(Op);
6662 SDValue Chain = ST->getChain();
6663 SDValue BasePtr = ST->getBasePtr();
6664 SDValue Value = ST->getValue();
6665 MachineMemOperand *MMO = ST->getMemOperand();
6667 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6669 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6672 // FIXME: Remove this once the ANDI glue bug is fixed:
6673 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6674 assert(Op.getValueType() == MVT::i1 &&
6675 "Custom lowering only for i1 results");
6678 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6682 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6684 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6685 // Not FP? Not a fsel.
6686 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6687 !Op.getOperand(2).getValueType().isFloatingPoint())
6690 // We might be able to do better than this under some circumstances, but in
6691 // general, fsel-based lowering of select is a finite-math-only optimization.
6692 // For more information, see section F.3 of the 2.06 ISA specification.
6693 if (!DAG.getTarget().Options.NoInfsFPMath ||
6694 !DAG.getTarget().Options.NoNaNsFPMath)
6696 // TODO: Propagate flags from the select rather than global settings.
6698 Flags.setNoInfs(true);
6699 Flags.setNoNaNs(true);
6701 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6703 EVT ResVT = Op.getValueType();
6704 EVT CmpVT = Op.getOperand(0).getValueType();
6705 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6706 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
6709 // If the RHS of the comparison is a 0.0, we don't need to do the
6710 // subtraction at all.
6712 if (isFloatingPointZero(RHS))
6714 default: break; // SETUO etc aren't handled by fsel.
6719 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6720 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6721 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6722 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6723 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6724 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6725 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6728 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6732 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6733 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6734 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6737 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6741 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6742 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6743 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6744 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6749 default: break; // SETUO etc aren't handled by fsel.
6754 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6755 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6756 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6757 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6758 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6759 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6760 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6761 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6764 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6765 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6766 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6767 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6770 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6771 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6772 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6773 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6776 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6777 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6778 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6779 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6782 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6783 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6784 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6785 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6790 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6792 const SDLoc &dl) const {
6793 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6794 SDValue Src = Op.getOperand(0);
6795 if (Src.getValueType() == MVT::f32)
6796 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6799 switch (Op.getSimpleValueType().SimpleTy) {
6800 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6803 Op.getOpcode() == ISD::FP_TO_SINT
6805 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6809 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6810 "i64 FP_TO_UINT is supported only with FPCVT");
6811 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6817 // Convert the FP value to an int value through memory.
6818 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6819 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6820 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6821 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6822 MachinePointerInfo MPI =
6823 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6825 // Emit a store to the stack slot.
6828 MachineFunction &MF = DAG.getMachineFunction();
6829 MachineMemOperand *MMO =
6830 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6831 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6832 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6833 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6835 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6837 // Result is a load from the stack slot. If loading 4 bytes, make sure to
6838 // add in a bias on big endian.
6839 if (Op.getValueType() == MVT::i32 && !i32Stack) {
6840 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6841 DAG.getConstant(4, dl, FIPtr.getValueType()));
6842 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6850 /// \brief Custom lowers floating point to integer conversions to use
6851 /// the direct move instructions available in ISA 2.07 to avoid the
6852 /// need for load/store combinations.
6853 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6855 const SDLoc &dl) const {
6856 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6857 SDValue Src = Op.getOperand(0);
6859 if (Src.getValueType() == MVT::f32)
6860 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6863 switch (Op.getSimpleValueType().SimpleTy) {
6864 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6867 Op.getOpcode() == ISD::FP_TO_SINT
6869 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6871 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6874 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6875 "i64 FP_TO_UINT is supported only with FPCVT");
6876 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6879 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6885 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6886 const SDLoc &dl) const {
6887 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6888 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6891 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6893 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6894 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6897 // We're trying to insert a regular store, S, and then a load, L. If the
6898 // incoming value, O, is a load, we might just be able to have our load use the
6899 // address used by O. However, we don't know if anything else will store to
6900 // that address before we can load from it. To prevent this situation, we need
6901 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6902 // the same chain operand as O, we create a token factor from the chain results
6903 // of O and L, and we replace all uses of O's chain result with that token
6904 // factor (see spliceIntoChain below for this last part).
6905 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6908 ISD::LoadExtType ET) const {
6910 if (ET == ISD::NON_EXTLOAD &&
6911 (Op.getOpcode() == ISD::FP_TO_UINT ||
6912 Op.getOpcode() == ISD::FP_TO_SINT) &&
6913 isOperationLegalOrCustom(Op.getOpcode(),
6914 Op.getOperand(0).getValueType())) {
6916 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6920 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6921 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6922 LD->isNonTemporal())
6924 if (LD->getMemoryVT() != MemVT)
6927 RLI.Ptr = LD->getBasePtr();
6928 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6929 assert(LD->getAddressingMode() == ISD::PRE_INC &&
6930 "Non-pre-inc AM on PPC?");
6931 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6935 RLI.Chain = LD->getChain();
6936 RLI.MPI = LD->getPointerInfo();
6937 RLI.IsDereferenceable = LD->isDereferenceable();
6938 RLI.IsInvariant = LD->isInvariant();
6939 RLI.Alignment = LD->getAlignment();
6940 RLI.AAInfo = LD->getAAInfo();
6941 RLI.Ranges = LD->getRanges();
6943 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6947 // Given the head of the old chain, ResChain, insert a token factor containing
6948 // it and NewResChain, and make users of ResChain now be users of that token
6950 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
6951 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6952 SDValue NewResChain,
6953 SelectionDAG &DAG) const {
6957 SDLoc dl(NewResChain);
6959 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6960 NewResChain, DAG.getUNDEF(MVT::Other));
6961 assert(TF.getNode() != NewResChain.getNode() &&
6962 "A new TF really is required here");
6964 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6965 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6968 /// \brief Analyze profitability of direct move
6969 /// prefer float load to int load plus direct move
6970 /// when there is no integer use of int load
6971 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6972 SDNode *Origin = Op.getOperand(0).getNode();
6973 if (Origin->getOpcode() != ISD::LOAD)
6976 // If there is no LXSIBZX/LXSIHZX, like Power8,
6977 // prefer direct move if the memory size is 1 or 2 bytes.
6978 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6979 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6982 for (SDNode::use_iterator UI = Origin->use_begin(),
6983 UE = Origin->use_end();
6986 // Only look at the users of the loaded value.
6987 if (UI.getUse().get().getResNo() != 0)
6990 if (UI->getOpcode() != ISD::SINT_TO_FP &&
6991 UI->getOpcode() != ISD::UINT_TO_FP)
6998 /// \brief Custom lowers integer to floating point conversions to use
6999 /// the direct move instructions available in ISA 2.07 to avoid the
7000 /// need for load/store combinations.
7001 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7003 const SDLoc &dl) const {
7004 assert((Op.getValueType() == MVT::f32 ||
7005 Op.getValueType() == MVT::f64) &&
7006 "Invalid floating point type as target of conversion");
7007 assert(Subtarget.hasFPCVT() &&
7008 "Int to FP conversions with direct moves require FPCVT");
7010 SDValue Src = Op.getOperand(0);
7011 bool SinglePrec = Op.getValueType() == MVT::f32;
7012 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7013 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7014 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7015 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7018 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7020 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7023 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7024 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7030 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7031 SelectionDAG &DAG) const {
7034 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7035 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7038 SDValue Value = Op.getOperand(0);
7039 // The values are now known to be -1 (false) or 1 (true). To convert this
7040 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7041 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7042 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7044 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7046 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7048 if (Op.getValueType() != MVT::v4f64)
7049 Value = DAG.getNode(ISD::FP_ROUND, dl,
7050 Op.getValueType(), Value,
7051 DAG.getIntPtrConstant(1, dl));
7055 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7056 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7059 if (Op.getOperand(0).getValueType() == MVT::i1)
7060 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7061 DAG.getConstantFP(1.0, dl, Op.getValueType()),
7062 DAG.getConstantFP(0.0, dl, Op.getValueType()));
7064 // If we have direct moves, we can do all the conversion, skip the store/load
7065 // however, without FPCVT we can't do most conversions.
7066 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7067 Subtarget.isPPC64() && Subtarget.hasFPCVT())
7068 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7070 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7071 "UINT_TO_FP is supported only with FPCVT");
7073 // If we have FCFIDS, then use it when converting to single-precision.
7074 // Otherwise, convert to double-precision and then round.
7075 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7076 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7078 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7080 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7084 if (Op.getOperand(0).getValueType() == MVT::i64) {
7085 SDValue SINT = Op.getOperand(0);
7086 // When converting to single-precision, we actually need to convert
7087 // to double-precision first and then round to single-precision.
7088 // To avoid double-rounding effects during that operation, we have
7089 // to prepare the input operand. Bits that might be truncated when
7090 // converting to double-precision are replaced by a bit that won't
7091 // be lost at this stage, but is below the single-precision rounding
7094 // However, if -enable-unsafe-fp-math is in effect, accept double
7095 // rounding to avoid the extra overhead.
7096 if (Op.getValueType() == MVT::f32 &&
7097 !Subtarget.hasFPCVT() &&
7098 !DAG.getTarget().Options.UnsafeFPMath) {
7100 // Twiddle input to make sure the low 11 bits are zero. (If this
7101 // is the case, we are guaranteed the value will fit into the 53 bit
7102 // mantissa of an IEEE double-precision value without rounding.)
7103 // If any of those low 11 bits were not zero originally, make sure
7104 // bit 12 (value 2048) is set instead, so that the final rounding
7105 // to single-precision gets the correct result.
7106 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7107 SINT, DAG.getConstant(2047, dl, MVT::i64));
7108 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7109 Round, DAG.getConstant(2047, dl, MVT::i64));
7110 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7111 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7112 Round, DAG.getConstant(-2048, dl, MVT::i64));
7114 // However, we cannot use that value unconditionally: if the magnitude
7115 // of the input value is small, the bit-twiddling we did above might
7116 // end up visibly changing the output. Fortunately, in that case, we
7117 // don't need to twiddle bits since the original input will convert
7118 // exactly to double-precision floating-point already. Therefore,
7119 // construct a conditional to use the original value if the top 11
7120 // bits are all sign-bit copies, and use the rounded value computed
7122 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7123 SINT, DAG.getConstant(53, dl, MVT::i32));
7124 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7125 Cond, DAG.getConstant(1, dl, MVT::i64));
7126 Cond = DAG.getSetCC(dl, MVT::i32,
7127 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7129 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7135 MachineFunction &MF = DAG.getMachineFunction();
7136 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7137 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7138 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7139 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7140 } else if (Subtarget.hasLFIWAX() &&
7141 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7142 MachineMemOperand *MMO =
7143 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7144 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7145 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7146 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7147 DAG.getVTList(MVT::f64, MVT::Other),
7148 Ops, MVT::i32, MMO);
7149 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7150 } else if (Subtarget.hasFPCVT() &&
7151 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7152 MachineMemOperand *MMO =
7153 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7154 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7155 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7156 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7157 DAG.getVTList(MVT::f64, MVT::Other),
7158 Ops, MVT::i32, MMO);
7159 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7160 } else if (((Subtarget.hasLFIWAX() &&
7161 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7162 (Subtarget.hasFPCVT() &&
7163 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7164 SINT.getOperand(0).getValueType() == MVT::i32) {
7165 MachineFrameInfo &MFI = MF.getFrameInfo();
7166 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7168 int FrameIdx = MFI.CreateStackObject(4, 4, false);
7169 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7172 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7173 MachinePointerInfo::getFixedStack(
7174 DAG.getMachineFunction(), FrameIdx));
7176 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7177 "Expected an i32 store");
7182 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7185 MachineMemOperand *MMO =
7186 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7187 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7188 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7189 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7190 PPCISD::LFIWZX : PPCISD::LFIWAX,
7191 dl, DAG.getVTList(MVT::f64, MVT::Other),
7192 Ops, MVT::i32, MMO);
7194 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7196 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7198 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7199 FP = DAG.getNode(ISD::FP_ROUND, dl,
7200 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7204 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7205 "Unhandled INT_TO_FP type in custom expander!");
7206 // Since we only generate this in 64-bit mode, we can take advantage of
7207 // 64-bit registers. In particular, sign extend the input value into the
7208 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7209 // then lfd it and fcfid it.
7210 MachineFunction &MF = DAG.getMachineFunction();
7211 MachineFrameInfo &MFI = MF.getFrameInfo();
7212 EVT PtrVT = getPointerTy(MF.getDataLayout());
7215 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7218 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7220 int FrameIdx = MFI.CreateStackObject(4, 4, false);
7221 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7224 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7225 MachinePointerInfo::getFixedStack(
7226 DAG.getMachineFunction(), FrameIdx));
7228 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7229 "Expected an i32 store");
7234 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7238 MachineMemOperand *MMO =
7239 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7240 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7241 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7242 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7243 PPCISD::LFIWZX : PPCISD::LFIWAX,
7244 dl, DAG.getVTList(MVT::f64, MVT::Other),
7245 Ops, MVT::i32, MMO);
7247 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7249 assert(Subtarget.isPPC64() &&
7250 "i32->FP without LFIWAX supported only on PPC64");
7252 int FrameIdx = MFI.CreateStackObject(8, 8, false);
7253 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7255 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7258 // STD the extended value into the stack slot.
7259 SDValue Store = DAG.getStore(
7260 DAG.getEntryNode(), dl, Ext64, FIdx,
7261 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7263 // Load the value as a double.
7265 MVT::f64, dl, Store, FIdx,
7266 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7269 // FCFID it and return it.
7270 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7271 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7272 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7273 DAG.getIntPtrConstant(0, dl));
7277 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7278 SelectionDAG &DAG) const {
7281 The rounding mode is in bits 30:31 of FPSR, and has the following
7288 FLT_ROUNDS, on the other hand, expects the following:
7295 To perform the conversion, we do:
7296 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7299 MachineFunction &MF = DAG.getMachineFunction();
7300 EVT VT = Op.getValueType();
7301 EVT PtrVT = getPointerTy(MF.getDataLayout());
7303 // Save FP Control Word to register
7305 MVT::f64, // return register
7306 MVT::Glue // unused in this context
7308 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7310 // Save FP register to stack slot
7311 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7312 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7313 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7314 MachinePointerInfo());
7316 // Load FP Control Word from low 32 bits of stack slot.
7317 SDValue Four = DAG.getConstant(4, dl, PtrVT);
7318 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7319 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7321 // Transform as necessary
7323 DAG.getNode(ISD::AND, dl, MVT::i32,
7324 CWD, DAG.getConstant(3, dl, MVT::i32));
7326 DAG.getNode(ISD::SRL, dl, MVT::i32,
7327 DAG.getNode(ISD::AND, dl, MVT::i32,
7328 DAG.getNode(ISD::XOR, dl, MVT::i32,
7329 CWD, DAG.getConstant(3, dl, MVT::i32)),
7330 DAG.getConstant(3, dl, MVT::i32)),
7331 DAG.getConstant(1, dl, MVT::i32));
7334 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7336 return DAG.getNode((VT.getSizeInBits() < 16 ?
7337 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7340 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7341 EVT VT = Op.getValueType();
7342 unsigned BitWidth = VT.getSizeInBits();
7344 assert(Op.getNumOperands() == 3 &&
7345 VT == Op.getOperand(1).getValueType() &&
7348 // Expand into a bunch of logical ops. Note that these ops
7349 // depend on the PPC behavior for oversized shift amounts.
7350 SDValue Lo = Op.getOperand(0);
7351 SDValue Hi = Op.getOperand(1);
7352 SDValue Amt = Op.getOperand(2);
7353 EVT AmtVT = Amt.getValueType();
7355 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7356 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7357 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7358 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7359 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7360 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7361 DAG.getConstant(-BitWidth, dl, AmtVT));
7362 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7363 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7364 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7365 SDValue OutOps[] = { OutLo, OutHi };
7366 return DAG.getMergeValues(OutOps, dl);
7369 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7370 EVT VT = Op.getValueType();
7372 unsigned BitWidth = VT.getSizeInBits();
7373 assert(Op.getNumOperands() == 3 &&
7374 VT == Op.getOperand(1).getValueType() &&
7377 // Expand into a bunch of logical ops. Note that these ops
7378 // depend on the PPC behavior for oversized shift amounts.
7379 SDValue Lo = Op.getOperand(0);
7380 SDValue Hi = Op.getOperand(1);
7381 SDValue Amt = Op.getOperand(2);
7382 EVT AmtVT = Amt.getValueType();
7384 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7385 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7386 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7387 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7388 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7389 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7390 DAG.getConstant(-BitWidth, dl, AmtVT));
7391 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7392 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7393 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7394 SDValue OutOps[] = { OutLo, OutHi };
7395 return DAG.getMergeValues(OutOps, dl);
7398 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7400 EVT VT = Op.getValueType();
7401 unsigned BitWidth = VT.getSizeInBits();
7402 assert(Op.getNumOperands() == 3 &&
7403 VT == Op.getOperand(1).getValueType() &&
7406 // Expand into a bunch of logical ops, followed by a select_cc.
7407 SDValue Lo = Op.getOperand(0);
7408 SDValue Hi = Op.getOperand(1);
7409 SDValue Amt = Op.getOperand(2);
7410 EVT AmtVT = Amt.getValueType();
7412 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7413 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7414 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7415 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7416 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7417 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7418 DAG.getConstant(-BitWidth, dl, AmtVT));
7419 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7420 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7421 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7422 Tmp4, Tmp6, ISD::SETLE);
7423 SDValue OutOps[] = { OutLo, OutHi };
7424 return DAG.getMergeValues(OutOps, dl);
7427 //===----------------------------------------------------------------------===//
7428 // Vector related lowering.
7431 /// BuildSplatI - Build a canonical splati of Val with an element size of
7432 /// SplatSize. Cast the result to VT.
7433 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7434 SelectionDAG &DAG, const SDLoc &dl) {
7435 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7437 static const MVT VTys[] = { // canonical VT to use for each size.
7438 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7441 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7443 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7447 EVT CanonicalVT = VTys[SplatSize-1];
7449 // Build a canonical splat for this value.
7450 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7453 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7454 /// specified intrinsic ID.
7455 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7456 const SDLoc &dl, EVT DestVT = MVT::Other) {
7457 if (DestVT == MVT::Other) DestVT = Op.getValueType();
7458 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7459 DAG.getConstant(IID, dl, MVT::i32), Op);
7462 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7463 /// specified intrinsic ID.
7464 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7465 SelectionDAG &DAG, const SDLoc &dl,
7466 EVT DestVT = MVT::Other) {
7467 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7468 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7469 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7472 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7473 /// specified intrinsic ID.
7474 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7475 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7476 EVT DestVT = MVT::Other) {
7477 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7478 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7479 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7482 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7483 /// amount. The result has the specified value type.
7484 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7485 SelectionDAG &DAG, const SDLoc &dl) {
7486 // Force LHS/RHS to be the right type.
7487 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7488 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7491 for (unsigned i = 0; i != 16; ++i)
7493 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7494 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7497 /// Do we have an efficient pattern in a .td file for this node?
7499 /// \param V - pointer to the BuildVectorSDNode being matched
7500 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7502 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7503 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7504 /// the opposite is true (expansion is beneficial) are:
7505 /// - The node builds a vector out of integers that are not 32 or 64-bits
7506 /// - The node builds a vector out of constants
7507 /// - The node is a "load-and-splat"
7508 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7509 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7512 EVT VecVT = V->getValueType(0);
7513 bool RightType = VecVT == MVT::v2f64 ||
7514 (HasP8Vector && VecVT == MVT::v4f32) ||
7515 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7519 bool IsSplat = true;
7520 bool IsLoad = false;
7521 SDValue Op0 = V->getOperand(0);
7523 // This function is called in a block that confirms the node is not a constant
7524 // splat. So a constant BUILD_VECTOR here means the vector is built out of
7525 // different constants.
7526 if (V->isConstant())
7528 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7529 if (V->getOperand(i).isUndef())
7531 // We want to expand nodes that represent load-and-splat even if the
7532 // loaded value is a floating point truncation or conversion to int.
7533 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7534 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7535 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7536 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7537 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7538 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7539 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7541 // If the operands are different or the input is not a load and has more
7542 // uses than just this BV node, then it isn't a splat.
7543 if (V->getOperand(i) != Op0 ||
7544 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7547 return !(IsSplat && IsLoad);
7550 // If this is a case we can't handle, return null and let the default
7551 // expansion code take care of it. If we CAN select this case, and if it
7552 // selects to a single instruction, return Op. Otherwise, if we can codegen
7553 // this case more efficiently than a constant pool load, lower it to the
7554 // sequence of ops that should be used.
7555 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7556 SelectionDAG &DAG) const {
7558 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7559 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7561 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7562 // We first build an i32 vector, load it into a QPX register,
7563 // then convert it to a floating-point vector and compare it
7564 // to a zero vector to get the boolean result.
7565 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7566 int FrameIdx = MFI.CreateStackObject(16, 16, false);
7567 MachinePointerInfo PtrInfo =
7568 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7569 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7570 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7572 assert(BVN->getNumOperands() == 4 &&
7573 "BUILD_VECTOR for v4i1 does not have 4 operands");
7575 bool IsConst = true;
7576 for (unsigned i = 0; i < 4; ++i) {
7577 if (BVN->getOperand(i).isUndef()) continue;
7578 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7586 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7588 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7591 for (unsigned i = 0; i < 4; ++i) {
7592 if (BVN->getOperand(i).isUndef())
7593 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7594 else if (isNullConstant(BVN->getOperand(i)))
7600 Constant *CP = ConstantVector::get(CV);
7601 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7602 16 /* alignment */);
7604 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7605 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7606 return DAG.getMemIntrinsicNode(
7607 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7608 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7611 SmallVector<SDValue, 4> Stores;
7612 for (unsigned i = 0; i < 4; ++i) {
7613 if (BVN->getOperand(i).isUndef()) continue;
7615 unsigned Offset = 4*i;
7616 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7617 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7619 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7620 if (StoreSize > 4) {
7622 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7623 PtrInfo.getWithOffset(Offset), MVT::i32));
7625 SDValue StoreValue = BVN->getOperand(i);
7627 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7629 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7630 PtrInfo.getWithOffset(Offset)));
7635 if (!Stores.empty())
7636 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7638 StoreChain = DAG.getEntryNode();
7640 // Now load from v4i32 into the QPX register; this will extend it to
7641 // v4i64 but not yet convert it to a floating point. Nevertheless, this
7642 // is typed as v4f64 because the QPX register integer states are not
7643 // explicitly represented.
7645 SDValue Ops[] = {StoreChain,
7646 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7648 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7650 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7651 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7652 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7653 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7656 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7658 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7661 // All other QPX vectors are handled by generic code.
7662 if (Subtarget.hasQPX())
7665 // Check if this is a splat of a constant value.
7666 APInt APSplatBits, APSplatUndef;
7667 unsigned SplatBitSize;
7669 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7670 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7671 SplatBitSize > 32) {
7672 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7673 // lowered to VSX instructions under certain conditions.
7674 // Without VSX, there is no pattern more efficient than expanding the node.
7675 if (Subtarget.hasVSX() &&
7676 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
7677 Subtarget.hasP8Vector()))
7682 unsigned SplatBits = APSplatBits.getZExtValue();
7683 unsigned SplatUndef = APSplatUndef.getZExtValue();
7684 unsigned SplatSize = SplatBitSize / 8;
7686 // First, handle single instruction cases.
7689 if (SplatBits == 0) {
7690 // Canonicalize all zero vectors to be v4i32.
7691 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7692 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7693 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7698 // We have XXSPLTIB for constant splats one byte wide
7699 if (Subtarget.hasP9Vector() && SplatSize == 1) {
7700 // This is a splat of 1-byte elements with some elements potentially undef.
7701 // Rather than trying to match undef in the SDAG patterns, ensure that all
7702 // elements are the same constant.
7703 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7704 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7706 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7707 if (Op.getValueType() != MVT::v16i8)
7708 return DAG.getBitcast(Op.getValueType(), NewBV);
7712 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
7713 // detect that constant splats like v8i16: 0xABAB are really just splats
7714 // of a 1-byte constant. In this case, we need to convert the node to a
7715 // splat of v16i8 and a bitcast.
7716 if (Op.getValueType() != MVT::v16i8)
7717 return DAG.getBitcast(Op.getValueType(),
7718 DAG.getConstant(SplatBits, dl, MVT::v16i8));
7723 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7724 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7726 if (SextVal >= -16 && SextVal <= 15)
7727 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7729 // Two instruction sequences.
7731 // If this value is in the range [-32,30] and is even, use:
7732 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7733 // If this value is in the range [17,31] and is odd, use:
7734 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7735 // If this value is in the range [-31,-17] and is odd, use:
7736 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7737 // Note the last two are three-instruction sequences.
7738 if (SextVal >= -32 && SextVal <= 31) {
7739 // To avoid having these optimizations undone by constant folding,
7740 // we convert to a pseudo that will be expanded later into one of
7742 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7743 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7744 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7745 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7746 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7747 if (VT == Op.getValueType())
7750 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7753 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
7754 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
7756 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7757 // Make -1 and vspltisw -1:
7758 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7760 // Make the VSLW intrinsic, computing 0x8000_0000.
7761 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7764 // xor by OnesV to invert it.
7765 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7766 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7769 // Check to see if this is a wide variety of vsplti*, binop self cases.
7770 static const signed char SplatCsts[] = {
7771 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7772 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7775 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7776 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7777 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
7778 int i = SplatCsts[idx];
7780 // Figure out what shift amount will be used by altivec if shifted by i in
7782 unsigned TypeShiftAmt = i & (SplatBitSize-1);
7784 // vsplti + shl self.
7785 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7786 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7787 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7788 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7789 Intrinsic::ppc_altivec_vslw
7791 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7792 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7795 // vsplti + srl self.
7796 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7797 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7798 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7799 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7800 Intrinsic::ppc_altivec_vsrw
7802 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7803 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7806 // vsplti + sra self.
7807 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7808 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7809 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7810 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7811 Intrinsic::ppc_altivec_vsraw
7813 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7814 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7817 // vsplti + rol self.
7818 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7819 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7820 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7821 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7822 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7823 Intrinsic::ppc_altivec_vrlw
7825 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7826 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7829 // t = vsplti c, result = vsldoi t, t, 1
7830 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7831 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7832 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7833 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7835 // t = vsplti c, result = vsldoi t, t, 2
7836 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7837 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7838 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7839 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7841 // t = vsplti c, result = vsldoi t, t, 3
7842 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7843 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7844 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7845 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7852 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7853 /// the specified operations to build the shuffle.
7854 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7855 SDValue RHS, SelectionDAG &DAG,
7857 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7858 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7859 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7862 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7874 if (OpNum == OP_COPY) {
7875 if (LHSID == (1*9+2)*9+3) return LHS;
7876 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7880 SDValue OpLHS, OpRHS;
7881 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7882 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7886 default: llvm_unreachable("Unknown i32 permute!");
7888 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
7889 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7890 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
7891 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7894 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7895 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7896 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7897 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7900 for (unsigned i = 0; i != 16; ++i)
7901 ShufIdxs[i] = (i&3)+0;
7904 for (unsigned i = 0; i != 16; ++i)
7905 ShufIdxs[i] = (i&3)+4;
7908 for (unsigned i = 0; i != 16; ++i)
7909 ShufIdxs[i] = (i&3)+8;
7912 for (unsigned i = 0; i != 16; ++i)
7913 ShufIdxs[i] = (i&3)+12;
7916 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7918 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7920 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7922 EVT VT = OpLHS.getValueType();
7923 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7924 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7925 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7926 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7929 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
7930 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
7932 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
7933 SelectionDAG &DAG) const {
7934 const unsigned BytesInVector = 16;
7935 bool IsLE = Subtarget.isLittleEndian();
7937 SDValue V1 = N->getOperand(0);
7938 SDValue V2 = N->getOperand(1);
7939 unsigned ShiftElts = 0, InsertAtByte = 0;
7942 // Shifts required to get the byte we want at element 7.
7943 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1,
7944 0, 15, 14, 13, 12, 11, 10, 9};
7945 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
7946 1, 2, 3, 4, 5, 6, 7, 8};
7948 ArrayRef<int> Mask = N->getMask();
7949 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
7951 // For each mask element, find out if we're just inserting something
7952 // from V2 into V1 or vice versa.
7953 // Possible permutations inserting an element from V2 into V1:
7954 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
7955 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
7957 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
7958 // Inserting from V1 into V2 will be similar, except mask range will be
7961 bool FoundCandidate = false;
7962 // If both vector operands for the shuffle are the same vector, the mask
7963 // will contain only elements from the first one and the second one will be
7965 unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
7966 // Go through the mask of half-words to find an element that's being moved
7967 // from one vector to the other.
7968 for (unsigned i = 0; i < BytesInVector; ++i) {
7969 unsigned CurrentElement = Mask[i];
7970 // If 2nd operand is undefined, we should only look for element 7 in the
7972 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
7975 bool OtherElementsInOrder = true;
7976 // Examine the other elements in the Mask to see if they're in original
7978 for (unsigned j = 0; j < BytesInVector; ++j) {
7981 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
7982 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined,
7983 // in which we always assume we're always picking from the 1st operand.
7985 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
7986 if (Mask[j] != OriginalOrder[j] + MaskOffset) {
7987 OtherElementsInOrder = false;
7991 // If other elements are in original order, we record the number of shifts
7992 // we need to get the element we want into element 7. Also record which byte
7993 // in the vector we should insert into.
7994 if (OtherElementsInOrder) {
7995 // If 2nd operand is undefined, we assume no shifts and no swapping.
8000 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8001 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8002 : BigEndianShifts[CurrentElement & 0xF];
8003 Swap = CurrentElement < BytesInVector;
8005 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8006 FoundCandidate = true;
8011 if (!FoundCandidate)
8014 // Candidate found, construct the proper SDAG sequence with VINSERTB,
8015 // optionally with VECSHL if shift is required.
8021 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8022 DAG.getConstant(ShiftElts, dl, MVT::i32));
8023 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8024 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8026 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8027 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8030 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8031 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8033 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8034 SelectionDAG &DAG) const {
8035 const unsigned NumHalfWords = 8;
8036 const unsigned BytesInVector = NumHalfWords * 2;
8037 // Check that the shuffle is on half-words.
8038 if (!isNByteElemShuffleMask(N, 2, 1))
8041 bool IsLE = Subtarget.isLittleEndian();
8043 SDValue V1 = N->getOperand(0);
8044 SDValue V2 = N->getOperand(1);
8045 unsigned ShiftElts = 0, InsertAtByte = 0;
8048 // Shifts required to get the half-word we want at element 3.
8049 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8050 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8053 uint32_t OriginalOrderLow = 0x1234567;
8054 uint32_t OriginalOrderHigh = 0x89ABCDEF;
8055 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a
8056 // 32-bit space, only need 4-bit nibbles per element.
8057 for (unsigned i = 0; i < NumHalfWords; ++i) {
8058 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8059 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8062 // For each mask element, find out if we're just inserting something
8063 // from V2 into V1 or vice versa. Possible permutations inserting an element
8065 // X, 1, 2, 3, 4, 5, 6, 7
8066 // 0, X, 2, 3, 4, 5, 6, 7
8067 // 0, 1, X, 3, 4, 5, 6, 7
8068 // 0, 1, 2, X, 4, 5, 6, 7
8069 // 0, 1, 2, 3, X, 5, 6, 7
8070 // 0, 1, 2, 3, 4, X, 6, 7
8071 // 0, 1, 2, 3, 4, 5, X, 7
8072 // 0, 1, 2, 3, 4, 5, 6, X
8073 // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8075 bool FoundCandidate = false;
8076 // Go through the mask of half-words to find an element that's being moved
8077 // from one vector to the other.
8078 for (unsigned i = 0; i < NumHalfWords; ++i) {
8079 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8080 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8081 uint32_t MaskOtherElts = ~(0xF << MaskShift);
8082 uint32_t TargetOrder = 0x0;
8084 // If both vector operands for the shuffle are the same vector, the mask
8085 // will contain only elements from the first one and the second one will be
8089 unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8090 TargetOrder = OriginalOrderLow;
8092 // Skip if not the correct element or mask of other elements don't equal
8093 // to our expected order.
8094 if (MaskOneElt == VINSERTHSrcElem &&
8095 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8096 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8097 FoundCandidate = true;
8100 } else { // If both operands are defined.
8101 // Target order is [8,15] if the current mask is between [0,7].
8103 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8104 // Skip if mask of other elements don't equal our expected order.
8105 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8106 // We only need the last 3 bits for the number of shifts.
8107 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8108 : BigEndianShifts[MaskOneElt & 0x7];
8109 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8110 Swap = MaskOneElt < NumHalfWords;
8111 FoundCandidate = true;
8117 if (!FoundCandidate)
8120 // Candidate found, construct the proper SDAG sequence with VINSERTH,
8121 // optionally with VECSHL if shift is required.
8126 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8128 // Double ShiftElts because we're left shifting on v16i8 type.
8129 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8130 DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8131 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8132 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8133 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8134 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8136 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8137 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8138 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8139 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8142 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
8143 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
8144 /// return the code it can be lowered into. Worst case, it can always be
8145 /// lowered into a vperm.
8146 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8147 SelectionDAG &DAG) const {
8149 SDValue V1 = Op.getOperand(0);
8150 SDValue V2 = Op.getOperand(1);
8151 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8152 EVT VT = Op.getValueType();
8153 bool isLittleEndian = Subtarget.isLittleEndian();
8155 unsigned ShiftElts, InsertAtByte;
8157 if (Subtarget.hasP9Vector() &&
8158 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8162 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8163 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8165 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8166 DAG.getConstant(ShiftElts, dl, MVT::i32));
8167 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8168 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8169 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8171 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8172 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8173 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8176 if (Subtarget.hasP9Altivec()) {
8178 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8181 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8185 if (Subtarget.hasVSX() &&
8186 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8189 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8191 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8193 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8194 DAG.getConstant(ShiftElts, dl, MVT::i32));
8195 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8198 if (Subtarget.hasVSX() &&
8199 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8202 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8204 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8206 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8207 DAG.getConstant(ShiftElts, dl, MVT::i32));
8208 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8211 if (Subtarget.hasP9Vector()) {
8212 if (PPC::isXXBRHShuffleMask(SVOp)) {
8213 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8214 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8215 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8216 } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8217 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8218 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8219 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8220 } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8221 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8222 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8223 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8224 } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8225 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8226 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8227 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8231 if (Subtarget.hasVSX()) {
8232 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8233 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8235 // If the source for the shuffle is a scalar_to_vector that came from a
8236 // 32-bit load, it will have used LXVWSX so we don't need to splat again.
8237 if (Subtarget.hasP9Vector() &&
8238 ((isLittleEndian && SplatIdx == 3) ||
8239 (!isLittleEndian && SplatIdx == 0))) {
8240 SDValue Src = V1.getOperand(0);
8241 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8242 Src.getOperand(0).getOpcode() == ISD::LOAD &&
8243 Src.getOperand(0).hasOneUse())
8246 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8247 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8248 DAG.getConstant(SplatIdx, dl, MVT::i32));
8249 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8252 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8253 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8254 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8255 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8256 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8260 if (Subtarget.hasQPX()) {
8261 if (VT.getVectorNumElements() != 4)
8264 if (V2.isUndef()) V2 = V1;
8266 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8267 if (AlignIdx != -1) {
8268 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8269 DAG.getConstant(AlignIdx, dl, MVT::i32));
8270 } else if (SVOp->isSplat()) {
8271 int SplatIdx = SVOp->getSplatIndex();
8272 if (SplatIdx >= 4) {
8277 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8278 DAG.getConstant(SplatIdx, dl, MVT::i32));
8281 // Lower this into a qvgpci/qvfperm pair.
8283 // Compute the qvgpci literal
8285 for (unsigned i = 0; i < 4; ++i) {
8286 int m = SVOp->getMaskElt(i);
8287 unsigned mm = m >= 0 ? (unsigned) m : i;
8288 idx |= mm << (3-i)*3;
8291 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8292 DAG.getConstant(idx, dl, MVT::i32));
8293 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8296 // Cases that are handled by instructions that take permute immediates
8297 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8298 // selected by the instruction selector.
8300 if (PPC::isSplatShuffleMask(SVOp, 1) ||
8301 PPC::isSplatShuffleMask(SVOp, 2) ||
8302 PPC::isSplatShuffleMask(SVOp, 4) ||
8303 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8304 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8305 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8306 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8307 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8308 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8309 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8310 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8311 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8312 (Subtarget.hasP8Altivec() && (
8313 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8314 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8315 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8320 // Altivec has a variety of "shuffle immediates" that take two vector inputs
8321 // and produce a fixed permutation. If any of these match, do not lower to
8323 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8324 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8325 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8326 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8327 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8328 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8329 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8330 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8331 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8332 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8333 (Subtarget.hasP8Altivec() && (
8334 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8335 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8336 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8339 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
8340 // perfect shuffle table to emit an optimal matching sequence.
8341 ArrayRef<int> PermMask = SVOp->getMask();
8343 unsigned PFIndexes[4];
8344 bool isFourElementShuffle = true;
8345 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8346 unsigned EltNo = 8; // Start out undef.
8347 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
8348 if (PermMask[i*4+j] < 0)
8349 continue; // Undef, ignore it.
8351 unsigned ByteSource = PermMask[i*4+j];
8352 if ((ByteSource & 3) != j) {
8353 isFourElementShuffle = false;
8358 EltNo = ByteSource/4;
8359 } else if (EltNo != ByteSource/4) {
8360 isFourElementShuffle = false;
8364 PFIndexes[i] = EltNo;
8367 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8368 // perfect shuffle vector to determine if it is cost effective to do this as
8369 // discrete instructions, or whether we should use a vperm.
8370 // For now, we skip this for little endian until such time as we have a
8371 // little-endian perfect shuffle table.
8372 if (isFourElementShuffle && !isLittleEndian) {
8373 // Compute the index in the perfect shuffle table.
8374 unsigned PFTableIndex =
8375 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8377 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8378 unsigned Cost = (PFEntry >> 30);
8380 // Determining when to avoid vperm is tricky. Many things affect the cost
8381 // of vperm, particularly how many times the perm mask needs to be computed.
8382 // For example, if the perm mask can be hoisted out of a loop or is already
8383 // used (perhaps because there are multiple permutes with the same shuffle
8384 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
8385 // the loop requires an extra register.
8387 // As a compromise, we only emit discrete instructions if the shuffle can be
8388 // generated in 3 or fewer operations. When we have loop information
8389 // available, if this block is within a loop, we should avoid using vperm
8390 // for 3-operation perms and use a constant pool load instead.
8392 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8395 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8396 // vector that will get spilled to the constant pool.
8397 if (V2.isUndef()) V2 = V1;
8399 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8400 // that it is in input element units, not in bytes. Convert now.
8402 // For little endian, the order of the input vectors is reversed, and
8403 // the permutation mask is complemented with respect to 31. This is
8404 // necessary to produce proper semantics with the big-endian-biased vperm
8406 EVT EltVT = V1.getValueType().getVectorElementType();
8407 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8409 SmallVector<SDValue, 16> ResultMask;
8410 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8411 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8413 for (unsigned j = 0; j != BytesPerElement; ++j)
8415 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8418 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8422 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8424 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8427 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8431 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8432 /// vector comparison. If it is, return true and fill in Opc/isDot with
8433 /// information about the intrinsic.
8434 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8435 bool &isDot, const PPCSubtarget &Subtarget) {
8436 unsigned IntrinsicID =
8437 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8440 switch (IntrinsicID) {
8443 // Comparison predicates.
8444 case Intrinsic::ppc_altivec_vcmpbfp_p:
8448 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8452 case Intrinsic::ppc_altivec_vcmpequb_p:
8456 case Intrinsic::ppc_altivec_vcmpequh_p:
8460 case Intrinsic::ppc_altivec_vcmpequw_p:
8464 case Intrinsic::ppc_altivec_vcmpequd_p:
8465 if (Subtarget.hasP8Altivec()) {
8471 case Intrinsic::ppc_altivec_vcmpneb_p:
8472 case Intrinsic::ppc_altivec_vcmpneh_p:
8473 case Intrinsic::ppc_altivec_vcmpnew_p:
8474 case Intrinsic::ppc_altivec_vcmpnezb_p:
8475 case Intrinsic::ppc_altivec_vcmpnezh_p:
8476 case Intrinsic::ppc_altivec_vcmpnezw_p:
8477 if (Subtarget.hasP9Altivec()) {
8478 switch (IntrinsicID) {
8480 llvm_unreachable("Unknown comparison intrinsic.");
8481 case Intrinsic::ppc_altivec_vcmpneb_p:
8484 case Intrinsic::ppc_altivec_vcmpneh_p:
8487 case Intrinsic::ppc_altivec_vcmpnew_p:
8490 case Intrinsic::ppc_altivec_vcmpnezb_p:
8493 case Intrinsic::ppc_altivec_vcmpnezh_p:
8496 case Intrinsic::ppc_altivec_vcmpnezw_p:
8504 case Intrinsic::ppc_altivec_vcmpgefp_p:
8508 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8512 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8516 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8520 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8524 case Intrinsic::ppc_altivec_vcmpgtsd_p:
8525 if (Subtarget.hasP8Altivec()) {
8531 case Intrinsic::ppc_altivec_vcmpgtub_p:
8535 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8539 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8543 case Intrinsic::ppc_altivec_vcmpgtud_p:
8544 if (Subtarget.hasP8Altivec()) {
8551 // VSX predicate comparisons use the same infrastructure
8552 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8553 case Intrinsic::ppc_vsx_xvcmpgedp_p:
8554 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8555 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8556 case Intrinsic::ppc_vsx_xvcmpgesp_p:
8557 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8558 if (Subtarget.hasVSX()) {
8559 switch (IntrinsicID) {
8560 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8563 case Intrinsic::ppc_vsx_xvcmpgedp_p:
8566 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8569 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8572 case Intrinsic::ppc_vsx_xvcmpgesp_p:
8575 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8584 // Normal Comparisons.
8585 case Intrinsic::ppc_altivec_vcmpbfp:
8588 case Intrinsic::ppc_altivec_vcmpeqfp:
8591 case Intrinsic::ppc_altivec_vcmpequb:
8594 case Intrinsic::ppc_altivec_vcmpequh:
8597 case Intrinsic::ppc_altivec_vcmpequw:
8600 case Intrinsic::ppc_altivec_vcmpequd:
8601 if (Subtarget.hasP8Altivec())
8606 case Intrinsic::ppc_altivec_vcmpneb:
8607 case Intrinsic::ppc_altivec_vcmpneh:
8608 case Intrinsic::ppc_altivec_vcmpnew:
8609 case Intrinsic::ppc_altivec_vcmpnezb:
8610 case Intrinsic::ppc_altivec_vcmpnezh:
8611 case Intrinsic::ppc_altivec_vcmpnezw:
8612 if (Subtarget.hasP9Altivec())
8613 switch (IntrinsicID) {
8615 llvm_unreachable("Unknown comparison intrinsic.");
8616 case Intrinsic::ppc_altivec_vcmpneb:
8619 case Intrinsic::ppc_altivec_vcmpneh:
8622 case Intrinsic::ppc_altivec_vcmpnew:
8625 case Intrinsic::ppc_altivec_vcmpnezb:
8628 case Intrinsic::ppc_altivec_vcmpnezh:
8631 case Intrinsic::ppc_altivec_vcmpnezw:
8638 case Intrinsic::ppc_altivec_vcmpgefp:
8641 case Intrinsic::ppc_altivec_vcmpgtfp:
8644 case Intrinsic::ppc_altivec_vcmpgtsb:
8647 case Intrinsic::ppc_altivec_vcmpgtsh:
8650 case Intrinsic::ppc_altivec_vcmpgtsw:
8653 case Intrinsic::ppc_altivec_vcmpgtsd:
8654 if (Subtarget.hasP8Altivec())
8659 case Intrinsic::ppc_altivec_vcmpgtub:
8662 case Intrinsic::ppc_altivec_vcmpgtuh:
8665 case Intrinsic::ppc_altivec_vcmpgtuw:
8668 case Intrinsic::ppc_altivec_vcmpgtud:
8669 if (Subtarget.hasP8Altivec())
8678 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8679 /// lower, do it, otherwise return null.
8680 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8681 SelectionDAG &DAG) const {
8682 unsigned IntrinsicID =
8683 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8687 if (IntrinsicID == Intrinsic::thread_pointer) {
8688 // Reads the thread pointer register, used for __builtin_thread_pointer.
8689 if (Subtarget.isPPC64())
8690 return DAG.getRegister(PPC::X13, MVT::i64);
8691 return DAG.getRegister(PPC::R2, MVT::i32);
8694 // We are looking for absolute values here.
8695 // The idea is to try to fit one of two patterns:
8696 // max (a, (0-a)) OR max ((0-a), a)
8697 if (Subtarget.hasP9Vector() &&
8698 (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw ||
8699 IntrinsicID == Intrinsic::ppc_altivec_vmaxsh ||
8700 IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) {
8701 SDValue V1 = Op.getOperand(1);
8702 SDValue V2 = Op.getOperand(2);
8703 if (V1.getSimpleValueType() == V2.getSimpleValueType() &&
8704 (V1.getSimpleValueType() == MVT::v4i32 ||
8705 V1.getSimpleValueType() == MVT::v8i16 ||
8706 V1.getSimpleValueType() == MVT::v16i8)) {
8707 if ( V1.getOpcode() == ISD::SUB &&
8708 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
8709 V1.getOperand(1) == V2 ) {
8710 // Generate the abs instruction with the operands
8711 return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2);
8714 if ( V2.getOpcode() == ISD::SUB &&
8715 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
8716 V2.getOperand(1) == V1 ) {
8717 // Generate the abs instruction with the operands
8718 return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1);
8723 // If this is a lowered altivec predicate compare, CompareOpc is set to the
8724 // opcode number of the comparison.
8727 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8728 return SDValue(); // Don't custom lower most intrinsics.
8730 // If this is a non-dot comparison, make the VCMP node and we are done.
8732 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8733 Op.getOperand(1), Op.getOperand(2),
8734 DAG.getConstant(CompareOpc, dl, MVT::i32));
8735 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8738 // Create the PPCISD altivec 'dot' comparison node.
8740 Op.getOperand(2), // LHS
8741 Op.getOperand(3), // RHS
8742 DAG.getConstant(CompareOpc, dl, MVT::i32)
8744 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8745 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8747 // Now that we have the comparison, emit a copy from the CR to a GPR.
8748 // This is flagged to the above dot comparison.
8749 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8750 DAG.getRegister(PPC::CR6, MVT::i32),
8751 CompNode.getValue(1));
8753 // Unpack the result based on how the target uses it.
8754 unsigned BitNo; // Bit # of CR6.
8755 bool InvertBit; // Invert result?
8756 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8757 default: // Can't happen, don't crash on invalid number though.
8758 case 0: // Return the value of the EQ bit of CR6.
8759 BitNo = 0; InvertBit = false;
8761 case 1: // Return the inverted value of the EQ bit of CR6.
8762 BitNo = 0; InvertBit = true;
8764 case 2: // Return the value of the LT bit of CR6.
8765 BitNo = 2; InvertBit = false;
8767 case 3: // Return the inverted value of the LT bit of CR6.
8768 BitNo = 2; InvertBit = true;
8772 // Shift the bit into the low position.
8773 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8774 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8776 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8777 DAG.getConstant(1, dl, MVT::i32));
8779 // If we are supposed to, toggle the bit.
8781 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8782 DAG.getConstant(1, dl, MVT::i32));
8786 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8787 SelectionDAG &DAG) const {
8788 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8789 // the beginning of the argument list.
8790 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8792 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8793 case Intrinsic::ppc_cfence: {
8794 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
8795 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8796 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8797 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8798 Op.getOperand(ArgStart + 1)),
8808 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
8809 // Check for a DIV with the same operands as this REM.
8810 for (auto UI : Op.getOperand(1)->uses()) {
8811 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
8812 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
8813 if (UI->getOperand(0) == Op.getOperand(0) &&
8814 UI->getOperand(1) == Op.getOperand(1))
8820 // Lower scalar BSWAP64 to xxbrd.
8821 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
8824 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
8827 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
8829 int VectorIndex = 0;
8830 if (Subtarget.isLittleEndian())
8832 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
8833 DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
8837 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8838 SelectionDAG &DAG) const {
8840 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8841 // instructions), but for smaller types, we need to first extend up to v2i32
8842 // before doing going farther.
8843 if (Op.getValueType() == MVT::v2i64) {
8844 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8845 if (ExtVT != MVT::v2i32) {
8846 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8847 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8848 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8849 ExtVT.getVectorElementType(), 4)));
8850 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8851 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8852 DAG.getValueType(MVT::v2i32));
8861 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8862 SelectionDAG &DAG) const {
8864 // Create a stack slot that is 16-byte aligned.
8865 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8866 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8867 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8868 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8870 // Store the input value into Value#0 of the stack slot.
8871 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8872 MachinePointerInfo());
8874 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8877 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8878 SelectionDAG &DAG) const {
8879 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8880 "Should only be called for ISD::INSERT_VECTOR_ELT");
8882 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8883 // We have legal lowering for constant indices but not for variable ones.
8887 EVT VT = Op.getValueType();
8889 SDValue V1 = Op.getOperand(0);
8890 SDValue V2 = Op.getOperand(1);
8891 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
8892 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
8893 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
8894 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
8895 unsigned InsertAtElement = C->getZExtValue();
8896 unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
8897 if (Subtarget.isLittleEndian()) {
8898 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
8900 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
8901 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8906 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8907 SelectionDAG &DAG) const {
8909 SDNode *N = Op.getNode();
8911 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8912 "Unknown extract_vector_elt type");
8914 SDValue Value = N->getOperand(0);
8916 // The first part of this is like the store lowering except that we don't
8917 // need to track the chain.
8919 // The values are now known to be -1 (false) or 1 (true). To convert this
8920 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8921 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8922 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8924 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8925 // understand how to form the extending load.
8926 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8928 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8930 // Now convert to an integer and store.
8931 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8932 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8935 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8936 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8937 MachinePointerInfo PtrInfo =
8938 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8939 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8940 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8942 SDValue StoreChain = DAG.getEntryNode();
8943 SDValue Ops[] = {StoreChain,
8944 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8946 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8948 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8949 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8951 // Extract the value requested.
8952 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8953 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8954 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8957 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8959 if (!Subtarget.useCRBits())
8962 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8965 /// Lowering for QPX v4i1 loads
8966 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8967 SelectionDAG &DAG) const {
8969 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8970 SDValue LoadChain = LN->getChain();
8971 SDValue BasePtr = LN->getBasePtr();
8973 if (Op.getValueType() == MVT::v4f64 ||
8974 Op.getValueType() == MVT::v4f32) {
8975 EVT MemVT = LN->getMemoryVT();
8976 unsigned Alignment = LN->getAlignment();
8978 // If this load is properly aligned, then it is legal.
8979 if (Alignment >= MemVT.getStoreSize())
8982 EVT ScalarVT = Op.getValueType().getScalarType(),
8983 ScalarMemVT = MemVT.getScalarType();
8984 unsigned Stride = ScalarMemVT.getStoreSize();
8986 SDValue Vals[4], LoadChains[4];
8987 for (unsigned Idx = 0; Idx < 4; ++Idx) {
8989 if (ScalarVT != ScalarMemVT)
8990 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8992 LN->getPointerInfo().getWithOffset(Idx * Stride),
8993 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8994 LN->getMemOperand()->getFlags(), LN->getAAInfo());
8996 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8997 LN->getPointerInfo().getWithOffset(Idx * Stride),
8998 MinAlign(Alignment, Idx * Stride),
8999 LN->getMemOperand()->getFlags(), LN->getAAInfo());
9001 if (Idx == 0 && LN->isIndexed()) {
9002 assert(LN->getAddressingMode() == ISD::PRE_INC &&
9003 "Unknown addressing mode on vector load");
9004 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9005 LN->getAddressingMode());
9009 LoadChains[Idx] = Load.getValue(1);
9011 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9012 DAG.getConstant(Stride, dl,
9013 BasePtr.getValueType()));
9016 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9017 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9019 if (LN->isIndexed()) {
9020 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9021 return DAG.getMergeValues(RetOps, dl);
9024 SDValue RetOps[] = { Value, TF };
9025 return DAG.getMergeValues(RetOps, dl);
9028 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9029 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9031 // To lower v4i1 from a byte array, we load the byte elements of the
9032 // vector and then reuse the BUILD_VECTOR logic.
9034 SDValue VectElmts[4], VectElmtChains[4];
9035 for (unsigned i = 0; i < 4; ++i) {
9036 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9037 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9039 VectElmts[i] = DAG.getExtLoad(
9040 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9041 LN->getPointerInfo().getWithOffset(i), MVT::i8,
9042 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9043 VectElmtChains[i] = VectElmts[i].getValue(1);
9046 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9047 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9049 SDValue RVals[] = { Value, LoadChain };
9050 return DAG.getMergeValues(RVals, dl);
9053 /// Lowering for QPX v4i1 stores
9054 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9055 SelectionDAG &DAG) const {
9057 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9058 SDValue StoreChain = SN->getChain();
9059 SDValue BasePtr = SN->getBasePtr();
9060 SDValue Value = SN->getValue();
9062 if (Value.getValueType() == MVT::v4f64 ||
9063 Value.getValueType() == MVT::v4f32) {
9064 EVT MemVT = SN->getMemoryVT();
9065 unsigned Alignment = SN->getAlignment();
9067 // If this store is properly aligned, then it is legal.
9068 if (Alignment >= MemVT.getStoreSize())
9071 EVT ScalarVT = Value.getValueType().getScalarType(),
9072 ScalarMemVT = MemVT.getScalarType();
9073 unsigned Stride = ScalarMemVT.getStoreSize();
9076 for (unsigned Idx = 0; Idx < 4; ++Idx) {
9077 SDValue Ex = DAG.getNode(
9078 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9079 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9081 if (ScalarVT != ScalarMemVT)
9083 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9084 SN->getPointerInfo().getWithOffset(Idx * Stride),
9085 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9086 SN->getMemOperand()->getFlags(), SN->getAAInfo());
9088 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9089 SN->getPointerInfo().getWithOffset(Idx * Stride),
9090 MinAlign(Alignment, Idx * Stride),
9091 SN->getMemOperand()->getFlags(), SN->getAAInfo());
9093 if (Idx == 0 && SN->isIndexed()) {
9094 assert(SN->getAddressingMode() == ISD::PRE_INC &&
9095 "Unknown addressing mode on vector store");
9096 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9097 SN->getAddressingMode());
9100 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9101 DAG.getConstant(Stride, dl,
9102 BasePtr.getValueType()));
9103 Stores[Idx] = Store;
9106 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9108 if (SN->isIndexed()) {
9109 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9110 return DAG.getMergeValues(RetOps, dl);
9116 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9117 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9119 // The values are now known to be -1 (false) or 1 (true). To convert this
9120 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9121 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9122 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9124 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9125 // understand how to form the extending load.
9126 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9128 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9130 // Now convert to an integer and store.
9131 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9132 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9135 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9136 int FrameIdx = MFI.CreateStackObject(16, 16, false);
9137 MachinePointerInfo PtrInfo =
9138 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9139 EVT PtrVT = getPointerTy(DAG.getDataLayout());
9140 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9142 SDValue Ops[] = {StoreChain,
9143 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9145 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9147 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9148 dl, VTs, Ops, MVT::v4i32, PtrInfo);
9150 // Move data into the byte array.
9151 SDValue Loads[4], LoadChains[4];
9152 for (unsigned i = 0; i < 4; ++i) {
9153 unsigned Offset = 4*i;
9154 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9155 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9157 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9158 PtrInfo.getWithOffset(Offset));
9159 LoadChains[i] = Loads[i].getValue(1);
9162 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9165 for (unsigned i = 0; i < 4; ++i) {
9166 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9167 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9169 Stores[i] = DAG.getTruncStore(
9170 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9171 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9175 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9180 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9182 if (Op.getValueType() == MVT::v4i32) {
9183 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9185 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
9186 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9188 SDValue RHSSwap = // = vrlw RHS, 16
9189 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9191 // Shrinkify inputs to v8i16.
9192 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9193 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9194 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9196 // Low parts multiplied together, generating 32-bit results (we ignore the
9198 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9199 LHS, RHS, DAG, dl, MVT::v4i32);
9201 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9202 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9203 // Shift the high parts up 16 bits.
9204 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9206 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9207 } else if (Op.getValueType() == MVT::v8i16) {
9208 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9210 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9212 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9213 LHS, RHS, Zero, DAG, dl);
9214 } else if (Op.getValueType() == MVT::v16i8) {
9215 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9216 bool isLittleEndian = Subtarget.isLittleEndian();
9218 // Multiply the even 8-bit parts, producing 16-bit sums.
9219 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9220 LHS, RHS, DAG, dl, MVT::v8i16);
9221 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9223 // Multiply the odd 8-bit parts, producing 16-bit sums.
9224 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9225 LHS, RHS, DAG, dl, MVT::v8i16);
9226 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9228 // Merge the results together. Because vmuleub and vmuloub are
9229 // instructions with a big-endian bias, we must reverse the
9230 // element numbering and reverse the meaning of "odd" and "even"
9231 // when generating little endian code.
9233 for (unsigned i = 0; i != 8; ++i) {
9234 if (isLittleEndian) {
9236 Ops[i*2+1] = 2*i+16;
9239 Ops[i*2+1] = 2*i+1+16;
9243 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9245 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9247 llvm_unreachable("Unknown mul to lower!");
9251 /// LowerOperation - Provide custom lowering hooks for some operations.
9253 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9254 switch (Op.getOpcode()) {
9255 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9256 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9257 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9258 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9259 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9260 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9261 case ISD::SETCC: return LowerSETCC(Op, DAG);
9262 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
9263 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
9265 return LowerVASTART(Op, DAG);
9268 return LowerVAARG(Op, DAG);
9271 return LowerVACOPY(Op, DAG);
9273 case ISD::STACKRESTORE:
9274 return LowerSTACKRESTORE(Op, DAG);
9276 case ISD::DYNAMIC_STACKALLOC:
9277 return LowerDYNAMIC_STACKALLOC(Op, DAG);
9279 case ISD::GET_DYNAMIC_AREA_OFFSET:
9280 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9282 case ISD::EH_DWARF_CFA:
9283 return LowerEH_DWARF_CFA(Op, DAG);
9285 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
9286 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
9288 case ISD::LOAD: return LowerLOAD(Op, DAG);
9289 case ISD::STORE: return LowerSTORE(Op, DAG);
9290 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
9291 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
9292 case ISD::FP_TO_UINT:
9293 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
9295 case ISD::UINT_TO_FP:
9296 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
9297 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9299 // Lower 64-bit shifts.
9300 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
9301 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
9302 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
9304 // Vector-related lowering.
9305 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9306 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9307 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9308 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9309 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
9310 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9311 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9312 case ISD::MUL: return LowerMUL(Op, DAG);
9314 // For counter-based loop handling.
9315 case ISD::INTRINSIC_W_CHAIN: return SDValue();
9317 // Frame & Return address.
9318 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9319 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9321 case ISD::INTRINSIC_VOID:
9322 return LowerINTRINSIC_VOID(Op, DAG);
9325 return LowerREM(Op, DAG);
9327 return LowerBSWAP(Op, DAG);
9331 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9332 SmallVectorImpl<SDValue>&Results,
9333 SelectionDAG &DAG) const {
9335 switch (N->getOpcode()) {
9337 llvm_unreachable("Do not know how to custom type legalize this operation!");
9338 case ISD::READCYCLECOUNTER: {
9339 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9340 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9342 Results.push_back(RTB);
9343 Results.push_back(RTB.getValue(1));
9344 Results.push_back(RTB.getValue(2));
9347 case ISD::INTRINSIC_W_CHAIN: {
9348 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9349 Intrinsic::ppc_is_decremented_ctr_nonzero)
9352 assert(N->getValueType(0) == MVT::i1 &&
9353 "Unexpected result type for CTR decrement intrinsic");
9354 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9355 N->getValueType(0));
9356 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9357 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9360 Results.push_back(NewInt);
9361 Results.push_back(NewInt.getValue(1));
9365 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9368 EVT VT = N->getValueType(0);
9370 if (VT == MVT::i64) {
9371 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9373 Results.push_back(NewNode);
9374 Results.push_back(NewNode.getValue(1));
9378 case ISD::FP_ROUND_INREG: {
9379 assert(N->getValueType(0) == MVT::ppcf128);
9380 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
9381 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
9382 MVT::f64, N->getOperand(0),
9383 DAG.getIntPtrConstant(0, dl));
9384 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
9385 MVT::f64, N->getOperand(0),
9386 DAG.getIntPtrConstant(1, dl));
9388 // Add the two halves of the long double in round-to-zero mode.
9389 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
9391 // We know the low half is about to be thrown away, so just use something
9393 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
9397 case ISD::FP_TO_SINT:
9398 case ISD::FP_TO_UINT:
9399 // LowerFP_TO_INT() can only handle f32 and f64.
9400 if (N->getOperand(0).getValueType() == MVT::ppcf128)
9402 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9407 //===----------------------------------------------------------------------===//
9408 // Other Lowering Code
9409 //===----------------------------------------------------------------------===//
9411 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
9412 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9413 Function *Func = Intrinsic::getDeclaration(M, Id);
9414 return Builder.CreateCall(Func, {});
9417 // The mappings for emitLeading/TrailingFence is taken from
9418 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
9419 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
9421 AtomicOrdering Ord) const {
9422 if (Ord == AtomicOrdering::SequentiallyConsistent)
9423 return callIntrinsic(Builder, Intrinsic::ppc_sync);
9424 if (isReleaseOrStronger(Ord))
9425 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9429 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
9431 AtomicOrdering Ord) const {
9432 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
9433 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
9434 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
9435 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
9436 if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
9437 return Builder.CreateCall(
9438 Intrinsic::getDeclaration(
9439 Builder.GetInsertBlock()->getParent()->getParent(),
9440 Intrinsic::ppc_cfence, {Inst->getType()}),
9442 // FIXME: Can use isync for rmw operation.
9443 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9449 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
9450 unsigned AtomicSize,
9453 unsigned CmpPred) const {
9454 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9455 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9457 auto LoadMnemonic = PPC::LDARX;
9458 auto StoreMnemonic = PPC::STDCX;
9459 switch (AtomicSize) {
9461 llvm_unreachable("Unexpected size of atomic entity");
9463 LoadMnemonic = PPC::LBARX;
9464 StoreMnemonic = PPC::STBCX;
9465 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9468 LoadMnemonic = PPC::LHARX;
9469 StoreMnemonic = PPC::STHCX;
9470 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9473 LoadMnemonic = PPC::LWARX;
9474 StoreMnemonic = PPC::STWCX;
9477 LoadMnemonic = PPC::LDARX;
9478 StoreMnemonic = PPC::STDCX;
9482 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9483 MachineFunction *F = BB->getParent();
9484 MachineFunction::iterator It = ++BB->getIterator();
9486 unsigned dest = MI.getOperand(0).getReg();
9487 unsigned ptrA = MI.getOperand(1).getReg();
9488 unsigned ptrB = MI.getOperand(2).getReg();
9489 unsigned incr = MI.getOperand(3).getReg();
9490 DebugLoc dl = MI.getDebugLoc();
9492 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9493 MachineBasicBlock *loop2MBB =
9494 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9495 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9496 F->insert(It, loopMBB);
9498 F->insert(It, loop2MBB);
9499 F->insert(It, exitMBB);
9500 exitMBB->splice(exitMBB->begin(), BB,
9501 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9502 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9504 MachineRegisterInfo &RegInfo = F->getRegInfo();
9505 unsigned TmpReg = (!BinOpcode) ? incr :
9506 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
9507 : &PPC::GPRCRegClass);
9511 // fallthrough --> loopMBB
9512 BB->addSuccessor(loopMBB);
9515 // l[wd]arx dest, ptr
9516 // add r0, dest, incr
9517 // st[wd]cx. r0, ptr
9519 // fallthrough --> exitMBB
9523 // l[wd]arx dest, ptr
9524 // cmpl?[wd] incr, dest
9527 // st[wd]cx. dest, ptr
9529 // fallthrough --> exitMBB
9532 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9533 .addReg(ptrA).addReg(ptrB);
9535 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
9537 // Signed comparisons of byte or halfword values must be sign-extended.
9538 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
9539 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9540 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
9541 ExtReg).addReg(dest);
9542 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9543 .addReg(incr).addReg(ExtReg);
9545 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9546 .addReg(incr).addReg(dest);
9548 BuildMI(BB, dl, TII->get(PPC::BCC))
9549 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9550 BB->addSuccessor(loop2MBB);
9551 BB->addSuccessor(exitMBB);
9554 BuildMI(BB, dl, TII->get(StoreMnemonic))
9555 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9556 BuildMI(BB, dl, TII->get(PPC::BCC))
9557 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9558 BB->addSuccessor(loopMBB);
9559 BB->addSuccessor(exitMBB);
9568 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
9569 MachineBasicBlock *BB,
9570 bool is8bit, // operation
9573 unsigned CmpPred) const {
9574 // If we support part-word atomic mnemonics, just use them
9575 if (Subtarget.hasPartwordAtomics())
9576 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
9577 CmpOpcode, CmpPred);
9579 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9580 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9581 // In 64 bit mode we have to use 64 bits for addresses, even though the
9582 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
9583 // registers without caring whether they're 32 or 64, but here we're
9584 // doing actual arithmetic on the addresses.
9585 bool is64bit = Subtarget.isPPC64();
9586 bool isLittleEndian = Subtarget.isLittleEndian();
9587 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9589 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9590 MachineFunction *F = BB->getParent();
9591 MachineFunction::iterator It = ++BB->getIterator();
9593 unsigned dest = MI.getOperand(0).getReg();
9594 unsigned ptrA = MI.getOperand(1).getReg();
9595 unsigned ptrB = MI.getOperand(2).getReg();
9596 unsigned incr = MI.getOperand(3).getReg();
9597 DebugLoc dl = MI.getDebugLoc();
9599 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9600 MachineBasicBlock *loop2MBB =
9601 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9602 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9603 F->insert(It, loopMBB);
9605 F->insert(It, loop2MBB);
9606 F->insert(It, exitMBB);
9607 exitMBB->splice(exitMBB->begin(), BB,
9608 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9609 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9611 MachineRegisterInfo &RegInfo = F->getRegInfo();
9612 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9613 : &PPC::GPRCRegClass;
9614 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9615 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9617 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9618 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
9619 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9620 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9621 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9622 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9623 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
9624 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9625 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9627 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
9631 // fallthrough --> loopMBB
9632 BB->addSuccessor(loopMBB);
9634 // The 4-byte load must be aligned, while a char or short may be
9635 // anywhere in the word. Hence all this nasty bookkeeping code.
9636 // add ptr1, ptrA, ptrB [copy if ptrA==0]
9637 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9638 // xori shift, shift1, 24 [16]
9639 // rlwinm ptr, ptr1, 0, 0, 29
9640 // slw incr2, incr, shift
9641 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9642 // slw mask, mask2, shift
9644 // lwarx tmpDest, ptr
9645 // add tmp, tmpDest, incr2
9646 // andc tmp2, tmpDest, mask
9647 // and tmp3, tmp, mask
9648 // or tmp4, tmp3, tmp2
9651 // fallthrough --> exitMBB
9652 // srw dest, tmpDest, shift
9653 if (ptrA != ZeroReg) {
9654 Ptr1Reg = RegInfo.createVirtualRegister(RC);
9655 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9656 .addReg(ptrA).addReg(ptrB);
9660 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9661 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9662 if (!isLittleEndian)
9663 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9664 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9666 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9667 .addReg(Ptr1Reg).addImm(0).addImm(61);
9669 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9670 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9671 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9672 .addReg(incr).addReg(ShiftReg);
9674 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9676 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9677 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9679 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9680 .addReg(Mask2Reg).addReg(ShiftReg);
9683 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9684 .addReg(ZeroReg).addReg(PtrReg);
9686 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9687 .addReg(Incr2Reg).addReg(TmpDestReg);
9688 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9689 .addReg(TmpDestReg).addReg(MaskReg);
9690 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9691 .addReg(TmpReg).addReg(MaskReg);
9693 // For unsigned comparisons, we can directly compare the shifted values.
9694 // For signed comparisons we shift and sign extend.
9695 unsigned SReg = RegInfo.createVirtualRegister(RC);
9696 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9697 .addReg(TmpDestReg).addReg(MaskReg);
9698 unsigned ValueReg = SReg;
9699 unsigned CmpReg = Incr2Reg;
9700 if (CmpOpcode == PPC::CMPW) {
9701 ValueReg = RegInfo.createVirtualRegister(RC);
9702 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9703 .addReg(SReg).addReg(ShiftReg);
9704 unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9705 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9707 ValueReg = ValueSReg;
9710 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9711 .addReg(CmpReg).addReg(ValueReg);
9712 BuildMI(BB, dl, TII->get(PPC::BCC))
9713 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9714 BB->addSuccessor(loop2MBB);
9715 BB->addSuccessor(exitMBB);
9718 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9719 .addReg(Tmp3Reg).addReg(Tmp2Reg);
9720 BuildMI(BB, dl, TII->get(PPC::STWCX))
9721 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9722 BuildMI(BB, dl, TII->get(PPC::BCC))
9723 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9724 BB->addSuccessor(loopMBB);
9725 BB->addSuccessor(exitMBB);
9730 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9735 llvm::MachineBasicBlock *
9736 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9737 MachineBasicBlock *MBB) const {
9738 DebugLoc DL = MI.getDebugLoc();
9739 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9740 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9742 MachineFunction *MF = MBB->getParent();
9743 MachineRegisterInfo &MRI = MF->getRegInfo();
9745 const BasicBlock *BB = MBB->getBasicBlock();
9746 MachineFunction::iterator I = ++MBB->getIterator();
9749 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9750 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9752 unsigned DstReg = MI.getOperand(0).getReg();
9753 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9754 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9755 unsigned mainDstReg = MRI.createVirtualRegister(RC);
9756 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9758 MVT PVT = getPointerTy(MF->getDataLayout());
9759 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9760 "Invalid Pointer Size!");
9761 // For v = setjmp(buf), we generate
9764 // SjLjSetup mainMBB
9770 // buf[LabelOffset] = LR
9774 // v = phi(main, restore)
9777 MachineBasicBlock *thisMBB = MBB;
9778 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9779 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9780 MF->insert(I, mainMBB);
9781 MF->insert(I, sinkMBB);
9783 MachineInstrBuilder MIB;
9785 // Transfer the remainder of BB and its successor edges to sinkMBB.
9786 sinkMBB->splice(sinkMBB->begin(), MBB,
9787 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9788 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9790 // Note that the structure of the jmp_buf used here is not compatible
9791 // with that used by libc, and is not designed to be. Specifically, it
9792 // stores only those 'reserved' registers that LLVM does not otherwise
9793 // understand how to spill. Also, by convention, by the time this
9794 // intrinsic is called, Clang has already stored the frame address in the
9795 // first slot of the buffer and stack address in the third. Following the
9796 // X86 target code, we'll store the jump address in the second slot. We also
9797 // need to save the TOC pointer (R2) to handle jumps between shared
9798 // libraries, and that will be stored in the fourth slot. The thread
9799 // identifier (R13) is not affected.
9802 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9803 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9804 const int64_t BPOffset = 4 * PVT.getStoreSize();
9806 // Prepare IP either in reg.
9807 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9808 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9809 unsigned BufReg = MI.getOperand(1).getReg();
9811 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9812 setUsesTOCBasePtr(*MBB->getParent());
9813 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9817 MIB.setMemRefs(MMOBegin, MMOEnd);
9820 // Naked functions never have a base pointer, and so we use r1. For all
9821 // other functions, this decision must be delayed until during PEI.
9823 if (MF->getFunction().hasFnAttribute(Attribute::Naked))
9824 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9826 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9828 MIB = BuildMI(*thisMBB, MI, DL,
9829 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9833 MIB.setMemRefs(MMOBegin, MMOEnd);
9836 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9837 MIB.addRegMask(TRI->getNoPreservedMask());
9839 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9841 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9843 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9845 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9846 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9851 BuildMI(mainMBB, DL,
9852 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9855 if (Subtarget.isPPC64()) {
9856 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9858 .addImm(LabelOffset)
9861 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9863 .addImm(LabelOffset)
9867 MIB.setMemRefs(MMOBegin, MMOEnd);
9869 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9870 mainMBB->addSuccessor(sinkMBB);
9873 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9874 TII->get(PPC::PHI), DstReg)
9875 .addReg(mainDstReg).addMBB(mainMBB)
9876 .addReg(restoreDstReg).addMBB(thisMBB);
9878 MI.eraseFromParent();
9883 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9884 MachineBasicBlock *MBB) const {
9885 DebugLoc DL = MI.getDebugLoc();
9886 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9888 MachineFunction *MF = MBB->getParent();
9889 MachineRegisterInfo &MRI = MF->getRegInfo();
9892 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9893 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9895 MVT PVT = getPointerTy(MF->getDataLayout());
9896 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9897 "Invalid Pointer Size!");
9899 const TargetRegisterClass *RC =
9900 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9901 unsigned Tmp = MRI.createVirtualRegister(RC);
9902 // Since FP is only updated here but NOT referenced, it's treated as GPR.
9903 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9904 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9908 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9911 MachineInstrBuilder MIB;
9913 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9914 const int64_t SPOffset = 2 * PVT.getStoreSize();
9915 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9916 const int64_t BPOffset = 4 * PVT.getStoreSize();
9918 unsigned BufReg = MI.getOperand(0).getReg();
9920 // Reload FP (the jumped-to function may not have had a
9921 // frame pointer, and if so, then its r31 will be restored
9923 if (PVT == MVT::i64) {
9924 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9928 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9932 MIB.setMemRefs(MMOBegin, MMOEnd);
9935 if (PVT == MVT::i64) {
9936 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9937 .addImm(LabelOffset)
9940 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9941 .addImm(LabelOffset)
9944 MIB.setMemRefs(MMOBegin, MMOEnd);
9947 if (PVT == MVT::i64) {
9948 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9952 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9956 MIB.setMemRefs(MMOBegin, MMOEnd);
9959 if (PVT == MVT::i64) {
9960 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9964 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9968 MIB.setMemRefs(MMOBegin, MMOEnd);
9971 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9972 setUsesTOCBasePtr(*MBB->getParent());
9973 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9977 MIB.setMemRefs(MMOBegin, MMOEnd);
9981 BuildMI(*MBB, MI, DL,
9982 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9983 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9985 MI.eraseFromParent();
9990 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9991 MachineBasicBlock *BB) const {
9992 if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9993 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9994 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9995 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9996 // Call lowering should have added an r2 operand to indicate a dependence
9997 // on the TOC base pointer value. It can't however, because there is no
9998 // way to mark the dependence as implicit there, and so the stackmap code
9999 // will confuse it with a regular operand. Instead, add the dependence
10001 setUsesTOCBasePtr(*BB->getParent());
10002 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10005 return emitPatchPoint(MI, BB);
10008 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10009 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10010 return emitEHSjLjSetJmp(MI, BB);
10011 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10012 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10013 return emitEHSjLjLongJmp(MI, BB);
10016 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10018 // To "insert" these instructions we actually have to insert their
10019 // control-flow patterns.
10020 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10021 MachineFunction::iterator It = ++BB->getIterator();
10023 MachineFunction *F = BB->getParent();
10025 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10026 MI.getOpcode() == PPC::SELECT_CC_I8 ||
10027 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
10028 SmallVector<MachineOperand, 2> Cond;
10029 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10030 MI.getOpcode() == PPC::SELECT_CC_I8)
10031 Cond.push_back(MI.getOperand(4));
10033 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10034 Cond.push_back(MI.getOperand(1));
10036 DebugLoc dl = MI.getDebugLoc();
10037 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10038 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10039 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10040 MI.getOpcode() == PPC::SELECT_CC_I8 ||
10041 MI.getOpcode() == PPC::SELECT_CC_F4 ||
10042 MI.getOpcode() == PPC::SELECT_CC_F8 ||
10043 MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10044 MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10045 MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10046 MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10047 MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10048 MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10049 MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10050 MI.getOpcode() == PPC::SELECT_I4 ||
10051 MI.getOpcode() == PPC::SELECT_I8 ||
10052 MI.getOpcode() == PPC::SELECT_F4 ||
10053 MI.getOpcode() == PPC::SELECT_F8 ||
10054 MI.getOpcode() == PPC::SELECT_QFRC ||
10055 MI.getOpcode() == PPC::SELECT_QSRC ||
10056 MI.getOpcode() == PPC::SELECT_QBRC ||
10057 MI.getOpcode() == PPC::SELECT_VRRC ||
10058 MI.getOpcode() == PPC::SELECT_VSFRC ||
10059 MI.getOpcode() == PPC::SELECT_VSSRC ||
10060 MI.getOpcode() == PPC::SELECT_VSRC) {
10061 // The incoming instruction knows the destination vreg to set, the
10062 // condition code register to branch on, the true/false values to
10063 // select between, and a branch opcode to use.
10068 // cmpTY ccX, r1, r2
10070 // fallthrough --> copy0MBB
10071 MachineBasicBlock *thisMBB = BB;
10072 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10073 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10074 DebugLoc dl = MI.getDebugLoc();
10075 F->insert(It, copy0MBB);
10076 F->insert(It, sinkMBB);
10078 // Transfer the remainder of BB and its successor edges to sinkMBB.
10079 sinkMBB->splice(sinkMBB->begin(), BB,
10080 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10081 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10083 // Next, add the true and fallthrough blocks as its successors.
10084 BB->addSuccessor(copy0MBB);
10085 BB->addSuccessor(sinkMBB);
10087 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10088 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10089 MI.getOpcode() == PPC::SELECT_QFRC ||
10090 MI.getOpcode() == PPC::SELECT_QSRC ||
10091 MI.getOpcode() == PPC::SELECT_QBRC ||
10092 MI.getOpcode() == PPC::SELECT_VRRC ||
10093 MI.getOpcode() == PPC::SELECT_VSFRC ||
10094 MI.getOpcode() == PPC::SELECT_VSSRC ||
10095 MI.getOpcode() == PPC::SELECT_VSRC) {
10096 BuildMI(BB, dl, TII->get(PPC::BC))
10097 .addReg(MI.getOperand(1).getReg())
10100 unsigned SelectPred = MI.getOperand(4).getImm();
10101 BuildMI(BB, dl, TII->get(PPC::BCC))
10102 .addImm(SelectPred)
10103 .addReg(MI.getOperand(1).getReg())
10108 // %FalseValue = ...
10109 // # fallthrough to sinkMBB
10112 // Update machine-CFG edges
10113 BB->addSuccessor(sinkMBB);
10116 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10119 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10120 .addReg(MI.getOperand(3).getReg())
10122 .addReg(MI.getOperand(2).getReg())
10124 } else if (MI.getOpcode() == PPC::ReadTB) {
10125 // To read the 64-bit time-base register on a 32-bit target, we read the
10126 // two halves. Should the counter have wrapped while it was being read, we
10127 // need to try again.
10130 // mfspr Rx,TBU # load from TBU
10131 // mfspr Ry,TB # load from TB
10132 // mfspr Rz,TBU # load from TBU
10133 // cmpw crX,Rx,Rz # check if 'old'='new'
10134 // bne readLoop # branch if they're not equal
10137 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10138 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10139 DebugLoc dl = MI.getDebugLoc();
10140 F->insert(It, readMBB);
10141 F->insert(It, sinkMBB);
10143 // Transfer the remainder of BB and its successor edges to sinkMBB.
10144 sinkMBB->splice(sinkMBB->begin(), BB,
10145 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10146 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10148 BB->addSuccessor(readMBB);
10151 MachineRegisterInfo &RegInfo = F->getRegInfo();
10152 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10153 unsigned LoReg = MI.getOperand(0).getReg();
10154 unsigned HiReg = MI.getOperand(1).getReg();
10156 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10157 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10158 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10160 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10162 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10163 .addReg(HiReg).addReg(ReadAgainReg);
10164 BuildMI(BB, dl, TII->get(PPC::BCC))
10165 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
10167 BB->addSuccessor(readMBB);
10168 BB->addSuccessor(sinkMBB);
10169 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10170 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10171 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10172 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10173 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10174 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10175 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10176 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10178 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10179 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10180 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10181 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10182 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10183 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10184 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10185 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10187 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10188 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10189 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10190 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10191 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10192 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10193 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10194 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10196 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10197 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10198 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10199 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10200 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10201 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10202 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10203 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10205 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10206 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10207 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10208 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10209 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10210 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10211 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10212 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10214 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10215 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10216 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10217 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10218 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10219 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10220 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10221 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10223 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10224 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10225 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10226 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10227 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10228 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10229 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10230 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10232 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10233 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10234 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10235 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10236 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10237 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10238 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10239 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10241 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10242 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10243 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10244 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10245 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10246 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10247 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10248 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10250 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10251 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10252 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10253 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10254 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10255 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10256 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10257 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10259 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10260 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10261 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10262 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10263 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10264 BB = EmitAtomicBinary(MI, BB, 4, 0);
10265 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10266 BB = EmitAtomicBinary(MI, BB, 8, 0);
10267 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10268 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10269 (Subtarget.hasPartwordAtomics() &&
10270 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10271 (Subtarget.hasPartwordAtomics() &&
10272 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10273 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10275 auto LoadMnemonic = PPC::LDARX;
10276 auto StoreMnemonic = PPC::STDCX;
10277 switch (MI.getOpcode()) {
10279 llvm_unreachable("Compare and swap of unknown size");
10280 case PPC::ATOMIC_CMP_SWAP_I8:
10281 LoadMnemonic = PPC::LBARX;
10282 StoreMnemonic = PPC::STBCX;
10283 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10285 case PPC::ATOMIC_CMP_SWAP_I16:
10286 LoadMnemonic = PPC::LHARX;
10287 StoreMnemonic = PPC::STHCX;
10288 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10290 case PPC::ATOMIC_CMP_SWAP_I32:
10291 LoadMnemonic = PPC::LWARX;
10292 StoreMnemonic = PPC::STWCX;
10294 case PPC::ATOMIC_CMP_SWAP_I64:
10295 LoadMnemonic = PPC::LDARX;
10296 StoreMnemonic = PPC::STDCX;
10299 unsigned dest = MI.getOperand(0).getReg();
10300 unsigned ptrA = MI.getOperand(1).getReg();
10301 unsigned ptrB = MI.getOperand(2).getReg();
10302 unsigned oldval = MI.getOperand(3).getReg();
10303 unsigned newval = MI.getOperand(4).getReg();
10304 DebugLoc dl = MI.getDebugLoc();
10306 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10307 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10308 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10309 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10310 F->insert(It, loop1MBB);
10311 F->insert(It, loop2MBB);
10312 F->insert(It, midMBB);
10313 F->insert(It, exitMBB);
10314 exitMBB->splice(exitMBB->begin(), BB,
10315 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10316 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10320 // fallthrough --> loopMBB
10321 BB->addSuccessor(loop1MBB);
10324 // l[bhwd]arx dest, ptr
10325 // cmp[wd] dest, oldval
10328 // st[bhwd]cx. newval, ptr
10332 // st[bhwd]cx. dest, ptr
10335 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10336 .addReg(ptrA).addReg(ptrB);
10337 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10338 .addReg(oldval).addReg(dest);
10339 BuildMI(BB, dl, TII->get(PPC::BCC))
10340 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10341 BB->addSuccessor(loop2MBB);
10342 BB->addSuccessor(midMBB);
10345 BuildMI(BB, dl, TII->get(StoreMnemonic))
10346 .addReg(newval).addReg(ptrA).addReg(ptrB);
10347 BuildMI(BB, dl, TII->get(PPC::BCC))
10348 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10349 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10350 BB->addSuccessor(loop1MBB);
10351 BB->addSuccessor(exitMBB);
10354 BuildMI(BB, dl, TII->get(StoreMnemonic))
10355 .addReg(dest).addReg(ptrA).addReg(ptrB);
10356 BB->addSuccessor(exitMBB);
10361 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10362 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10363 // We must use 64-bit registers for addresses when targeting 64-bit,
10364 // since we're actually doing arithmetic on them. Other registers
10366 bool is64bit = Subtarget.isPPC64();
10367 bool isLittleEndian = Subtarget.isLittleEndian();
10368 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10370 unsigned dest = MI.getOperand(0).getReg();
10371 unsigned ptrA = MI.getOperand(1).getReg();
10372 unsigned ptrB = MI.getOperand(2).getReg();
10373 unsigned oldval = MI.getOperand(3).getReg();
10374 unsigned newval = MI.getOperand(4).getReg();
10375 DebugLoc dl = MI.getDebugLoc();
10377 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10378 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10379 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10380 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10381 F->insert(It, loop1MBB);
10382 F->insert(It, loop2MBB);
10383 F->insert(It, midMBB);
10384 F->insert(It, exitMBB);
10385 exitMBB->splice(exitMBB->begin(), BB,
10386 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10387 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10389 MachineRegisterInfo &RegInfo = F->getRegInfo();
10390 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
10391 : &PPC::GPRCRegClass;
10392 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10393 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
10394 unsigned ShiftReg =
10395 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
10396 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
10397 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
10398 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
10399 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
10400 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
10401 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
10402 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
10403 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
10404 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
10405 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
10407 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
10408 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10411 // fallthrough --> loopMBB
10412 BB->addSuccessor(loop1MBB);
10414 // The 4-byte load must be aligned, while a char or short may be
10415 // anywhere in the word. Hence all this nasty bookkeeping code.
10416 // add ptr1, ptrA, ptrB [copy if ptrA==0]
10417 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10418 // xori shift, shift1, 24 [16]
10419 // rlwinm ptr, ptr1, 0, 0, 29
10420 // slw newval2, newval, shift
10421 // slw oldval2, oldval,shift
10422 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10423 // slw mask, mask2, shift
10424 // and newval3, newval2, mask
10425 // and oldval3, oldval2, mask
10427 // lwarx tmpDest, ptr
10428 // and tmp, tmpDest, mask
10429 // cmpw tmp, oldval3
10432 // andc tmp2, tmpDest, mask
10433 // or tmp4, tmp2, newval3
10434 // stwcx. tmp4, ptr
10438 // stwcx. tmpDest, ptr
10440 // srw dest, tmpDest, shift
10441 if (ptrA != ZeroReg) {
10442 Ptr1Reg = RegInfo.createVirtualRegister(RC);
10443 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10444 .addReg(ptrA).addReg(ptrB);
10448 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
10449 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
10450 if (!isLittleEndian)
10451 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
10452 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
10454 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10455 .addReg(Ptr1Reg).addImm(0).addImm(61);
10457 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10458 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
10459 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
10460 .addReg(newval).addReg(ShiftReg);
10461 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
10462 .addReg(oldval).addReg(ShiftReg);
10464 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10466 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10467 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10468 .addReg(Mask3Reg).addImm(65535);
10470 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10471 .addReg(Mask2Reg).addReg(ShiftReg);
10472 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
10473 .addReg(NewVal2Reg).addReg(MaskReg);
10474 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
10475 .addReg(OldVal2Reg).addReg(MaskReg);
10478 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10479 .addReg(ZeroReg).addReg(PtrReg);
10480 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
10481 .addReg(TmpDestReg).addReg(MaskReg);
10482 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
10483 .addReg(TmpReg).addReg(OldVal3Reg);
10484 BuildMI(BB, dl, TII->get(PPC::BCC))
10485 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10486 BB->addSuccessor(loop2MBB);
10487 BB->addSuccessor(midMBB);
10490 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
10491 .addReg(TmpDestReg).addReg(MaskReg);
10492 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
10493 .addReg(Tmp2Reg).addReg(NewVal3Reg);
10494 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
10495 .addReg(ZeroReg).addReg(PtrReg);
10496 BuildMI(BB, dl, TII->get(PPC::BCC))
10497 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10498 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10499 BB->addSuccessor(loop1MBB);
10500 BB->addSuccessor(exitMBB);
10503 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
10504 .addReg(ZeroReg).addReg(PtrReg);
10505 BB->addSuccessor(exitMBB);
10510 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
10512 } else if (MI.getOpcode() == PPC::FADDrtz) {
10513 // This pseudo performs an FADD with rounding mode temporarily forced
10514 // to round-to-zero. We emit this via custom inserter since the FPSCR
10515 // is not modeled at the SelectionDAG level.
10516 unsigned Dest = MI.getOperand(0).getReg();
10517 unsigned Src1 = MI.getOperand(1).getReg();
10518 unsigned Src2 = MI.getOperand(2).getReg();
10519 DebugLoc dl = MI.getDebugLoc();
10521 MachineRegisterInfo &RegInfo = F->getRegInfo();
10522 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
10524 // Save FPSCR value.
10525 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
10527 // Set rounding mode to round-to-zero.
10528 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
10529 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
10531 // Perform addition.
10532 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
10534 // Restore FPSCR value.
10535 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
10536 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10537 MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
10538 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10539 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
10540 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10541 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
10544 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10545 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
10547 MachineRegisterInfo &RegInfo = F->getRegInfo();
10548 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
10549 &PPC::GPRCRegClass :
10550 &PPC::G8RCRegClass);
10552 DebugLoc dl = MI.getDebugLoc();
10553 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
10554 .addReg(MI.getOperand(1).getReg())
10556 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
10557 MI.getOperand(0).getReg())
10558 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
10559 } else if (MI.getOpcode() == PPC::TCHECK_RET) {
10560 DebugLoc Dl = MI.getDebugLoc();
10561 MachineRegisterInfo &RegInfo = F->getRegInfo();
10562 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10563 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
10566 llvm_unreachable("Unexpected instr type to insert");
10569 MI.eraseFromParent(); // The pseudo instruction is gone now.
10573 //===----------------------------------------------------------------------===//
10574 // Target Optimization Hooks
10575 //===----------------------------------------------------------------------===//
10577 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
10578 // For the estimates, convergence is quadratic, so we essentially double the
10579 // number of digits correct after every iteration. For both FRE and FRSQRTE,
10580 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
10581 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
10582 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
10583 if (VT.getScalarType() == MVT::f64)
10585 return RefinementSteps;
10588 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
10589 int Enabled, int &RefinementSteps,
10590 bool &UseOneConstNR,
10591 bool Reciprocal) const {
10592 EVT VT = Operand.getValueType();
10593 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
10594 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
10595 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10596 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10597 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10598 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10599 if (RefinementSteps == ReciprocalEstimate::Unspecified)
10600 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10602 UseOneConstNR = true;
10603 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
10608 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
10610 int &RefinementSteps) const {
10611 EVT VT = Operand.getValueType();
10612 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
10613 (VT == MVT::f64 && Subtarget.hasFRE()) ||
10614 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10615 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10616 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10617 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10618 if (RefinementSteps == ReciprocalEstimate::Unspecified)
10619 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10620 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
10625 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
10626 // Note: This functionality is used only when unsafe-fp-math is enabled, and
10627 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
10628 // enabled for division), this functionality is redundant with the default
10629 // combiner logic (once the division -> reciprocal/multiply transformation
10630 // has taken place). As a result, this matters more for older cores than for
10633 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10634 // reciprocal if there are two or more FDIVs (for embedded cores with only
10635 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10636 switch (Subtarget.getDarwinDirective()) {
10641 case PPC::DIR_E500mc:
10642 case PPC::DIR_E5500:
10647 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10648 // collapsed, and so we need to look through chains of them.
10649 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10650 int64_t& Offset, SelectionDAG &DAG) {
10651 if (DAG.isBaseWithConstantOffset(Loc)) {
10652 Base = Loc.getOperand(0);
10653 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10655 // The base might itself be a base plus an offset, and if so, accumulate
10657 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10661 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10662 unsigned Bytes, int Dist,
10663 SelectionDAG &DAG) {
10664 if (VT.getSizeInBits() / 8 != Bytes)
10667 SDValue BaseLoc = Base->getBasePtr();
10668 if (Loc.getOpcode() == ISD::FrameIndex) {
10669 if (BaseLoc.getOpcode() != ISD::FrameIndex)
10671 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10672 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
10673 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10674 int FS = MFI.getObjectSize(FI);
10675 int BFS = MFI.getObjectSize(BFI);
10676 if (FS != BFS || FS != (int)Bytes) return false;
10677 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10680 SDValue Base1 = Loc, Base2 = BaseLoc;
10681 int64_t Offset1 = 0, Offset2 = 0;
10682 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10683 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10684 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10688 const GlobalValue *GV1 = nullptr;
10689 const GlobalValue *GV2 = nullptr;
10692 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10693 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10694 if (isGA1 && isGA2 && GV1 == GV2)
10695 return Offset1 == (Offset2 + Dist*Bytes);
10699 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10700 // not enforce equality of the chain operands.
10701 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10702 unsigned Bytes, int Dist,
10703 SelectionDAG &DAG) {
10704 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10705 EVT VT = LS->getMemoryVT();
10706 SDValue Loc = LS->getBasePtr();
10707 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10710 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10712 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10713 default: return false;
10714 case Intrinsic::ppc_qpx_qvlfd:
10715 case Intrinsic::ppc_qpx_qvlfda:
10718 case Intrinsic::ppc_qpx_qvlfs:
10719 case Intrinsic::ppc_qpx_qvlfsa:
10722 case Intrinsic::ppc_qpx_qvlfcd:
10723 case Intrinsic::ppc_qpx_qvlfcda:
10726 case Intrinsic::ppc_qpx_qvlfcs:
10727 case Intrinsic::ppc_qpx_qvlfcsa:
10730 case Intrinsic::ppc_qpx_qvlfiwa:
10731 case Intrinsic::ppc_qpx_qvlfiwz:
10732 case Intrinsic::ppc_altivec_lvx:
10733 case Intrinsic::ppc_altivec_lvxl:
10734 case Intrinsic::ppc_vsx_lxvw4x:
10735 case Intrinsic::ppc_vsx_lxvw4x_be:
10738 case Intrinsic::ppc_vsx_lxvd2x:
10739 case Intrinsic::ppc_vsx_lxvd2x_be:
10742 case Intrinsic::ppc_altivec_lvebx:
10745 case Intrinsic::ppc_altivec_lvehx:
10748 case Intrinsic::ppc_altivec_lvewx:
10753 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10756 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10758 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10759 default: return false;
10760 case Intrinsic::ppc_qpx_qvstfd:
10761 case Intrinsic::ppc_qpx_qvstfda:
10764 case Intrinsic::ppc_qpx_qvstfs:
10765 case Intrinsic::ppc_qpx_qvstfsa:
10768 case Intrinsic::ppc_qpx_qvstfcd:
10769 case Intrinsic::ppc_qpx_qvstfcda:
10772 case Intrinsic::ppc_qpx_qvstfcs:
10773 case Intrinsic::ppc_qpx_qvstfcsa:
10776 case Intrinsic::ppc_qpx_qvstfiw:
10777 case Intrinsic::ppc_qpx_qvstfiwa:
10778 case Intrinsic::ppc_altivec_stvx:
10779 case Intrinsic::ppc_altivec_stvxl:
10780 case Intrinsic::ppc_vsx_stxvw4x:
10783 case Intrinsic::ppc_vsx_stxvd2x:
10786 case Intrinsic::ppc_vsx_stxvw4x_be:
10789 case Intrinsic::ppc_vsx_stxvd2x_be:
10792 case Intrinsic::ppc_altivec_stvebx:
10795 case Intrinsic::ppc_altivec_stvehx:
10798 case Intrinsic::ppc_altivec_stvewx:
10803 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10809 // Return true is there is a nearyby consecutive load to the one provided
10810 // (regardless of alignment). We search up and down the chain, looking though
10811 // token factors and other loads (but nothing else). As a result, a true result
10812 // indicates that it is safe to create a new consecutive load adjacent to the
10814 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10815 SDValue Chain = LD->getChain();
10816 EVT VT = LD->getMemoryVT();
10818 SmallSet<SDNode *, 16> LoadRoots;
10819 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10820 SmallSet<SDNode *, 16> Visited;
10822 // First, search up the chain, branching to follow all token-factor operands.
10823 // If we find a consecutive load, then we're done, otherwise, record all
10824 // nodes just above the top-level loads and token factors.
10825 while (!Queue.empty()) {
10826 SDNode *ChainNext = Queue.pop_back_val();
10827 if (!Visited.insert(ChainNext).second)
10830 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10831 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10834 if (!Visited.count(ChainLD->getChain().getNode()))
10835 Queue.push_back(ChainLD->getChain().getNode());
10836 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10837 for (const SDUse &O : ChainNext->ops())
10838 if (!Visited.count(O.getNode()))
10839 Queue.push_back(O.getNode());
10841 LoadRoots.insert(ChainNext);
10844 // Second, search down the chain, starting from the top-level nodes recorded
10845 // in the first phase. These top-level nodes are the nodes just above all
10846 // loads and token factors. Starting with their uses, recursively look though
10847 // all loads (just the chain uses) and token factors to find a consecutive
10852 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10853 IE = LoadRoots.end(); I != IE; ++I) {
10854 Queue.push_back(*I);
10856 while (!Queue.empty()) {
10857 SDNode *LoadRoot = Queue.pop_back_val();
10858 if (!Visited.insert(LoadRoot).second)
10861 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10862 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10865 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10866 UE = LoadRoot->use_end(); UI != UE; ++UI)
10867 if (((isa<MemSDNode>(*UI) &&
10868 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10869 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10870 Queue.push_back(*UI);
10877 /// This function is called when we have proved that a SETCC node can be replaced
10878 /// by subtraction (and other supporting instructions) so that the result of
10879 /// comparison is kept in a GPR instead of CR. This function is purely for
10880 /// codegen purposes and has some flags to guide the codegen process.
10881 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10882 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10883 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10885 // Zero extend the operands to the largest legal integer. Originally, they
10886 // must be of a strictly smaller size.
10887 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10888 DAG.getConstant(Size, DL, MVT::i32));
10889 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10890 DAG.getConstant(Size, DL, MVT::i32));
10892 // Swap if needed. Depends on the condition code.
10894 std::swap(Op0, Op1);
10896 // Subtract extended integers.
10897 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10899 // Move the sign bit to the least significant position and zero out the rest.
10900 // Now the least significant bit carries the result of original comparison.
10901 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10902 DAG.getConstant(Size - 1, DL, MVT::i32));
10903 auto Final = Shifted;
10905 // Complement the result if needed. Based on the condition code.
10907 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10908 DAG.getConstant(1, DL, MVT::i64));
10910 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10913 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10914 DAGCombinerInfo &DCI) const {
10915 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10917 SelectionDAG &DAG = DCI.DAG;
10920 // Size of integers being compared has a critical role in the following
10921 // analysis, so we prefer to do this when all types are legal.
10922 if (!DCI.isAfterLegalizeVectorOps())
10925 // If all users of SETCC extend its value to a legal integer type
10926 // then we replace SETCC with a subtraction
10927 for (SDNode::use_iterator UI = N->use_begin(),
10928 UE = N->use_end(); UI != UE; ++UI) {
10929 if (UI->getOpcode() != ISD::ZERO_EXTEND)
10933 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10934 auto OpSize = N->getOperand(0).getValueSizeInBits();
10936 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10938 if (OpSize < Size) {
10942 return generateEquivalentSub(N, Size, false, false, DL, DAG);
10944 return generateEquivalentSub(N, Size, true, true, DL, DAG);
10946 return generateEquivalentSub(N, Size, false, true, DL, DAG);
10948 return generateEquivalentSub(N, Size, true, false, DL, DAG);
10955 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10956 DAGCombinerInfo &DCI) const {
10957 SelectionDAG &DAG = DCI.DAG;
10960 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10961 // If we're tracking CR bits, we need to be careful that we don't have:
10962 // trunc(binary-ops(zext(x), zext(y)))
10964 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10965 // such that we're unnecessarily moving things into GPRs when it would be
10966 // better to keep them in CR bits.
10968 // Note that trunc here can be an actual i1 trunc, or can be the effective
10969 // truncation that comes from a setcc or select_cc.
10970 if (N->getOpcode() == ISD::TRUNCATE &&
10971 N->getValueType(0) != MVT::i1)
10974 if (N->getOperand(0).getValueType() != MVT::i32 &&
10975 N->getOperand(0).getValueType() != MVT::i64)
10978 if (N->getOpcode() == ISD::SETCC ||
10979 N->getOpcode() == ISD::SELECT_CC) {
10980 // If we're looking at a comparison, then we need to make sure that the
10981 // high bits (all except for the first) don't matter the result.
10983 cast<CondCodeSDNode>(N->getOperand(
10984 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10985 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10987 if (ISD::isSignedIntSetCC(CC)) {
10988 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10989 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10991 } else if (ISD::isUnsignedIntSetCC(CC)) {
10992 if (!DAG.MaskedValueIsZero(N->getOperand(0),
10993 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10994 !DAG.MaskedValueIsZero(N->getOperand(1),
10995 APInt::getHighBitsSet(OpBits, OpBits-1)))
10996 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10999 // This is neither a signed nor an unsigned comparison, just make sure
11000 // that the high bits are equal.
11001 KnownBits Op1Known, Op2Known;
11002 DAG.computeKnownBits(N->getOperand(0), Op1Known);
11003 DAG.computeKnownBits(N->getOperand(1), Op2Known);
11005 // We don't really care about what is known about the first bit (if
11006 // anything), so clear it in all masks prior to comparing them.
11007 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11008 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11010 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11015 // We now know that the higher-order bits are irrelevant, we just need to
11016 // make sure that all of the intermediate operations are bit operations, and
11017 // all inputs are extensions.
11018 if (N->getOperand(0).getOpcode() != ISD::AND &&
11019 N->getOperand(0).getOpcode() != ISD::OR &&
11020 N->getOperand(0).getOpcode() != ISD::XOR &&
11021 N->getOperand(0).getOpcode() != ISD::SELECT &&
11022 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11023 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11024 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11025 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11026 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11029 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11030 N->getOperand(1).getOpcode() != ISD::AND &&
11031 N->getOperand(1).getOpcode() != ISD::OR &&
11032 N->getOperand(1).getOpcode() != ISD::XOR &&
11033 N->getOperand(1).getOpcode() != ISD::SELECT &&
11034 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11035 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11036 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11037 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11038 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11041 SmallVector<SDValue, 4> Inputs;
11042 SmallVector<SDValue, 8> BinOps, PromOps;
11043 SmallPtrSet<SDNode *, 16> Visited;
11045 for (unsigned i = 0; i < 2; ++i) {
11046 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11047 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11048 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11049 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11050 isa<ConstantSDNode>(N->getOperand(i)))
11051 Inputs.push_back(N->getOperand(i));
11053 BinOps.push_back(N->getOperand(i));
11055 if (N->getOpcode() == ISD::TRUNCATE)
11059 // Visit all inputs, collect all binary operations (and, or, xor and
11060 // select) that are all fed by extensions.
11061 while (!BinOps.empty()) {
11062 SDValue BinOp = BinOps.back();
11065 if (!Visited.insert(BinOp.getNode()).second)
11068 PromOps.push_back(BinOp);
11070 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11071 // The condition of the select is not promoted.
11072 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11074 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11077 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11078 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11079 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11080 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11081 isa<ConstantSDNode>(BinOp.getOperand(i))) {
11082 Inputs.push_back(BinOp.getOperand(i));
11083 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11084 BinOp.getOperand(i).getOpcode() == ISD::OR ||
11085 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11086 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11087 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11088 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11089 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11090 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11091 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11092 BinOps.push_back(BinOp.getOperand(i));
11094 // We have an input that is not an extension or another binary
11095 // operation; we'll abort this transformation.
11101 // Make sure that this is a self-contained cluster of operations (which
11102 // is not quite the same thing as saying that everything has only one
11104 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11105 if (isa<ConstantSDNode>(Inputs[i]))
11108 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11109 UE = Inputs[i].getNode()->use_end();
11111 SDNode *User = *UI;
11112 if (User != N && !Visited.count(User))
11115 // Make sure that we're not going to promote the non-output-value
11116 // operand(s) or SELECT or SELECT_CC.
11117 // FIXME: Although we could sometimes handle this, and it does occur in
11118 // practice that one of the condition inputs to the select is also one of
11119 // the outputs, we currently can't deal with this.
11120 if (User->getOpcode() == ISD::SELECT) {
11121 if (User->getOperand(0) == Inputs[i])
11123 } else if (User->getOpcode() == ISD::SELECT_CC) {
11124 if (User->getOperand(0) == Inputs[i] ||
11125 User->getOperand(1) == Inputs[i])
11131 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11132 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11133 UE = PromOps[i].getNode()->use_end();
11135 SDNode *User = *UI;
11136 if (User != N && !Visited.count(User))
11139 // Make sure that we're not going to promote the non-output-value
11140 // operand(s) or SELECT or SELECT_CC.
11141 // FIXME: Although we could sometimes handle this, and it does occur in
11142 // practice that one of the condition inputs to the select is also one of
11143 // the outputs, we currently can't deal with this.
11144 if (User->getOpcode() == ISD::SELECT) {
11145 if (User->getOperand(0) == PromOps[i])
11147 } else if (User->getOpcode() == ISD::SELECT_CC) {
11148 if (User->getOperand(0) == PromOps[i] ||
11149 User->getOperand(1) == PromOps[i])
11155 // Replace all inputs with the extension operand.
11156 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11157 // Constants may have users outside the cluster of to-be-promoted nodes,
11158 // and so we need to replace those as we do the promotions.
11159 if (isa<ConstantSDNode>(Inputs[i]))
11162 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
11165 std::list<HandleSDNode> PromOpHandles;
11166 for (auto &PromOp : PromOps)
11167 PromOpHandles.emplace_back(PromOp);
11169 // Replace all operations (these are all the same, but have a different
11170 // (i1) return type). DAG.getNode will validate that the types of
11171 // a binary operator match, so go through the list in reverse so that
11172 // we've likely promoted both operands first. Any intermediate truncations or
11173 // extensions disappear.
11174 while (!PromOpHandles.empty()) {
11175 SDValue PromOp = PromOpHandles.back().getValue();
11176 PromOpHandles.pop_back();
11178 if (PromOp.getOpcode() == ISD::TRUNCATE ||
11179 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11180 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11181 PromOp.getOpcode() == ISD::ANY_EXTEND) {
11182 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11183 PromOp.getOperand(0).getValueType() != MVT::i1) {
11184 // The operand is not yet ready (see comment below).
11185 PromOpHandles.emplace_front(PromOp);
11189 SDValue RepValue = PromOp.getOperand(0);
11190 if (isa<ConstantSDNode>(RepValue))
11191 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11193 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11198 switch (PromOp.getOpcode()) {
11199 default: C = 0; break;
11200 case ISD::SELECT: C = 1; break;
11201 case ISD::SELECT_CC: C = 2; break;
11204 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11205 PromOp.getOperand(C).getValueType() != MVT::i1) ||
11206 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11207 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11208 // The to-be-promoted operands of this node have not yet been
11209 // promoted (this should be rare because we're going through the
11210 // list backward, but if one of the operands has several users in
11211 // this cluster of to-be-promoted nodes, it is possible).
11212 PromOpHandles.emplace_front(PromOp);
11216 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11217 PromOp.getNode()->op_end());
11219 // If there are any constant inputs, make sure they're replaced now.
11220 for (unsigned i = 0; i < 2; ++i)
11221 if (isa<ConstantSDNode>(Ops[C+i]))
11222 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
11224 DAG.ReplaceAllUsesOfValueWith(PromOp,
11225 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
11228 // Now we're left with the initial truncation itself.
11229 if (N->getOpcode() == ISD::TRUNCATE)
11230 return N->getOperand(0);
11232 // Otherwise, this is a comparison. The operands to be compared have just
11233 // changed type (to i1), but everything else is the same.
11234 return SDValue(N, 0);
11237 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
11238 DAGCombinerInfo &DCI) const {
11239 SelectionDAG &DAG = DCI.DAG;
11242 // If we're tracking CR bits, we need to be careful that we don't have:
11243 // zext(binary-ops(trunc(x), trunc(y)))
11245 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
11246 // such that we're unnecessarily moving things into CR bits that can more
11247 // efficiently stay in GPRs. Note that if we're not certain that the high
11248 // bits are set as required by the final extension, we still may need to do
11249 // some masking to get the proper behavior.
11251 // This same functionality is important on PPC64 when dealing with
11252 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
11253 // the return values of functions. Because it is so similar, it is handled
11256 if (N->getValueType(0) != MVT::i32 &&
11257 N->getValueType(0) != MVT::i64)
11260 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
11261 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
11264 if (N->getOperand(0).getOpcode() != ISD::AND &&
11265 N->getOperand(0).getOpcode() != ISD::OR &&
11266 N->getOperand(0).getOpcode() != ISD::XOR &&
11267 N->getOperand(0).getOpcode() != ISD::SELECT &&
11268 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
11271 SmallVector<SDValue, 4> Inputs;
11272 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
11273 SmallPtrSet<SDNode *, 16> Visited;
11275 // Visit all inputs, collect all binary operations (and, or, xor and
11276 // select) that are all fed by truncations.
11277 while (!BinOps.empty()) {
11278 SDValue BinOp = BinOps.back();
11281 if (!Visited.insert(BinOp.getNode()).second)
11284 PromOps.push_back(BinOp);
11286 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11287 // The condition of the select is not promoted.
11288 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11290 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11293 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11294 isa<ConstantSDNode>(BinOp.getOperand(i))) {
11295 Inputs.push_back(BinOp.getOperand(i));
11296 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11297 BinOp.getOperand(i).getOpcode() == ISD::OR ||
11298 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11299 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11300 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
11301 BinOps.push_back(BinOp.getOperand(i));
11303 // We have an input that is not a truncation or another binary
11304 // operation; we'll abort this transformation.
11310 // The operands of a select that must be truncated when the select is
11311 // promoted because the operand is actually part of the to-be-promoted set.
11312 DenseMap<SDNode *, EVT> SelectTruncOp[2];
11314 // Make sure that this is a self-contained cluster of operations (which
11315 // is not quite the same thing as saying that everything has only one
11317 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11318 if (isa<ConstantSDNode>(Inputs[i]))
11321 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11322 UE = Inputs[i].getNode()->use_end();
11324 SDNode *User = *UI;
11325 if (User != N && !Visited.count(User))
11328 // If we're going to promote the non-output-value operand(s) or SELECT or
11329 // SELECT_CC, record them for truncation.
11330 if (User->getOpcode() == ISD::SELECT) {
11331 if (User->getOperand(0) == Inputs[i])
11332 SelectTruncOp[0].insert(std::make_pair(User,
11333 User->getOperand(0).getValueType()));
11334 } else if (User->getOpcode() == ISD::SELECT_CC) {
11335 if (User->getOperand(0) == Inputs[i])
11336 SelectTruncOp[0].insert(std::make_pair(User,
11337 User->getOperand(0).getValueType()));
11338 if (User->getOperand(1) == Inputs[i])
11339 SelectTruncOp[1].insert(std::make_pair(User,
11340 User->getOperand(1).getValueType()));
11345 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11346 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11347 UE = PromOps[i].getNode()->use_end();
11349 SDNode *User = *UI;
11350 if (User != N && !Visited.count(User))
11353 // If we're going to promote the non-output-value operand(s) or SELECT or
11354 // SELECT_CC, record them for truncation.
11355 if (User->getOpcode() == ISD::SELECT) {
11356 if (User->getOperand(0) == PromOps[i])
11357 SelectTruncOp[0].insert(std::make_pair(User,
11358 User->getOperand(0).getValueType()));
11359 } else if (User->getOpcode() == ISD::SELECT_CC) {
11360 if (User->getOperand(0) == PromOps[i])
11361 SelectTruncOp[0].insert(std::make_pair(User,
11362 User->getOperand(0).getValueType()));
11363 if (User->getOperand(1) == PromOps[i])
11364 SelectTruncOp[1].insert(std::make_pair(User,
11365 User->getOperand(1).getValueType()));
11370 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
11371 bool ReallyNeedsExt = false;
11372 if (N->getOpcode() != ISD::ANY_EXTEND) {
11373 // If all of the inputs are not already sign/zero extended, then
11374 // we'll still need to do that at the end.
11375 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11376 if (isa<ConstantSDNode>(Inputs[i]))
11380 Inputs[i].getOperand(0).getValueSizeInBits();
11381 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
11383 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
11384 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
11385 APInt::getHighBitsSet(OpBits,
11386 OpBits-PromBits))) ||
11387 (N->getOpcode() == ISD::SIGN_EXTEND &&
11388 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
11389 (OpBits-(PromBits-1)))) {
11390 ReallyNeedsExt = true;
11396 // Replace all inputs, either with the truncation operand, or a
11397 // truncation or extension to the final output type.
11398 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11399 // Constant inputs need to be replaced with the to-be-promoted nodes that
11400 // use them because they might have users outside of the cluster of
11402 if (isa<ConstantSDNode>(Inputs[i]))
11405 SDValue InSrc = Inputs[i].getOperand(0);
11406 if (Inputs[i].getValueType() == N->getValueType(0))
11407 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
11408 else if (N->getOpcode() == ISD::SIGN_EXTEND)
11409 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11410 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
11411 else if (N->getOpcode() == ISD::ZERO_EXTEND)
11412 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11413 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
11415 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11416 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
11419 std::list<HandleSDNode> PromOpHandles;
11420 for (auto &PromOp : PromOps)
11421 PromOpHandles.emplace_back(PromOp);
11423 // Replace all operations (these are all the same, but have a different
11424 // (promoted) return type). DAG.getNode will validate that the types of
11425 // a binary operator match, so go through the list in reverse so that
11426 // we've likely promoted both operands first.
11427 while (!PromOpHandles.empty()) {
11428 SDValue PromOp = PromOpHandles.back().getValue();
11429 PromOpHandles.pop_back();
11432 switch (PromOp.getOpcode()) {
11433 default: C = 0; break;
11434 case ISD::SELECT: C = 1; break;
11435 case ISD::SELECT_CC: C = 2; break;
11438 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11439 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
11440 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11441 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
11442 // The to-be-promoted operands of this node have not yet been
11443 // promoted (this should be rare because we're going through the
11444 // list backward, but if one of the operands has several users in
11445 // this cluster of to-be-promoted nodes, it is possible).
11446 PromOpHandles.emplace_front(PromOp);
11450 // For SELECT and SELECT_CC nodes, we do a similar check for any
11451 // to-be-promoted comparison inputs.
11452 if (PromOp.getOpcode() == ISD::SELECT ||
11453 PromOp.getOpcode() == ISD::SELECT_CC) {
11454 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
11455 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
11456 (SelectTruncOp[1].count(PromOp.getNode()) &&
11457 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
11458 PromOpHandles.emplace_front(PromOp);
11463 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11464 PromOp.getNode()->op_end());
11466 // If this node has constant inputs, then they'll need to be promoted here.
11467 for (unsigned i = 0; i < 2; ++i) {
11468 if (!isa<ConstantSDNode>(Ops[C+i]))
11470 if (Ops[C+i].getValueType() == N->getValueType(0))
11473 if (N->getOpcode() == ISD::SIGN_EXTEND)
11474 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11475 else if (N->getOpcode() == ISD::ZERO_EXTEND)
11476 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11478 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11481 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
11482 // truncate them again to the original value type.
11483 if (PromOp.getOpcode() == ISD::SELECT ||
11484 PromOp.getOpcode() == ISD::SELECT_CC) {
11485 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
11486 if (SI0 != SelectTruncOp[0].end())
11487 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
11488 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
11489 if (SI1 != SelectTruncOp[1].end())
11490 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
11493 DAG.ReplaceAllUsesOfValueWith(PromOp,
11494 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
11497 // Now we're left with the initial extension itself.
11498 if (!ReallyNeedsExt)
11499 return N->getOperand(0);
11501 // To zero extend, just mask off everything except for the first bit (in the
11503 if (N->getOpcode() == ISD::ZERO_EXTEND)
11504 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
11505 DAG.getConstant(APInt::getLowBitsSet(
11506 N->getValueSizeInBits(0), PromBits),
11507 dl, N->getValueType(0)));
11509 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
11510 "Invalid extension type");
11511 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
11513 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
11514 return DAG.getNode(
11515 ISD::SRA, dl, N->getValueType(0),
11516 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
11520 /// \brief Reduces the number of fp-to-int conversion when building a vector.
11522 /// If this vector is built out of floating to integer conversions,
11523 /// transform it to a vector built out of floating point values followed by a
11524 /// single floating to integer conversion of the vector.
11525 /// Namely (build_vector (fptosi $A), (fptosi $B), ...)
11526 /// becomes (fptosi (build_vector ($A, $B, ...)))
11527 SDValue PPCTargetLowering::
11528 combineElementTruncationToVectorTruncation(SDNode *N,
11529 DAGCombinerInfo &DCI) const {
11530 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11531 "Should be called with a BUILD_VECTOR node");
11533 SelectionDAG &DAG = DCI.DAG;
11536 SDValue FirstInput = N->getOperand(0);
11537 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
11538 "The input operand must be an fp-to-int conversion.");
11540 // This combine happens after legalization so the fp_to_[su]i nodes are
11541 // already converted to PPCSISD nodes.
11542 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
11543 if (FirstConversion == PPCISD::FCTIDZ ||
11544 FirstConversion == PPCISD::FCTIDUZ ||
11545 FirstConversion == PPCISD::FCTIWZ ||
11546 FirstConversion == PPCISD::FCTIWUZ) {
11547 bool IsSplat = true;
11548 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
11549 FirstConversion == PPCISD::FCTIWUZ;
11550 EVT SrcVT = FirstInput.getOperand(0).getValueType();
11551 SmallVector<SDValue, 4> Ops;
11552 EVT TargetVT = N->getValueType(0);
11553 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11554 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
11556 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
11557 if (NextConversion != FirstConversion)
11559 if (N->getOperand(i) != FirstInput)
11563 // If this is a splat, we leave it as-is since there will be only a single
11564 // fp-to-int conversion followed by a splat of the integer. This is better
11565 // for 32-bit and smaller ints and neutral for 64-bit ints.
11569 // Now that we know we have the right type of node, get its operands
11570 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11571 SDValue In = N->getOperand(i).getOperand(0);
11572 // For 32-bit values, we need to add an FP_ROUND node.
11575 Ops.push_back(DAG.getUNDEF(SrcVT));
11577 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
11578 MVT::f32, In.getOperand(0),
11579 DAG.getIntPtrConstant(1, dl));
11580 Ops.push_back(Trunc);
11583 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
11587 if (FirstConversion == PPCISD::FCTIDZ ||
11588 FirstConversion == PPCISD::FCTIWZ)
11589 Opcode = ISD::FP_TO_SINT;
11591 Opcode = ISD::FP_TO_UINT;
11593 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
11594 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
11595 return DAG.getNode(Opcode, dl, TargetVT, BV);
11600 /// \brief Reduce the number of loads when building a vector.
11602 /// Building a vector out of multiple loads can be converted to a load
11603 /// of the vector type if the loads are consecutive. If the loads are
11604 /// consecutive but in descending order, a shuffle is added at the end
11605 /// to reorder the vector.
11606 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
11607 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11608 "Should be called with a BUILD_VECTOR node");
11611 bool InputsAreConsecutiveLoads = true;
11612 bool InputsAreReverseConsecutive = true;
11613 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
11614 SDValue FirstInput = N->getOperand(0);
11615 bool IsRoundOfExtLoad = false;
11617 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
11618 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
11619 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
11620 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
11622 // Not a build vector of (possibly fp_rounded) loads.
11623 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
11626 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
11627 // If any inputs are fp_round(extload), they all must be.
11628 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
11631 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11633 if (NextInput.getOpcode() != ISD::LOAD)
11636 SDValue PreviousInput =
11637 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11638 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11639 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11641 // If any inputs are fp_round(extload), they all must be.
11642 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11645 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11646 InputsAreConsecutiveLoads = false;
11647 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11648 InputsAreReverseConsecutive = false;
11650 // Exit early if the loads are neither consecutive nor reverse consecutive.
11651 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11655 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11656 "The loads cannot be both consecutive and reverse consecutive.");
11658 SDValue FirstLoadOp =
11659 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11660 SDValue LastLoadOp =
11661 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11662 N->getOperand(N->getNumOperands()-1);
11664 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11665 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11666 if (InputsAreConsecutiveLoads) {
11667 assert(LD1 && "Input needs to be a LoadSDNode.");
11668 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11669 LD1->getBasePtr(), LD1->getPointerInfo(),
11670 LD1->getAlignment());
11672 if (InputsAreReverseConsecutive) {
11673 assert(LDL && "Input needs to be a LoadSDNode.");
11674 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11675 LDL->getBasePtr(), LDL->getPointerInfo(),
11676 LDL->getAlignment());
11677 SmallVector<int, 16> Ops;
11678 for (int i = N->getNumOperands() - 1; i >= 0; i--)
11681 return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11682 DAG.getUNDEF(N->getValueType(0)), Ops);
11687 // This function adds the required vector_shuffle needed to get
11688 // the elements of the vector extract in the correct position
11689 // as specified by the CorrectElems encoding.
11690 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
11691 SDValue Input, uint64_t Elems,
11692 uint64_t CorrectElems) {
11695 unsigned NumElems = Input.getValueType().getVectorNumElements();
11696 SmallVector<int, 16> ShuffleMask(NumElems, -1);
11698 // Knowing the element indices being extracted from the original
11699 // vector and the order in which they're being inserted, just put
11700 // them at element indices required for the instruction.
11701 for (unsigned i = 0; i < N->getNumOperands(); i++) {
11702 if (DAG.getDataLayout().isLittleEndian())
11703 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
11705 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
11706 CorrectElems = CorrectElems >> 8;
11707 Elems = Elems >> 8;
11711 DAG.getVectorShuffle(Input.getValueType(), dl, Input,
11712 DAG.getUNDEF(Input.getValueType()), ShuffleMask);
11714 EVT Ty = N->getValueType(0);
11715 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
11719 // Look for build vector patterns where input operands come from sign
11720 // extended vector_extract elements of specific indices. If the correct indices
11721 // aren't used, add a vector shuffle to fix up the indices and create a new
11722 // PPCISD:SExtVElems node which selects the vector sign extend instructions
11723 // during instruction selection.
11724 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
11725 // This array encodes the indices that the vector sign extend instructions
11726 // extract from when extending from one type to another for both BE and LE.
11727 // The right nibble of each byte corresponds to the LE incides.
11728 // and the left nibble of each byte corresponds to the BE incides.
11729 // For example: 0x3074B8FC byte->word
11730 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
11731 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
11732 // For example: 0x000070F8 byte->double word
11733 // For LE: the allowed indices are: 0x0,0x8
11734 // For BE: the allowed indices are: 0x7,0xF
11735 uint64_t TargetElems[] = {
11736 0x3074B8FC, // b->w
11737 0x000070F8, // b->d
11738 0x10325476, // h->w
11739 0x00003074, // h->d
11740 0x00001032, // w->d
11743 uint64_t Elems = 0;
11747 auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
11750 if (Op.getOpcode() != ISD::SIGN_EXTEND)
11753 SDValue Extract = Op.getOperand(0);
11754 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11757 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
11761 Index = ExtOp->getZExtValue();
11762 if (Input && Input != Extract.getOperand(0))
11766 Input = Extract.getOperand(0);
11768 Elems = Elems << 8;
11769 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
11775 // If the build vector operands aren't sign extended vector extracts,
11776 // of the same input vector, then return.
11777 for (unsigned i = 0; i < N->getNumOperands(); i++) {
11778 if (!isSExtOfVecExtract(N->getOperand(i))) {
11783 // If the vector extract indicies are not correct, add the appropriate
11785 int TgtElemArrayIdx;
11786 int InputSize = Input.getValueType().getScalarSizeInBits();
11787 int OutputSize = N->getValueType(0).getScalarSizeInBits();
11788 if (InputSize + OutputSize == 40)
11789 TgtElemArrayIdx = 0;
11790 else if (InputSize + OutputSize == 72)
11791 TgtElemArrayIdx = 1;
11792 else if (InputSize + OutputSize == 48)
11793 TgtElemArrayIdx = 2;
11794 else if (InputSize + OutputSize == 80)
11795 TgtElemArrayIdx = 3;
11796 else if (InputSize + OutputSize == 96)
11797 TgtElemArrayIdx = 4;
11801 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
11802 CorrectElems = DAG.getDataLayout().isLittleEndian()
11803 ? CorrectElems & 0x0F0F0F0F0F0F0F0F
11804 : CorrectElems & 0xF0F0F0F0F0F0F0F0;
11805 if (Elems != CorrectElems) {
11806 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
11809 // Regular lowering will catch cases where a shuffle is not needed.
11813 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11814 DAGCombinerInfo &DCI) const {
11815 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11816 "Should be called with a BUILD_VECTOR node");
11818 SelectionDAG &DAG = DCI.DAG;
11821 if (!Subtarget.hasVSX())
11824 // The target independent DAG combiner will leave a build_vector of
11825 // float-to-int conversions intact. We can generate MUCH better code for
11826 // a float-to-int conversion of a vector of floats.
11827 SDValue FirstInput = N->getOperand(0);
11828 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11829 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11834 // If we're building a vector out of consecutive loads, just load that
11836 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11840 // If we're building a vector out of extended elements from another vector
11841 // we have P9 vector integer extend instructions.
11842 if (Subtarget.hasP9Altivec()) {
11843 Reduced = combineBVOfVecSExt(N, DAG);
11849 if (N->getValueType(0) != MVT::v2f64)
11853 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11854 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11855 FirstInput.getOpcode() != ISD::UINT_TO_FP)
11857 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11858 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11860 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11863 SDValue Ext1 = FirstInput.getOperand(0);
11864 SDValue Ext2 = N->getOperand(1).getOperand(0);
11865 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11866 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11869 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11870 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11871 if (!Ext1Op || !Ext2Op)
11873 if (Ext1.getValueType() != MVT::i32 ||
11874 Ext2.getValueType() != MVT::i32)
11875 if (Ext1.getOperand(0) != Ext2.getOperand(0))
11878 int FirstElem = Ext1Op->getZExtValue();
11879 int SecondElem = Ext2Op->getZExtValue();
11881 if (FirstElem == 0 && SecondElem == 1)
11882 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11883 else if (FirstElem == 2 && SecondElem == 3)
11884 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11888 SDValue SrcVec = Ext1.getOperand(0);
11889 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11890 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11891 return DAG.getNode(NodeType, dl, MVT::v2f64,
11892 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11895 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11896 DAGCombinerInfo &DCI) const {
11897 assert((N->getOpcode() == ISD::SINT_TO_FP ||
11898 N->getOpcode() == ISD::UINT_TO_FP) &&
11899 "Need an int -> FP conversion node here");
11901 if (useSoftFloat() || !Subtarget.has64BitSupport())
11904 SelectionDAG &DAG = DCI.DAG;
11908 // Don't handle ppc_fp128 here or i1 conversions.
11909 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11911 if (Op.getOperand(0).getValueType() == MVT::i1)
11914 SDValue FirstOperand(Op.getOperand(0));
11915 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11916 (FirstOperand.getValueType() == MVT::i8 ||
11917 FirstOperand.getValueType() == MVT::i16);
11918 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11919 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11920 bool DstDouble = Op.getValueType() == MVT::f64;
11921 unsigned ConvOp = Signed ?
11922 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
11923 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11924 SDValue WidthConst =
11925 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11927 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11928 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11929 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11930 DAG.getVTList(MVT::f64, MVT::Other),
11931 Ops, MVT::i8, LDN->getMemOperand());
11933 // For signed conversion, we need to sign-extend the value in the VSR
11935 SDValue ExtOps[] = { Ld, WidthConst };
11936 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11937 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11939 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11943 // For i32 intermediate values, unfortunately, the conversion functions
11944 // leave the upper 32 bits of the value are undefined. Within the set of
11945 // scalar instructions, we have no method for zero- or sign-extending the
11946 // value. Thus, we cannot handle i32 intermediate values here.
11947 if (Op.getOperand(0).getValueType() == MVT::i32)
11950 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11951 "UINT_TO_FP is supported only with FPCVT");
11953 // If we have FCFIDS, then use it when converting to single-precision.
11954 // Otherwise, convert to double-precision and then round.
11955 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11956 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11958 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11960 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11964 // If we're converting from a float, to an int, and back to a float again,
11965 // then we don't need the store/load pair at all.
11966 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11967 Subtarget.hasFPCVT()) ||
11968 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11969 SDValue Src = Op.getOperand(0).getOperand(0);
11970 if (Src.getValueType() == MVT::f32) {
11971 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11972 DCI.AddToWorklist(Src.getNode());
11973 } else if (Src.getValueType() != MVT::f64) {
11974 // Make sure that we don't pick up a ppc_fp128 source value.
11979 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11982 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11983 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11985 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11986 FP = DAG.getNode(ISD::FP_ROUND, dl,
11987 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11988 DCI.AddToWorklist(FP.getNode());
11997 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11998 // builtins) into loads with swaps.
11999 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12000 DAGCombinerInfo &DCI) const {
12001 SelectionDAG &DAG = DCI.DAG;
12005 MachineMemOperand *MMO;
12007 switch (N->getOpcode()) {
12009 llvm_unreachable("Unexpected opcode for little endian VSX load");
12011 LoadSDNode *LD = cast<LoadSDNode>(N);
12012 Chain = LD->getChain();
12013 Base = LD->getBasePtr();
12014 MMO = LD->getMemOperand();
12015 // If the MMO suggests this isn't a load of a full vector, leave
12016 // things alone. For a built-in, we have to make the change for
12017 // correctness, so if there is a size problem that will be a bug.
12018 if (MMO->getSize() < 16)
12022 case ISD::INTRINSIC_W_CHAIN: {
12023 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12024 Chain = Intrin->getChain();
12025 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12026 // us what we want. Get operand 2 instead.
12027 Base = Intrin->getOperand(2);
12028 MMO = Intrin->getMemOperand();
12033 MVT VecTy = N->getValueType(0).getSimpleVT();
12035 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12036 // aligned and the type is a vector with elements up to 4 bytes
12037 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12038 && VecTy.getScalarSizeInBits() <= 32 ) {
12042 SDValue LoadOps[] = { Chain, Base };
12043 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12044 DAG.getVTList(MVT::v2f64, MVT::Other),
12045 LoadOps, MVT::v2f64, MMO);
12047 DCI.AddToWorklist(Load.getNode());
12048 Chain = Load.getValue(1);
12049 SDValue Swap = DAG.getNode(
12050 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12051 DCI.AddToWorklist(Swap.getNode());
12053 // Add a bitcast if the resulting load type doesn't match v2f64.
12054 if (VecTy != MVT::v2f64) {
12055 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12056 DCI.AddToWorklist(N.getNode());
12057 // Package {bitcast value, swap's chain} to match Load's shape.
12058 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12059 N, Swap.getValue(1));
12065 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12066 // builtins) into stores with swaps.
12067 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12068 DAGCombinerInfo &DCI) const {
12069 SelectionDAG &DAG = DCI.DAG;
12074 MachineMemOperand *MMO;
12076 switch (N->getOpcode()) {
12078 llvm_unreachable("Unexpected opcode for little endian VSX store");
12080 StoreSDNode *ST = cast<StoreSDNode>(N);
12081 Chain = ST->getChain();
12082 Base = ST->getBasePtr();
12083 MMO = ST->getMemOperand();
12085 // If the MMO suggests this isn't a store of a full vector, leave
12086 // things alone. For a built-in, we have to make the change for
12087 // correctness, so if there is a size problem that will be a bug.
12088 if (MMO->getSize() < 16)
12092 case ISD::INTRINSIC_VOID: {
12093 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12094 Chain = Intrin->getChain();
12095 // Intrin->getBasePtr() oddly does not get what we want.
12096 Base = Intrin->getOperand(3);
12097 MMO = Intrin->getMemOperand();
12103 SDValue Src = N->getOperand(SrcOpnd);
12104 MVT VecTy = Src.getValueType().getSimpleVT();
12106 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
12107 // aligned and the type is a vector with elements up to 4 bytes
12108 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12109 && VecTy.getScalarSizeInBits() <= 32 ) {
12113 // All stores are done as v2f64 and possible bit cast.
12114 if (VecTy != MVT::v2f64) {
12115 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
12116 DCI.AddToWorklist(Src.getNode());
12119 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
12120 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
12121 DCI.AddToWorklist(Swap.getNode());
12122 Chain = Swap.getValue(1);
12123 SDValue StoreOps[] = { Chain, Swap, Base };
12124 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
12125 DAG.getVTList(MVT::Other),
12126 StoreOps, VecTy, MMO);
12127 DCI.AddToWorklist(Store.getNode());
12131 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
12132 DAGCombinerInfo &DCI) const {
12133 SelectionDAG &DAG = DCI.DAG;
12135 switch (N->getOpcode()) {
12138 return combineSHL(N, DCI);
12140 return combineSRA(N, DCI);
12142 return combineSRL(N, DCI);
12144 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
12145 return N->getOperand(0);
12148 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
12149 return N->getOperand(0);
12152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
12153 if (C->isNullValue() || // 0 >>s V -> 0.
12154 C->isAllOnesValue()) // -1 >>s V -> -1.
12155 return N->getOperand(0);
12158 case ISD::SIGN_EXTEND:
12159 case ISD::ZERO_EXTEND:
12160 case ISD::ANY_EXTEND:
12161 return DAGCombineExtBoolTrunc(N, DCI);
12162 case ISD::TRUNCATE:
12164 case ISD::SELECT_CC:
12165 return DAGCombineTruncBoolExt(N, DCI);
12166 case ISD::SINT_TO_FP:
12167 case ISD::UINT_TO_FP:
12168 return combineFPToIntToFP(N, DCI);
12170 EVT Op1VT = N->getOperand(1).getValueType();
12171 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
12172 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
12174 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
12175 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
12176 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
12177 ValidTypeForStoreFltAsInt &&
12178 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
12179 SDValue Val = N->getOperand(1).getOperand(0);
12180 if (Val.getValueType() == MVT::f32) {
12181 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
12182 DCI.AddToWorklist(Val.getNode());
12184 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
12185 DCI.AddToWorklist(Val.getNode());
12187 if (Op1VT == MVT::i32) {
12189 N->getOperand(0), Val, N->getOperand(2),
12190 DAG.getValueType(N->getOperand(1).getValueType())
12193 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
12194 DAG.getVTList(MVT::Other), Ops,
12195 cast<StoreSDNode>(N)->getMemoryVT(),
12196 cast<StoreSDNode>(N)->getMemOperand());
12198 unsigned WidthInBytes =
12199 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
12200 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
12203 N->getOperand(0), Val, N->getOperand(2), WidthConst,
12204 DAG.getValueType(N->getOperand(1).getValueType())
12206 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
12207 DAG.getVTList(MVT::Other), Ops,
12208 cast<StoreSDNode>(N)->getMemoryVT(),
12209 cast<StoreSDNode>(N)->getMemOperand());
12212 DCI.AddToWorklist(Val.getNode());
12216 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
12217 if (cast<StoreSDNode>(N)->isUnindexed() &&
12218 N->getOperand(1).getOpcode() == ISD::BSWAP &&
12219 N->getOperand(1).getNode()->hasOneUse() &&
12220 (N->getOperand(1).getValueType() == MVT::i32 ||
12221 N->getOperand(1).getValueType() == MVT::i16 ||
12222 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12223 N->getOperand(1).getValueType() == MVT::i64))) {
12224 SDValue BSwapOp = N->getOperand(1).getOperand(0);
12225 // Do an any-extend to 32-bits if this is a half-word input.
12226 if (BSwapOp.getValueType() == MVT::i16)
12227 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
12229 // If the type of BSWAP operand is wider than stored memory width
12230 // it need to be shifted to the right side before STBRX.
12231 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
12232 if (Op1VT.bitsGT(mVT)) {
12233 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
12234 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
12235 DAG.getConstant(Shift, dl, MVT::i32));
12236 // Need to truncate if this is a bswap of i64 stored as i32/i16.
12237 if (Op1VT == MVT::i64)
12238 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
12242 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
12245 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
12246 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
12247 cast<StoreSDNode>(N)->getMemOperand());
12250 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0>
12251 // So it can increase the chance of CSE constant construction.
12252 EVT VT = N->getOperand(1).getValueType();
12253 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
12254 isa<ConstantSDNode>(N->getOperand(1)) && VT == MVT::i32) {
12255 // Need to sign-extended to 64-bits to handle negative values.
12256 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
12257 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
12258 MemVT.getSizeInBits());
12259 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
12261 // DAG.getTruncStore() can't be used here because it doesn't accept
12262 // the general (base + offset) addressing mode.
12263 // So we use UpdateNodeOperands and setTruncatingStore instead.
12264 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
12266 cast<StoreSDNode>(N)->setTruncatingStore(true);
12267 return SDValue(N, 0);
12270 // For little endian, VSX stores require generating xxswapd/lxvd2x.
12271 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12272 if (VT.isSimple()) {
12273 MVT StoreVT = VT.getSimpleVT();
12274 if (Subtarget.needsSwapsForVSXMemOps() &&
12275 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
12276 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
12277 return expandVSXStoreForLE(N, DCI);
12282 LoadSDNode *LD = cast<LoadSDNode>(N);
12283 EVT VT = LD->getValueType(0);
12285 // For little endian, VSX loads require generating lxvd2x/xxswapd.
12286 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12287 if (VT.isSimple()) {
12288 MVT LoadVT = VT.getSimpleVT();
12289 if (Subtarget.needsSwapsForVSXMemOps() &&
12290 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
12291 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
12292 return expandVSXLoadForLE(N, DCI);
12295 // We sometimes end up with a 64-bit integer load, from which we extract
12296 // two single-precision floating-point numbers. This happens with
12297 // std::complex<float>, and other similar structures, because of the way we
12298 // canonicalize structure copies. However, if we lack direct moves,
12299 // then the final bitcasts from the extracted integer values to the
12300 // floating-point numbers turn into store/load pairs. Even with direct moves,
12301 // just loading the two floating-point numbers is likely better.
12302 auto ReplaceTwoFloatLoad = [&]() {
12303 if (VT != MVT::i64)
12306 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
12310 // We're looking for a sequence like this:
12311 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
12312 // t16: i64 = srl t13, Constant:i32<32>
12313 // t17: i32 = truncate t16
12314 // t18: f32 = bitcast t17
12315 // t19: i32 = truncate t13
12316 // t20: f32 = bitcast t19
12318 if (!LD->hasNUsesOfValue(2, 0))
12321 auto UI = LD->use_begin();
12322 while (UI.getUse().getResNo() != 0) ++UI;
12323 SDNode *Trunc = *UI++;
12324 while (UI.getUse().getResNo() != 0) ++UI;
12325 SDNode *RightShift = *UI;
12326 if (Trunc->getOpcode() != ISD::TRUNCATE)
12327 std::swap(Trunc, RightShift);
12329 if (Trunc->getOpcode() != ISD::TRUNCATE ||
12330 Trunc->getValueType(0) != MVT::i32 ||
12331 !Trunc->hasOneUse())
12333 if (RightShift->getOpcode() != ISD::SRL ||
12334 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
12335 RightShift->getConstantOperandVal(1) != 32 ||
12336 !RightShift->hasOneUse())
12339 SDNode *Trunc2 = *RightShift->use_begin();
12340 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
12341 Trunc2->getValueType(0) != MVT::i32 ||
12342 !Trunc2->hasOneUse())
12345 SDNode *Bitcast = *Trunc->use_begin();
12346 SDNode *Bitcast2 = *Trunc2->use_begin();
12348 if (Bitcast->getOpcode() != ISD::BITCAST ||
12349 Bitcast->getValueType(0) != MVT::f32)
12351 if (Bitcast2->getOpcode() != ISD::BITCAST ||
12352 Bitcast2->getValueType(0) != MVT::f32)
12355 if (Subtarget.isLittleEndian())
12356 std::swap(Bitcast, Bitcast2);
12358 // Bitcast has the second float (in memory-layout order) and Bitcast2
12359 // has the first one.
12361 SDValue BasePtr = LD->getBasePtr();
12362 if (LD->isIndexed()) {
12363 assert(LD->getAddressingMode() == ISD::PRE_INC &&
12364 "Non-pre-inc AM on PPC?");
12366 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12371 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
12372 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
12373 LD->getPointerInfo(), LD->getAlignment(),
12374 MMOFlags, LD->getAAInfo());
12376 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
12377 BasePtr, DAG.getIntPtrConstant(4, dl));
12378 SDValue FloatLoad2 = DAG.getLoad(
12379 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
12380 LD->getPointerInfo().getWithOffset(4),
12381 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
12383 if (LD->isIndexed()) {
12384 // Note that DAGCombine should re-form any pre-increment load(s) from
12385 // what is produced here if that makes sense.
12386 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
12389 DCI.CombineTo(Bitcast2, FloatLoad);
12390 DCI.CombineTo(Bitcast, FloatLoad2);
12392 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
12393 SDValue(FloatLoad2.getNode(), 1));
12397 if (ReplaceTwoFloatLoad())
12398 return SDValue(N, 0);
12400 EVT MemVT = LD->getMemoryVT();
12401 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
12402 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
12403 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
12404 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
12405 if (LD->isUnindexed() && VT.isVector() &&
12406 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
12407 // P8 and later hardware should just use LOAD.
12408 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
12409 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
12410 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
12411 LD->getAlignment() >= ScalarABIAlignment)) &&
12412 LD->getAlignment() < ABIAlignment) {
12413 // This is a type-legal unaligned Altivec or QPX load.
12414 SDValue Chain = LD->getChain();
12415 SDValue Ptr = LD->getBasePtr();
12416 bool isLittleEndian = Subtarget.isLittleEndian();
12418 // This implements the loading of unaligned vectors as described in
12419 // the venerable Apple Velocity Engine overview. Specifically:
12420 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
12421 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
12423 // The general idea is to expand a sequence of one or more unaligned
12424 // loads into an alignment-based permutation-control instruction (lvsl
12425 // or lvsr), a series of regular vector loads (which always truncate
12426 // their input address to an aligned address), and a series of
12427 // permutations. The results of these permutations are the requested
12428 // loaded values. The trick is that the last "extra" load is not taken
12429 // from the address you might suspect (sizeof(vector) bytes after the
12430 // last requested load), but rather sizeof(vector) - 1 bytes after the
12431 // last requested vector. The point of this is to avoid a page fault if
12432 // the base address happened to be aligned. This works because if the
12433 // base address is aligned, then adding less than a full vector length
12434 // will cause the last vector in the sequence to be (re)loaded.
12435 // Otherwise, the next vector will be fetched as you might suspect was
12438 // We might be able to reuse the permutation generation from
12439 // a different base address offset from this one by an aligned amount.
12440 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
12441 // optimization later.
12442 Intrinsic::ID Intr, IntrLD, IntrPerm;
12443 MVT PermCntlTy, PermTy, LDTy;
12444 if (Subtarget.hasAltivec()) {
12445 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
12446 Intrinsic::ppc_altivec_lvsl;
12447 IntrLD = Intrinsic::ppc_altivec_lvx;
12448 IntrPerm = Intrinsic::ppc_altivec_vperm;
12449 PermCntlTy = MVT::v16i8;
12450 PermTy = MVT::v4i32;
12453 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
12454 Intrinsic::ppc_qpx_qvlpcls;
12455 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
12456 Intrinsic::ppc_qpx_qvlfs;
12457 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
12458 PermCntlTy = MVT::v4f64;
12459 PermTy = MVT::v4f64;
12460 LDTy = MemVT.getSimpleVT();
12463 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
12465 // Create the new MMO for the new base load. It is like the original MMO,
12466 // but represents an area in memory almost twice the vector size centered
12467 // on the original address. If the address is unaligned, we might start
12468 // reading up to (sizeof(vector)-1) bytes below the address of the
12469 // original unaligned load.
12470 MachineFunction &MF = DAG.getMachineFunction();
12471 MachineMemOperand *BaseMMO =
12472 MF.getMachineMemOperand(LD->getMemOperand(),
12473 -(long)MemVT.getStoreSize()+1,
12474 2*MemVT.getStoreSize()-1);
12476 // Create the new base load.
12478 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
12479 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
12481 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12482 DAG.getVTList(PermTy, MVT::Other),
12483 BaseLoadOps, LDTy, BaseMMO);
12485 // Note that the value of IncOffset (which is provided to the next
12486 // load's pointer info offset value, and thus used to calculate the
12487 // alignment), and the value of IncValue (which is actually used to
12488 // increment the pointer value) are different! This is because we
12489 // require the next load to appear to be aligned, even though it
12490 // is actually offset from the base pointer by a lesser amount.
12491 int IncOffset = VT.getSizeInBits() / 8;
12492 int IncValue = IncOffset;
12494 // Walk (both up and down) the chain looking for another load at the real
12495 // (aligned) offset (the alignment of the other load does not matter in
12496 // this case). If found, then do not use the offset reduction trick, as
12497 // that will prevent the loads from being later combined (as they would
12498 // otherwise be duplicates).
12499 if (!findConsecutiveLoad(LD, DAG))
12502 SDValue Increment =
12503 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
12504 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
12506 MachineMemOperand *ExtraMMO =
12507 MF.getMachineMemOperand(LD->getMemOperand(),
12508 1, 2*MemVT.getStoreSize()-1);
12509 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
12510 SDValue ExtraLoad =
12511 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12512 DAG.getVTList(PermTy, MVT::Other),
12513 ExtraLoadOps, LDTy, ExtraMMO);
12515 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
12516 BaseLoad.getValue(1), ExtraLoad.getValue(1));
12518 // Because vperm has a big-endian bias, we must reverse the order
12519 // of the input vectors and complement the permute control vector
12520 // when generating little endian code. We have already handled the
12521 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
12522 // and ExtraLoad here.
12524 if (isLittleEndian)
12525 Perm = BuildIntrinsicOp(IntrPerm,
12526 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
12528 Perm = BuildIntrinsicOp(IntrPerm,
12529 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
12532 Perm = Subtarget.hasAltivec() ?
12533 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
12534 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
12535 DAG.getTargetConstant(1, dl, MVT::i64));
12536 // second argument is 1 because this rounding
12537 // is always exact.
12539 // The output of the permutation is our loaded result, the TokenFactor is
12541 DCI.CombineTo(N, Perm, TF);
12542 return SDValue(N, 0);
12546 case ISD::INTRINSIC_WO_CHAIN: {
12547 bool isLittleEndian = Subtarget.isLittleEndian();
12548 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12549 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
12550 : Intrinsic::ppc_altivec_lvsl);
12551 if ((IID == Intr ||
12552 IID == Intrinsic::ppc_qpx_qvlpcld ||
12553 IID == Intrinsic::ppc_qpx_qvlpcls) &&
12554 N->getOperand(1)->getOpcode() == ISD::ADD) {
12555 SDValue Add = N->getOperand(1);
12557 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
12558 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
12560 if (DAG.MaskedValueIsZero(Add->getOperand(1),
12561 APInt::getAllOnesValue(Bits /* alignment */)
12562 .zext(Add.getScalarValueSizeInBits()))) {
12563 SDNode *BasePtr = Add->getOperand(0).getNode();
12564 for (SDNode::use_iterator UI = BasePtr->use_begin(),
12565 UE = BasePtr->use_end();
12567 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12568 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
12569 // We've found another LVSL/LVSR, and this address is an aligned
12570 // multiple of that one. The results will be the same, so use the
12571 // one we've just found instead.
12573 return SDValue(*UI, 0);
12578 if (isa<ConstantSDNode>(Add->getOperand(1))) {
12579 SDNode *BasePtr = Add->getOperand(0).getNode();
12580 for (SDNode::use_iterator UI = BasePtr->use_begin(),
12581 UE = BasePtr->use_end(); UI != UE; ++UI) {
12582 if (UI->getOpcode() == ISD::ADD &&
12583 isa<ConstantSDNode>(UI->getOperand(1)) &&
12584 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
12585 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
12586 (1ULL << Bits) == 0) {
12587 SDNode *OtherAdd = *UI;
12588 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
12589 VE = OtherAdd->use_end(); VI != VE; ++VI) {
12590 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12591 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
12592 return SDValue(*VI, 0);
12602 case ISD::INTRINSIC_W_CHAIN:
12603 // For little endian, VSX loads require generating lxvd2x/xxswapd.
12604 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12605 if (Subtarget.needsSwapsForVSXMemOps()) {
12606 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12609 case Intrinsic::ppc_vsx_lxvw4x:
12610 case Intrinsic::ppc_vsx_lxvd2x:
12611 return expandVSXLoadForLE(N, DCI);
12615 case ISD::INTRINSIC_VOID:
12616 // For little endian, VSX stores require generating xxswapd/stxvd2x.
12617 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12618 if (Subtarget.needsSwapsForVSXMemOps()) {
12619 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12622 case Intrinsic::ppc_vsx_stxvw4x:
12623 case Intrinsic::ppc_vsx_stxvd2x:
12624 return expandVSXStoreForLE(N, DCI);
12629 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
12630 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
12631 N->getOperand(0).hasOneUse() &&
12632 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
12633 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12634 N->getValueType(0) == MVT::i64))) {
12635 SDValue Load = N->getOperand(0);
12636 LoadSDNode *LD = cast<LoadSDNode>(Load);
12637 // Create the byte-swapping load.
12639 LD->getChain(), // Chain
12640 LD->getBasePtr(), // Ptr
12641 DAG.getValueType(N->getValueType(0)) // VT
12644 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
12645 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
12646 MVT::i64 : MVT::i32, MVT::Other),
12647 Ops, LD->getMemoryVT(), LD->getMemOperand());
12649 // If this is an i16 load, insert the truncate.
12650 SDValue ResVal = BSLoad;
12651 if (N->getValueType(0) == MVT::i16)
12652 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
12654 // First, combine the bswap away. This makes the value produced by the
12656 DCI.CombineTo(N, ResVal);
12658 // Next, combine the load away, we give it a bogus result value but a real
12659 // chain result. The result value is dead because the bswap is dead.
12660 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
12662 // Return N so it doesn't get rechecked!
12663 return SDValue(N, 0);
12667 // If a VCMPo node already exists with exactly the same operands as this
12668 // node, use its result instead of this node (VCMPo computes both a CR6 and
12669 // a normal output).
12671 if (!N->getOperand(0).hasOneUse() &&
12672 !N->getOperand(1).hasOneUse() &&
12673 !N->getOperand(2).hasOneUse()) {
12675 // Scan all of the users of the LHS, looking for VCMPo's that match.
12676 SDNode *VCMPoNode = nullptr;
12678 SDNode *LHSN = N->getOperand(0).getNode();
12679 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
12681 if (UI->getOpcode() == PPCISD::VCMPo &&
12682 UI->getOperand(1) == N->getOperand(1) &&
12683 UI->getOperand(2) == N->getOperand(2) &&
12684 UI->getOperand(0) == N->getOperand(0)) {
12689 // If there is no VCMPo node, or if the flag value has a single use, don't
12691 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
12694 // Look at the (necessarily single) use of the flag value. If it has a
12695 // chain, this transformation is more complex. Note that multiple things
12696 // could use the value result, which we should ignore.
12697 SDNode *FlagUser = nullptr;
12698 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
12699 FlagUser == nullptr; ++UI) {
12700 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
12701 SDNode *User = *UI;
12702 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
12703 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
12710 // If the user is a MFOCRF instruction, we know this is safe.
12711 // Otherwise we give up for right now.
12712 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
12713 return SDValue(VCMPoNode, 0);
12716 case ISD::BRCOND: {
12717 SDValue Cond = N->getOperand(1);
12718 SDValue Target = N->getOperand(2);
12720 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12721 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
12722 Intrinsic::ppc_is_decremented_ctr_nonzero) {
12724 // We now need to make the intrinsic dead (it cannot be instruction
12726 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
12727 assert(Cond.getNode()->hasOneUse() &&
12728 "Counter decrement has more than one use");
12730 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
12731 N->getOperand(0), Target);
12736 // If this is a branch on an altivec predicate comparison, lower this so
12737 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
12738 // lowering is done pre-legalize, because the legalizer lowers the predicate
12739 // compare down to code that is difficult to reassemble.
12740 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
12741 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
12743 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
12744 // value. If so, pass-through the AND to get to the intrinsic.
12745 if (LHS.getOpcode() == ISD::AND &&
12746 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12747 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
12748 Intrinsic::ppc_is_decremented_ctr_nonzero &&
12749 isa<ConstantSDNode>(LHS.getOperand(1)) &&
12750 !isNullConstant(LHS.getOperand(1)))
12751 LHS = LHS.getOperand(0);
12753 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12754 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
12755 Intrinsic::ppc_is_decremented_ctr_nonzero &&
12756 isa<ConstantSDNode>(RHS)) {
12757 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
12758 "Counter decrement comparison is not EQ or NE");
12760 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12761 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
12762 (CC == ISD::SETNE && !Val);
12764 // We now need to make the intrinsic dead (it cannot be instruction
12766 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
12767 assert(LHS.getNode()->hasOneUse() &&
12768 "Counter decrement has more than one use");
12770 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
12771 N->getOperand(0), N->getOperand(4));
12777 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12778 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
12779 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
12780 assert(isDot && "Can't compare against a vector result!");
12782 // If this is a comparison against something other than 0/1, then we know
12783 // that the condition is never/always true.
12784 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12785 if (Val != 0 && Val != 1) {
12786 if (CC == ISD::SETEQ) // Cond never true, remove branch.
12787 return N->getOperand(0);
12788 // Always !=, turn it into an unconditional branch.
12789 return DAG.getNode(ISD::BR, dl, MVT::Other,
12790 N->getOperand(0), N->getOperand(4));
12793 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
12795 // Create the PPCISD altivec 'dot' comparison node.
12797 LHS.getOperand(2), // LHS of compare
12798 LHS.getOperand(3), // RHS of compare
12799 DAG.getConstant(CompareOpc, dl, MVT::i32)
12801 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
12802 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12804 // Unpack the result based on how the target uses it.
12805 PPC::Predicate CompOpc;
12806 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12807 default: // Can't happen, don't crash on invalid number though.
12808 case 0: // Branch on the value of the EQ bit of CR6.
12809 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12811 case 1: // Branch on the inverted value of the EQ bit of CR6.
12812 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12814 case 2: // Branch on the value of the LT bit of CR6.
12815 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12817 case 3: // Branch on the inverted value of the LT bit of CR6.
12818 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12822 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12823 DAG.getConstant(CompOpc, dl, MVT::i32),
12824 DAG.getRegister(PPC::CR6, MVT::i32),
12825 N->getOperand(4), CompNode.getValue(1));
12829 case ISD::BUILD_VECTOR:
12830 return DAGCombineBuildVector(N, DCI);
12837 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12839 std::vector<SDNode *> *Created) const {
12840 // fold (sdiv X, pow2)
12841 EVT VT = N->getValueType(0);
12842 if (VT == MVT::i64 && !Subtarget.isPPC64())
12844 if ((VT != MVT::i32 && VT != MVT::i64) ||
12845 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12849 SDValue N0 = N->getOperand(0);
12851 bool IsNegPow2 = (-Divisor).isPowerOf2();
12852 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12853 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12855 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12857 Created->push_back(Op.getNode());
12860 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12862 Created->push_back(Op.getNode());
12868 //===----------------------------------------------------------------------===//
12869 // Inline Assembly Support
12870 //===----------------------------------------------------------------------===//
12872 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12874 const APInt &DemandedElts,
12875 const SelectionDAG &DAG,
12876 unsigned Depth) const {
12878 switch (Op.getOpcode()) {
12880 case PPCISD::LBRX: {
12881 // lhbrx is known to have the top bits cleared out.
12882 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12883 Known.Zero = 0xFFFF0000;
12886 case ISD::INTRINSIC_WO_CHAIN: {
12887 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12889 case Intrinsic::ppc_altivec_vcmpbfp_p:
12890 case Intrinsic::ppc_altivec_vcmpeqfp_p:
12891 case Intrinsic::ppc_altivec_vcmpequb_p:
12892 case Intrinsic::ppc_altivec_vcmpequh_p:
12893 case Intrinsic::ppc_altivec_vcmpequw_p:
12894 case Intrinsic::ppc_altivec_vcmpequd_p:
12895 case Intrinsic::ppc_altivec_vcmpgefp_p:
12896 case Intrinsic::ppc_altivec_vcmpgtfp_p:
12897 case Intrinsic::ppc_altivec_vcmpgtsb_p:
12898 case Intrinsic::ppc_altivec_vcmpgtsh_p:
12899 case Intrinsic::ppc_altivec_vcmpgtsw_p:
12900 case Intrinsic::ppc_altivec_vcmpgtsd_p:
12901 case Intrinsic::ppc_altivec_vcmpgtub_p:
12902 case Intrinsic::ppc_altivec_vcmpgtuh_p:
12903 case Intrinsic::ppc_altivec_vcmpgtuw_p:
12904 case Intrinsic::ppc_altivec_vcmpgtud_p:
12905 Known.Zero = ~1U; // All bits but the low one are known to be zero.
12912 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12913 switch (Subtarget.getDarwinDirective()) {
12916 case PPC::DIR_PWR4:
12917 case PPC::DIR_PWR5:
12918 case PPC::DIR_PWR5X:
12919 case PPC::DIR_PWR6:
12920 case PPC::DIR_PWR6X:
12921 case PPC::DIR_PWR7:
12922 case PPC::DIR_PWR8:
12923 case PPC::DIR_PWR9: {
12927 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12929 // For small loops (between 5 and 8 instructions), align to a 32-byte
12930 // boundary so that the entire loop fits in one instruction-cache line.
12931 uint64_t LoopSize = 0;
12932 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12933 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12934 LoopSize += TII->getInstSizeInBytes(*J);
12939 if (LoopSize > 16 && LoopSize <= 32)
12946 return TargetLowering::getPrefLoopAlignment(ML);
12949 /// getConstraintType - Given a constraint, return the type of
12950 /// constraint it is for this target.
12951 PPCTargetLowering::ConstraintType
12952 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12953 if (Constraint.size() == 1) {
12954 switch (Constraint[0]) {
12962 return C_RegisterClass;
12964 // FIXME: While Z does indicate a memory constraint, it specifically
12965 // indicates an r+r address (used in conjunction with the 'y' modifier
12966 // in the replacement string). Currently, we're forcing the base
12967 // register to be r0 in the asm printer (which is interpreted as zero)
12968 // and forming the complete address in the second register. This is
12972 } else if (Constraint == "wc") { // individual CR bits.
12973 return C_RegisterClass;
12974 } else if (Constraint == "wa" || Constraint == "wd" ||
12975 Constraint == "wf" || Constraint == "ws") {
12976 return C_RegisterClass; // VSX registers.
12978 return TargetLowering::getConstraintType(Constraint);
12981 /// Examine constraint type and operand type and determine a weight value.
12982 /// This object must already have been set up with the operand type
12983 /// and the current alternative constraint selected.
12984 TargetLowering::ConstraintWeight
12985 PPCTargetLowering::getSingleConstraintMatchWeight(
12986 AsmOperandInfo &info, const char *constraint) const {
12987 ConstraintWeight weight = CW_Invalid;
12988 Value *CallOperandVal = info.CallOperandVal;
12989 // If we don't have a value, we can't do a match,
12990 // but allow it at the lowest weight.
12991 if (!CallOperandVal)
12993 Type *type = CallOperandVal->getType();
12995 // Look at the constraint type.
12996 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12997 return CW_Register; // an individual CR bit.
12998 else if ((StringRef(constraint) == "wa" ||
12999 StringRef(constraint) == "wd" ||
13000 StringRef(constraint) == "wf") &&
13001 type->isVectorTy())
13002 return CW_Register;
13003 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
13004 return CW_Register;
13006 switch (*constraint) {
13008 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13011 if (type->isIntegerTy())
13012 weight = CW_Register;
13015 if (type->isFloatTy())
13016 weight = CW_Register;
13019 if (type->isDoubleTy())
13020 weight = CW_Register;
13023 if (type->isVectorTy())
13024 weight = CW_Register;
13027 weight = CW_Register;
13030 weight = CW_Memory;
13036 std::pair<unsigned, const TargetRegisterClass *>
13037 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
13038 StringRef Constraint,
13040 if (Constraint.size() == 1) {
13041 // GCC RS6000 Constraint Letters
13042 switch (Constraint[0]) {
13043 case 'b': // R1-R31
13044 if (VT == MVT::i64 && Subtarget.isPPC64())
13045 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
13046 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
13047 case 'r': // R0-R31
13048 if (VT == MVT::i64 && Subtarget.isPPC64())
13049 return std::make_pair(0U, &PPC::G8RCRegClass);
13050 return std::make_pair(0U, &PPC::GPRCRegClass);
13051 // 'd' and 'f' constraints are both defined to be "the floating point
13052 // registers", where one is for 32-bit and the other for 64-bit. We don't
13053 // really care overly much here so just give them all the same reg classes.
13056 if (VT == MVT::f32 || VT == MVT::i32)
13057 return std::make_pair(0U, &PPC::F4RCRegClass);
13058 if (VT == MVT::f64 || VT == MVT::i64)
13059 return std::make_pair(0U, &PPC::F8RCRegClass);
13060 if (VT == MVT::v4f64 && Subtarget.hasQPX())
13061 return std::make_pair(0U, &PPC::QFRCRegClass);
13062 if (VT == MVT::v4f32 && Subtarget.hasQPX())
13063 return std::make_pair(0U, &PPC::QSRCRegClass);
13066 if (VT == MVT::v4f64 && Subtarget.hasQPX())
13067 return std::make_pair(0U, &PPC::QFRCRegClass);
13068 if (VT == MVT::v4f32 && Subtarget.hasQPX())
13069 return std::make_pair(0U, &PPC::QSRCRegClass);
13070 if (Subtarget.hasAltivec())
13071 return std::make_pair(0U, &PPC::VRRCRegClass);
13074 return std::make_pair(0U, &PPC::CRRCRegClass);
13076 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
13077 // An individual CR bit.
13078 return std::make_pair(0U, &PPC::CRBITRCRegClass);
13079 } else if ((Constraint == "wa" || Constraint == "wd" ||
13080 Constraint == "wf") && Subtarget.hasVSX()) {
13081 return std::make_pair(0U, &PPC::VSRCRegClass);
13082 } else if (Constraint == "ws" && Subtarget.hasVSX()) {
13083 if (VT == MVT::f32 && Subtarget.hasP8Vector())
13084 return std::make_pair(0U, &PPC::VSSRCRegClass);
13086 return std::make_pair(0U, &PPC::VSFRCRegClass);
13089 std::pair<unsigned, const TargetRegisterClass *> R =
13090 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13092 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
13093 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
13094 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
13096 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
13097 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
13098 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
13099 PPC::GPRCRegClass.contains(R.first))
13100 return std::make_pair(TRI->getMatchingSuperReg(R.first,
13101 PPC::sub_32, &PPC::G8RCRegClass),
13102 &PPC::G8RCRegClass);
13104 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
13105 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
13106 R.first = PPC::CR0;
13107 R.second = &PPC::CRRCRegClass;
13113 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13114 /// vector. If it is invalid, don't add anything to Ops.
13115 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13116 std::string &Constraint,
13117 std::vector<SDValue>&Ops,
13118 SelectionDAG &DAG) const {
13121 // Only support length 1 constraints.
13122 if (Constraint.length() > 1) return;
13124 char Letter = Constraint[0];
13135 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
13136 if (!CST) return; // Must be an immediate to match.
13138 int64_t Value = CST->getSExtValue();
13139 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
13140 // numbers are printed as such.
13142 default: llvm_unreachable("Unknown constraint letter!");
13143 case 'I': // "I" is a signed 16-bit constant.
13144 if (isInt<16>(Value))
13145 Result = DAG.getTargetConstant(Value, dl, TCVT);
13147 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
13148 if (isShiftedUInt<16, 16>(Value))
13149 Result = DAG.getTargetConstant(Value, dl, TCVT);
13151 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
13152 if (isShiftedInt<16, 16>(Value))
13153 Result = DAG.getTargetConstant(Value, dl, TCVT);
13155 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
13156 if (isUInt<16>(Value))
13157 Result = DAG.getTargetConstant(Value, dl, TCVT);
13159 case 'M': // "M" is a constant that is greater than 31.
13161 Result = DAG.getTargetConstant(Value, dl, TCVT);
13163 case 'N': // "N" is a positive constant that is an exact power of two.
13164 if (Value > 0 && isPowerOf2_64(Value))
13165 Result = DAG.getTargetConstant(Value, dl, TCVT);
13167 case 'O': // "O" is the constant zero.
13169 Result = DAG.getTargetConstant(Value, dl, TCVT);
13171 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
13172 if (isInt<16>(-Value))
13173 Result = DAG.getTargetConstant(Value, dl, TCVT);
13180 if (Result.getNode()) {
13181 Ops.push_back(Result);
13185 // Handle standard constraint letters.
13186 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13189 // isLegalAddressingMode - Return true if the addressing mode represented
13190 // by AM is legal for this target, for a load/store of the specified type.
13191 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13192 const AddrMode &AM, Type *Ty,
13193 unsigned AS, Instruction *I) const {
13194 // PPC does not allow r+i addressing modes for vectors!
13195 if (Ty->isVectorTy() && AM.BaseOffs != 0)
13198 // PPC allows a sign-extended 16-bit immediate field.
13199 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
13202 // No global is ever allowed as a base.
13206 // PPC only support r+r,
13207 switch (AM.Scale) {
13208 case 0: // "r+i" or just "i", depending on HasBaseReg.
13211 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
13213 // Otherwise we have r+r or r+i.
13216 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
13218 // Allow 2*r as r+r.
13221 // No other scales are supported.
13228 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
13229 SelectionDAG &DAG) const {
13230 MachineFunction &MF = DAG.getMachineFunction();
13231 MachineFrameInfo &MFI = MF.getFrameInfo();
13232 MFI.setReturnAddressIsTaken(true);
13234 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13238 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13240 // Make sure the function does not optimize away the store of the RA to
13242 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
13243 FuncInfo->setLRStoreRequired();
13244 bool isPPC64 = Subtarget.isPPC64();
13245 auto PtrVT = getPointerTy(MF.getDataLayout());
13248 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13250 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
13251 isPPC64 ? MVT::i64 : MVT::i32);
13252 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13253 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
13254 MachinePointerInfo());
13257 // Just load the return address off the stack.
13258 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
13259 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
13260 MachinePointerInfo());
13263 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
13264 SelectionDAG &DAG) const {
13266 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13268 MachineFunction &MF = DAG.getMachineFunction();
13269 MachineFrameInfo &MFI = MF.getFrameInfo();
13270 MFI.setFrameAddressIsTaken(true);
13272 EVT PtrVT = getPointerTy(MF.getDataLayout());
13273 bool isPPC64 = PtrVT == MVT::i64;
13275 // Naked functions never have a frame pointer, and so we use r1. For all
13276 // other functions, this decision must be delayed until during PEI.
13278 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
13279 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
13281 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
13283 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
13286 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
13287 FrameAddr, MachinePointerInfo());
13291 // FIXME? Maybe this could be a TableGen attribute on some registers and
13292 // this table could be generated automatically from RegInfo.
13293 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
13294 SelectionDAG &DAG) const {
13295 bool isPPC64 = Subtarget.isPPC64();
13296 bool isDarwinABI = Subtarget.isDarwinABI();
13298 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
13299 (!isPPC64 && VT != MVT::i32))
13300 report_fatal_error("Invalid register global variable type");
13302 bool is64Bit = isPPC64 && VT == MVT::i64;
13303 unsigned Reg = StringSwitch<unsigned>(RegName)
13304 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
13305 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
13306 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
13307 (is64Bit ? PPC::X13 : PPC::R13))
13312 report_fatal_error("Invalid register name global variable");
13316 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13317 // The PowerPC target isn't yet aware of offsets.
13321 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13323 MachineFunction &MF,
13324 unsigned Intrinsic) const {
13325 switch (Intrinsic) {
13326 case Intrinsic::ppc_qpx_qvlfd:
13327 case Intrinsic::ppc_qpx_qvlfs:
13328 case Intrinsic::ppc_qpx_qvlfcd:
13329 case Intrinsic::ppc_qpx_qvlfcs:
13330 case Intrinsic::ppc_qpx_qvlfiwa:
13331 case Intrinsic::ppc_qpx_qvlfiwz:
13332 case Intrinsic::ppc_altivec_lvx:
13333 case Intrinsic::ppc_altivec_lvxl:
13334 case Intrinsic::ppc_altivec_lvebx:
13335 case Intrinsic::ppc_altivec_lvehx:
13336 case Intrinsic::ppc_altivec_lvewx:
13337 case Intrinsic::ppc_vsx_lxvd2x:
13338 case Intrinsic::ppc_vsx_lxvw4x: {
13340 switch (Intrinsic) {
13341 case Intrinsic::ppc_altivec_lvebx:
13344 case Intrinsic::ppc_altivec_lvehx:
13347 case Intrinsic::ppc_altivec_lvewx:
13350 case Intrinsic::ppc_vsx_lxvd2x:
13353 case Intrinsic::ppc_qpx_qvlfd:
13356 case Intrinsic::ppc_qpx_qvlfs:
13359 case Intrinsic::ppc_qpx_qvlfcd:
13362 case Intrinsic::ppc_qpx_qvlfcs:
13370 Info.opc = ISD::INTRINSIC_W_CHAIN;
13372 Info.ptrVal = I.getArgOperand(0);
13373 Info.offset = -VT.getStoreSize()+1;
13374 Info.size = 2*VT.getStoreSize()-1;
13376 Info.flags = MachineMemOperand::MOLoad;
13379 case Intrinsic::ppc_qpx_qvlfda:
13380 case Intrinsic::ppc_qpx_qvlfsa:
13381 case Intrinsic::ppc_qpx_qvlfcda:
13382 case Intrinsic::ppc_qpx_qvlfcsa:
13383 case Intrinsic::ppc_qpx_qvlfiwaa:
13384 case Intrinsic::ppc_qpx_qvlfiwza: {
13386 switch (Intrinsic) {
13387 case Intrinsic::ppc_qpx_qvlfda:
13390 case Intrinsic::ppc_qpx_qvlfsa:
13393 case Intrinsic::ppc_qpx_qvlfcda:
13396 case Intrinsic::ppc_qpx_qvlfcsa:
13404 Info.opc = ISD::INTRINSIC_W_CHAIN;
13406 Info.ptrVal = I.getArgOperand(0);
13408 Info.size = VT.getStoreSize();
13410 Info.flags = MachineMemOperand::MOLoad;
13413 case Intrinsic::ppc_qpx_qvstfd:
13414 case Intrinsic::ppc_qpx_qvstfs:
13415 case Intrinsic::ppc_qpx_qvstfcd:
13416 case Intrinsic::ppc_qpx_qvstfcs:
13417 case Intrinsic::ppc_qpx_qvstfiw:
13418 case Intrinsic::ppc_altivec_stvx:
13419 case Intrinsic::ppc_altivec_stvxl:
13420 case Intrinsic::ppc_altivec_stvebx:
13421 case Intrinsic::ppc_altivec_stvehx:
13422 case Intrinsic::ppc_altivec_stvewx:
13423 case Intrinsic::ppc_vsx_stxvd2x:
13424 case Intrinsic::ppc_vsx_stxvw4x: {
13426 switch (Intrinsic) {
13427 case Intrinsic::ppc_altivec_stvebx:
13430 case Intrinsic::ppc_altivec_stvehx:
13433 case Intrinsic::ppc_altivec_stvewx:
13436 case Intrinsic::ppc_vsx_stxvd2x:
13439 case Intrinsic::ppc_qpx_qvstfd:
13442 case Intrinsic::ppc_qpx_qvstfs:
13445 case Intrinsic::ppc_qpx_qvstfcd:
13448 case Intrinsic::ppc_qpx_qvstfcs:
13456 Info.opc = ISD::INTRINSIC_VOID;
13458 Info.ptrVal = I.getArgOperand(1);
13459 Info.offset = -VT.getStoreSize()+1;
13460 Info.size = 2*VT.getStoreSize()-1;
13462 Info.flags = MachineMemOperand::MOStore;
13465 case Intrinsic::ppc_qpx_qvstfda:
13466 case Intrinsic::ppc_qpx_qvstfsa:
13467 case Intrinsic::ppc_qpx_qvstfcda:
13468 case Intrinsic::ppc_qpx_qvstfcsa:
13469 case Intrinsic::ppc_qpx_qvstfiwa: {
13471 switch (Intrinsic) {
13472 case Intrinsic::ppc_qpx_qvstfda:
13475 case Intrinsic::ppc_qpx_qvstfsa:
13478 case Intrinsic::ppc_qpx_qvstfcda:
13481 case Intrinsic::ppc_qpx_qvstfcsa:
13489 Info.opc = ISD::INTRINSIC_VOID;
13491 Info.ptrVal = I.getArgOperand(1);
13493 Info.size = VT.getStoreSize();
13495 Info.flags = MachineMemOperand::MOStore;
13505 /// getOptimalMemOpType - Returns the target specific optimal type for load
13506 /// and store operations as a result of memset, memcpy, and memmove
13507 /// lowering. If DstAlign is zero that means it's safe to destination
13508 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
13509 /// means there isn't a need to check it against alignment requirement,
13510 /// probably because the source does not need to be loaded. If 'IsMemset' is
13511 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
13512 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
13513 /// source is constant so it does not need to be loaded.
13514 /// It returns EVT::Other if the type should be determined using generic
13515 /// target-independent logic.
13516 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
13517 unsigned DstAlign, unsigned SrcAlign,
13518 bool IsMemset, bool ZeroMemset,
13520 MachineFunction &MF) const {
13521 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
13522 const Function &F = MF.getFunction();
13523 // When expanding a memset, require at least two QPX instructions to cover
13524 // the cost of loading the value to be stored from the constant pool.
13525 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
13526 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
13527 !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
13531 // We should use Altivec/VSX loads and stores when available. For unaligned
13532 // addresses, unaligned VSX loads are only fast starting with the P8.
13533 if (Subtarget.hasAltivec() && Size >= 16 &&
13534 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
13535 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
13539 if (Subtarget.isPPC64()) {
13546 /// \brief Returns true if it is beneficial to convert a load of a constant
13547 /// to just the constant itself.
13548 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13550 assert(Ty->isIntegerTy());
13552 unsigned BitSize = Ty->getPrimitiveSizeInBits();
13553 return !(BitSize == 0 || BitSize > 64);
13556 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13557 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13559 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13560 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13561 return NumBits1 == 64 && NumBits2 == 32;
13564 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13565 if (!VT1.isInteger() || !VT2.isInteger())
13567 unsigned NumBits1 = VT1.getSizeInBits();
13568 unsigned NumBits2 = VT2.getSizeInBits();
13569 return NumBits1 == 64 && NumBits2 == 32;
13572 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13573 // Generally speaking, zexts are not free, but they are free when they can be
13574 // folded with other operations.
13575 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
13576 EVT MemVT = LD->getMemoryVT();
13577 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
13578 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
13579 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
13580 LD->getExtensionType() == ISD::ZEXTLOAD))
13584 // FIXME: Add other cases...
13585 // - 32-bit shifts with a zext to i64
13586 // - zext after ctlz, bswap, etc.
13587 // - zext after and by a constant mask
13589 return TargetLowering::isZExtFree(Val, VT2);
13592 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
13593 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
13594 "invalid fpext types");
13598 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13599 return isInt<16>(Imm) || isUInt<16>(Imm);
13602 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13603 return isInt<16>(Imm) || isUInt<16>(Imm);
13606 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
13609 bool *Fast) const {
13610 if (DisablePPCUnaligned)
13613 // PowerPC supports unaligned memory access for simple non-vector types.
13614 // Although accessing unaligned addresses is not as efficient as accessing
13615 // aligned addresses, it is generally more efficient than manual expansion,
13616 // and generally only traps for software emulation when crossing page
13619 if (!VT.isSimple())
13622 if (VT.getSimpleVT().isVector()) {
13623 if (Subtarget.hasVSX()) {
13624 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
13625 VT != MVT::v4f32 && VT != MVT::v4i32)
13632 if (VT == MVT::ppcf128)
13641 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13642 VT = VT.getScalarType();
13644 if (!VT.isSimple())
13647 switch (VT.getSimpleVT().SimpleTy) {
13659 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
13660 // LR is a callee-save register, but we must treat it as clobbered by any call
13661 // site. Hence we include LR in the scratch registers, which are in turn added
13662 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
13663 // to CTR, which is used by any indirect call.
13664 static const MCPhysReg ScratchRegs[] = {
13665 PPC::X12, PPC::LR8, PPC::CTR8, 0
13668 return ScratchRegs;
13671 unsigned PPCTargetLowering::getExceptionPointerRegister(
13672 const Constant *PersonalityFn) const {
13673 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
13676 unsigned PPCTargetLowering::getExceptionSelectorRegister(
13677 const Constant *PersonalityFn) const {
13678 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
13682 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
13683 EVT VT , unsigned DefinedValues) const {
13684 if (VT == MVT::v2i64)
13685 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
13687 if (Subtarget.hasVSX() || Subtarget.hasQPX())
13690 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
13693 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
13694 if (DisableILPPref || Subtarget.enableMachineScheduler())
13695 return TargetLowering::getSchedulingPreference(N);
13700 // Create a fast isel object.
13702 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
13703 const TargetLibraryInfo *LibInfo) const {
13704 return PPC::createFastISel(FuncInfo, LibInfo);
13707 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13708 if (Subtarget.isDarwinABI()) return;
13709 if (!Subtarget.isPPC64()) return;
13711 // Update IsSplitCSR in PPCFunctionInfo
13712 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
13713 PFI->setIsSplitCSR(true);
13716 void PPCTargetLowering::insertCopiesSplitCSR(
13717 MachineBasicBlock *Entry,
13718 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13719 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13720 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13724 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13725 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13726 MachineBasicBlock::iterator MBBI = Entry->begin();
13727 for (const MCPhysReg *I = IStart; *I; ++I) {
13728 const TargetRegisterClass *RC = nullptr;
13729 if (PPC::G8RCRegClass.contains(*I))
13730 RC = &PPC::G8RCRegClass;
13731 else if (PPC::F8RCRegClass.contains(*I))
13732 RC = &PPC::F8RCRegClass;
13733 else if (PPC::CRRCRegClass.contains(*I))
13734 RC = &PPC::CRRCRegClass;
13735 else if (PPC::VRRCRegClass.contains(*I))
13736 RC = &PPC::VRRCRegClass;
13738 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13740 unsigned NewVR = MRI->createVirtualRegister(RC);
13741 // Create copy from CSR to a virtual register.
13742 // FIXME: this currently does not emit CFI pseudo-instructions, it works
13743 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13744 // nounwind. If we want to generalize this later, we may need to emit
13745 // CFI pseudo-instructions.
13746 assert(Entry->getParent()->getFunction().hasFnAttribute(
13747 Attribute::NoUnwind) &&
13748 "Function should be nounwind in insertCopiesSplitCSR!");
13749 Entry->addLiveIn(*I);
13750 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13753 // Insert the copy-back instructions right before the terminator
13754 for (auto *Exit : Exits)
13755 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13756 TII->get(TargetOpcode::COPY), *I)
13761 // Override to enable LOAD_STACK_GUARD lowering on Linux.
13762 bool PPCTargetLowering::useLoadStackGuardNode() const {
13763 if (!Subtarget.isTargetLinux())
13764 return TargetLowering::useLoadStackGuardNode();
13768 // Override to disable global variable loading on Linux.
13769 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
13770 if (!Subtarget.isTargetLinux())
13771 return TargetLowering::insertSSPDeclarations(M);
13774 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13775 if (!VT.isSimple() || !Subtarget.hasVSX())
13778 switch(VT.getSimpleVT().SimpleTy) {
13780 // For FP types that are currently not supported by PPC backend, return
13781 // false. Examples: f16, f80.
13786 return Imm.isPosZero();
13790 // For vector shift operation op, fold
13791 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
13792 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
13793 SelectionDAG &DAG) {
13794 SDValue N0 = N->getOperand(0);
13795 SDValue N1 = N->getOperand(1);
13796 EVT VT = N0.getValueType();
13797 unsigned OpSizeInBits = VT.getScalarSizeInBits();
13798 unsigned Opcode = N->getOpcode();
13799 unsigned TargetOpcode;
13803 llvm_unreachable("Unexpected shift operation");
13805 TargetOpcode = PPCISD::SHL;
13808 TargetOpcode = PPCISD::SRL;
13811 TargetOpcode = PPCISD::SRA;
13815 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13816 N1->getOpcode() == ISD::AND)
13817 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13818 if (Mask->getZExtValue() == OpSizeInBits - 1)
13819 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13824 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13825 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13831 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13832 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13838 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13839 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13845 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
13846 // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
13847 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
13850 // If not a tail call then no need to proceed.
13851 if (!CI->isTailCall())
13854 // If tail calls are disabled for the caller then we are done.
13855 const Function *Caller = CI->getParent()->getParent();
13856 auto Attr = Caller->getFnAttribute("disable-tail-calls");
13857 if (Attr.getValueAsString() == "true")
13860 // If sibling calls have been disabled and tail-calls aren't guaranteed
13861 // there is no reason to duplicate.
13862 auto &TM = getTargetMachine();
13863 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
13866 // Can't tail call a function called indirectly, or if it has variadic args.
13867 const Function *Callee = CI->getCalledFunction();
13868 if (!Callee || Callee->isVarArg())
13871 // Make sure the callee and caller calling conventions are eligible for tco.
13872 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
13873 CI->getCallingConv()))
13876 // If the function is local then we have a good chance at tail-calling it
13877 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);