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 "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCCCState.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCISelLowering.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/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.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/ValueTypes.h"
55 #include "llvm/IR/CallingConv.h"
56 #include "llvm/IR/CallSite.h"
57 #include "llvm/IR/Constant.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Function.h"
63 #include "llvm/IR/GlobalValue.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Module.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/MC/MCExpr.h"
72 #include "llvm/MC/MCRegisterInfo.h"
73 #include "llvm/Support/AtomicOrdering.h"
74 #include "llvm/Support/BranchProbability.h"
75 #include "llvm/Support/Casting.h"
76 #include "llvm/Support/CodeGen.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/Format.h"
82 #include "llvm/Support/KnownBits.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetInstrInfo.h"
86 #include "llvm/Target/TargetLowering.h"
87 #include "llvm/Target/TargetMachine.h"
88 #include "llvm/Target/TargetOptions.h"
89 #include "llvm/Target/TargetRegisterInfo.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 // FIXME: Remove this once the bug has been fixed!
118 extern cl::opt<bool> ANDIGlueBug;
120 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
121 const PPCSubtarget &STI)
122 : TargetLowering(TM), Subtarget(STI) {
123 // Use _setjmp/_longjmp instead of setjmp/longjmp.
124 setUseUnderscoreSetJmp(true);
125 setUseUnderscoreLongJmp(true);
127 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
128 // arguments are at least 4/8 bytes aligned.
129 bool isPPC64 = Subtarget.isPPC64();
130 setMinStackArgumentAlignment(isPPC64 ? 8:4);
132 // Set up the register classes.
133 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
134 if (!useSoftFloat()) {
135 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
136 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
139 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
140 for (MVT VT : MVT::integer_valuetypes()) {
141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
145 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
147 // PowerPC has pre-inc load and store's.
148 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
149 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
150 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
151 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
152 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
153 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
154 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
155 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
156 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
157 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
158 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
159 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
160 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
161 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
163 if (Subtarget.useCRBits()) {
164 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
166 if (isPPC64 || Subtarget.hasFPCVT()) {
167 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
168 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
169 isPPC64 ? MVT::i64 : MVT::i32);
170 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
171 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
172 isPPC64 ? MVT::i64 : MVT::i32);
174 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
175 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
178 // PowerPC does not support direct load / store of condition registers
179 setOperationAction(ISD::LOAD, MVT::i1, Custom);
180 setOperationAction(ISD::STORE, MVT::i1, Custom);
182 // FIXME: Remove this once the ANDI glue bug is fixed:
184 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
186 for (MVT VT : MVT::integer_valuetypes()) {
187 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
188 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
189 setTruncStoreAction(VT, MVT::i1, Expand);
192 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
195 // This is used in the ppcf128->int sequence. Note it has different semantics
196 // from FP_ROUND: that rounds to nearest, this rounds to zero.
197 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
199 // We do not currently implement these libm ops for PowerPC.
200 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
201 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
202 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
203 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
204 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
205 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
207 // PowerPC has no SREM/UREM instructions
208 setOperationAction(ISD::SREM, MVT::i32, Expand);
209 setOperationAction(ISD::UREM, MVT::i32, Expand);
210 setOperationAction(ISD::SREM, MVT::i64, Expand);
211 setOperationAction(ISD::UREM, MVT::i64, Expand);
213 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
214 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
215 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
216 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
217 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
218 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
219 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
220 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
221 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
223 // We don't support sin/cos/sqrt/fmod/pow
224 setOperationAction(ISD::FSIN , MVT::f64, Expand);
225 setOperationAction(ISD::FCOS , MVT::f64, Expand);
226 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
227 setOperationAction(ISD::FREM , MVT::f64, Expand);
228 setOperationAction(ISD::FPOW , MVT::f64, Expand);
229 setOperationAction(ISD::FMA , MVT::f64, Legal);
230 setOperationAction(ISD::FSIN , MVT::f32, Expand);
231 setOperationAction(ISD::FCOS , MVT::f32, Expand);
232 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
233 setOperationAction(ISD::FREM , MVT::f32, Expand);
234 setOperationAction(ISD::FPOW , MVT::f32, Expand);
235 setOperationAction(ISD::FMA , MVT::f32, Legal);
237 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
239 // If we're enabling GP optimizations, use hardware square root
240 if (!Subtarget.hasFSQRT() &&
241 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
243 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
245 if (!Subtarget.hasFSQRT() &&
246 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
247 Subtarget.hasFRES()))
248 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
250 if (Subtarget.hasFCPSGN()) {
251 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
252 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
254 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
255 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
258 if (Subtarget.hasFPRND()) {
259 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
260 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
261 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
262 setOperationAction(ISD::FROUND, MVT::f64, Legal);
264 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
265 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
266 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
267 setOperationAction(ISD::FROUND, MVT::f32, Legal);
270 // PowerPC does not have BSWAP
271 // CTPOP or CTTZ were introduced in P8/P9 respectivelly
272 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
273 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
274 if (Subtarget.isISA3_0()) {
275 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
276 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
278 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
279 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
282 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
283 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
284 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
286 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
287 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
290 // PowerPC does not have ROTR
291 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
292 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
294 if (!Subtarget.useCRBits()) {
295 // PowerPC does not have Select
296 setOperationAction(ISD::SELECT, MVT::i32, Expand);
297 setOperationAction(ISD::SELECT, MVT::i64, Expand);
298 setOperationAction(ISD::SELECT, MVT::f32, Expand);
299 setOperationAction(ISD::SELECT, MVT::f64, Expand);
302 // PowerPC wants to turn select_cc of FP into fsel when possible.
303 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
304 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
306 // PowerPC wants to optimize integer setcc a bit
307 if (!Subtarget.useCRBits())
308 setOperationAction(ISD::SETCC, MVT::i32, Custom);
310 // PowerPC does not have BRCOND which requires SetCC
311 if (!Subtarget.useCRBits())
312 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
314 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
316 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
317 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
319 // PowerPC does not have [U|S]INT_TO_FP
320 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
321 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
323 if (Subtarget.hasDirectMove() && isPPC64) {
324 setOperationAction(ISD::BITCAST, MVT::f32, Legal);
325 setOperationAction(ISD::BITCAST, MVT::i32, Legal);
326 setOperationAction(ISD::BITCAST, MVT::i64, Legal);
327 setOperationAction(ISD::BITCAST, MVT::f64, Legal);
329 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
330 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
331 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
332 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
335 // We cannot sextinreg(i1). Expand to shifts.
336 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
338 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
339 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
340 // support continuation, user-level threading, and etc.. As a result, no
341 // other SjLj exception interfaces are implemented and please don't build
342 // your own exception handling based on them.
343 // LLVM/Clang supports zero-cost DWARF exception handling.
344 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
345 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
347 // We want to legalize GlobalAddress and ConstantPool nodes into the
348 // appropriate instructions to materialize the address.
349 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
350 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
351 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
352 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
353 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
354 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
355 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
356 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
357 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
358 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
361 setOperationAction(ISD::TRAP, MVT::Other, Legal);
363 // TRAMPOLINE is custom lowered.
364 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
365 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
367 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
368 setOperationAction(ISD::VASTART , MVT::Other, Custom);
370 if (Subtarget.isSVR4ABI()) {
372 // VAARG always uses double-word chunks, so promote anything smaller.
373 setOperationAction(ISD::VAARG, MVT::i1, Promote);
374 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
375 setOperationAction(ISD::VAARG, MVT::i8, Promote);
376 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
377 setOperationAction(ISD::VAARG, MVT::i16, Promote);
378 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
379 setOperationAction(ISD::VAARG, MVT::i32, Promote);
380 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
381 setOperationAction(ISD::VAARG, MVT::Other, Expand);
383 // VAARG is custom lowered with the 32-bit SVR4 ABI.
384 setOperationAction(ISD::VAARG, MVT::Other, Custom);
385 setOperationAction(ISD::VAARG, MVT::i64, Custom);
388 setOperationAction(ISD::VAARG, MVT::Other, Expand);
390 if (Subtarget.isSVR4ABI() && !isPPC64)
391 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
392 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
394 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
396 // Use the default implementation.
397 setOperationAction(ISD::VAEND , MVT::Other, Expand);
398 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
399 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
400 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
401 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
402 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
403 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
404 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
405 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
407 // We want to custom lower some of our intrinsics.
408 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
410 // To handle counter-based loop conditions.
411 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
413 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
414 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
415 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
416 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
418 // Comparisons that require checking two conditions.
419 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
420 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
421 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
422 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
423 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
424 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
425 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
426 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
427 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
428 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
429 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
430 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
432 if (Subtarget.has64BitSupport()) {
433 // They also have instructions for converting between i64 and fp.
434 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
435 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
436 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
437 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
438 // This is just the low 32 bits of a (signed) fp->i64 conversion.
439 // We cannot do this with Promote because i64 is not a legal type.
440 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
442 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
443 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
445 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
446 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
449 // With the instructions enabled under FPCVT, we can do everything.
450 if (Subtarget.hasFPCVT()) {
451 if (Subtarget.has64BitSupport()) {
452 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
453 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
454 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
455 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
458 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
459 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
460 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
461 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
464 if (Subtarget.use64BitRegs()) {
465 // 64-bit PowerPC implementations can support i64 types directly
466 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
467 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
468 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
469 // 64-bit PowerPC wants to expand i128 shifts itself.
470 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
471 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
472 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
474 // 32-bit PowerPC wants to expand i64 shifts itself.
475 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
476 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
477 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
480 if (Subtarget.hasAltivec()) {
481 // First set operation action for all vector types to expand. Then we
482 // will selectively turn on ones that can be effectively codegen'd.
483 for (MVT VT : MVT::vector_valuetypes()) {
484 // add/sub are legal for all supported vector VT's.
485 setOperationAction(ISD::ADD, VT, Legal);
486 setOperationAction(ISD::SUB, VT, Legal);
488 // Vector instructions introduced in P8
489 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
490 setOperationAction(ISD::CTPOP, VT, Legal);
491 setOperationAction(ISD::CTLZ, VT, Legal);
494 setOperationAction(ISD::CTPOP, VT, Expand);
495 setOperationAction(ISD::CTLZ, VT, Expand);
498 // Vector instructions introduced in P9
499 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
500 setOperationAction(ISD::CTTZ, VT, Legal);
502 setOperationAction(ISD::CTTZ, VT, Expand);
504 // We promote all shuffles to v16i8.
505 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
506 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
508 // We promote all non-typed operations to v4i32.
509 setOperationAction(ISD::AND , VT, Promote);
510 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
511 setOperationAction(ISD::OR , VT, Promote);
512 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
513 setOperationAction(ISD::XOR , VT, Promote);
514 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
515 setOperationAction(ISD::LOAD , VT, Promote);
516 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
517 setOperationAction(ISD::SELECT, VT, Promote);
518 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
519 setOperationAction(ISD::SELECT_CC, VT, Promote);
520 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
521 setOperationAction(ISD::STORE, VT, Promote);
522 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
524 // No other operations are legal.
525 setOperationAction(ISD::MUL , VT, Expand);
526 setOperationAction(ISD::SDIV, VT, Expand);
527 setOperationAction(ISD::SREM, VT, Expand);
528 setOperationAction(ISD::UDIV, VT, Expand);
529 setOperationAction(ISD::UREM, VT, Expand);
530 setOperationAction(ISD::FDIV, VT, Expand);
531 setOperationAction(ISD::FREM, VT, Expand);
532 setOperationAction(ISD::FNEG, VT, Expand);
533 setOperationAction(ISD::FSQRT, VT, Expand);
534 setOperationAction(ISD::FLOG, VT, Expand);
535 setOperationAction(ISD::FLOG10, VT, Expand);
536 setOperationAction(ISD::FLOG2, VT, Expand);
537 setOperationAction(ISD::FEXP, VT, Expand);
538 setOperationAction(ISD::FEXP2, VT, Expand);
539 setOperationAction(ISD::FSIN, VT, Expand);
540 setOperationAction(ISD::FCOS, VT, Expand);
541 setOperationAction(ISD::FABS, VT, Expand);
542 setOperationAction(ISD::FFLOOR, VT, Expand);
543 setOperationAction(ISD::FCEIL, VT, Expand);
544 setOperationAction(ISD::FTRUNC, VT, Expand);
545 setOperationAction(ISD::FRINT, VT, Expand);
546 setOperationAction(ISD::FNEARBYINT, VT, Expand);
547 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
548 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
549 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
550 setOperationAction(ISD::MULHU, VT, Expand);
551 setOperationAction(ISD::MULHS, VT, Expand);
552 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
553 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
554 setOperationAction(ISD::UDIVREM, VT, Expand);
555 setOperationAction(ISD::SDIVREM, VT, Expand);
556 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
557 setOperationAction(ISD::FPOW, VT, Expand);
558 setOperationAction(ISD::BSWAP, VT, Expand);
559 setOperationAction(ISD::VSELECT, VT, Expand);
560 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
561 setOperationAction(ISD::ROTL, VT, Expand);
562 setOperationAction(ISD::ROTR, VT, Expand);
564 for (MVT InnerVT : MVT::vector_valuetypes()) {
565 setTruncStoreAction(VT, InnerVT, Expand);
566 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
567 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
568 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
572 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
573 // with merges, splats, etc.
574 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
576 setOperationAction(ISD::AND , MVT::v4i32, Legal);
577 setOperationAction(ISD::OR , MVT::v4i32, Legal);
578 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
579 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
580 setOperationAction(ISD::SELECT, MVT::v4i32,
581 Subtarget.useCRBits() ? Legal : Expand);
582 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
583 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
584 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
585 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
586 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
587 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
588 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
589 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
590 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
592 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
593 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
594 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
595 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
597 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
598 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
600 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
601 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
602 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
605 if (Subtarget.hasP8Altivec())
606 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
608 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
610 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
611 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
613 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
614 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
616 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
617 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
619 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
621 // Altivec does not contain unordered floating-point compare instructions
622 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
623 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
624 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
625 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
627 if (Subtarget.hasVSX()) {
628 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
629 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
630 if (Subtarget.hasP8Vector()) {
631 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
632 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
634 if (Subtarget.hasDirectMove() && isPPC64) {
635 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
636 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
637 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
638 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
639 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
640 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
641 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
642 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
644 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
646 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
647 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
648 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
649 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
650 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
652 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
654 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
655 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
657 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
658 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
660 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
661 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
662 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
663 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
664 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
666 // Share the Altivec comparison restrictions.
667 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
668 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
669 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
670 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
672 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
673 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
675 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
677 if (Subtarget.hasP8Vector())
678 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
680 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
682 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
683 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
684 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
686 if (Subtarget.hasP8Altivec()) {
687 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
688 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
689 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
691 // 128 bit shifts can be accomplished via 3 instructions for SHL and
692 // SRL, but not for SRA because of the instructions available:
693 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
695 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
696 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
697 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
699 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
702 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
703 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
704 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
706 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
708 // VSX v2i64 only supports non-arithmetic operations.
709 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
710 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
713 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
714 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
715 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
716 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
718 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
720 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
721 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
722 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
723 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
725 // Vector operation legalization checks the result type of
726 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
727 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
728 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
729 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
730 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
732 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
733 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
734 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
735 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
737 if (Subtarget.hasDirectMove())
738 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
739 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
741 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
744 if (Subtarget.hasP8Altivec()) {
745 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
746 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
749 if (Subtarget.hasP9Vector()) {
750 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
751 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
753 // 128 bit shifts can be accomplished via 3 instructions for SHL and
754 // SRL, but not for SRA because of the instructions available:
755 // VS{RL} and VS{RL}O.
756 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
757 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
758 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
762 if (Subtarget.hasQPX()) {
763 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
764 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
765 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
766 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
768 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
769 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
771 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
772 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
774 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
775 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
777 if (!Subtarget.useCRBits())
778 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
779 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
781 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
782 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
783 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
784 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
785 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
786 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
787 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
789 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
790 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
792 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
793 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
794 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
796 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
797 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
798 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
799 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
800 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
801 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
802 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
803 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
804 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
805 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
807 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
808 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
810 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
811 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
813 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
815 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
816 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
817 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
818 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
820 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
821 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
823 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
824 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
826 if (!Subtarget.useCRBits())
827 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
828 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
830 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
831 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
832 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
833 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
834 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
835 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
836 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
838 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
839 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
841 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
842 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
843 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
844 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
845 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
846 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
847 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
848 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
849 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
850 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
852 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
853 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
855 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
856 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
858 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
860 setOperationAction(ISD::AND , MVT::v4i1, Legal);
861 setOperationAction(ISD::OR , MVT::v4i1, Legal);
862 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
864 if (!Subtarget.useCRBits())
865 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
866 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
868 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
869 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
871 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
872 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
873 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
874 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
875 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
876 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
877 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
879 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
880 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
882 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
884 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
885 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
886 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
887 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
889 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
890 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
891 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
892 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
894 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
895 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
897 // These need to set FE_INEXACT, and so cannot be vectorized here.
898 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
899 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
901 if (TM.Options.UnsafeFPMath) {
902 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
903 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
905 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
906 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
908 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
909 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
911 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
912 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
916 if (Subtarget.has64BitSupport())
917 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
919 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
922 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
923 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
926 setBooleanContents(ZeroOrOneBooleanContent);
928 if (Subtarget.hasAltivec()) {
929 // Altivec instructions set fields to all zeros or all ones.
930 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
934 // These libcalls are not available in 32-bit.
935 setLibcallName(RTLIB::SHL_I128, nullptr);
936 setLibcallName(RTLIB::SRL_I128, nullptr);
937 setLibcallName(RTLIB::SRA_I128, nullptr);
940 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
942 // We have target-specific dag combine patterns for the following nodes:
943 setTargetDAGCombine(ISD::SHL);
944 setTargetDAGCombine(ISD::SRA);
945 setTargetDAGCombine(ISD::SRL);
946 setTargetDAGCombine(ISD::SINT_TO_FP);
947 setTargetDAGCombine(ISD::BUILD_VECTOR);
948 if (Subtarget.hasFPCVT())
949 setTargetDAGCombine(ISD::UINT_TO_FP);
950 setTargetDAGCombine(ISD::LOAD);
951 setTargetDAGCombine(ISD::STORE);
952 setTargetDAGCombine(ISD::BR_CC);
953 if (Subtarget.useCRBits())
954 setTargetDAGCombine(ISD::BRCOND);
955 setTargetDAGCombine(ISD::BSWAP);
956 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
957 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
958 setTargetDAGCombine(ISD::INTRINSIC_VOID);
960 setTargetDAGCombine(ISD::SIGN_EXTEND);
961 setTargetDAGCombine(ISD::ZERO_EXTEND);
962 setTargetDAGCombine(ISD::ANY_EXTEND);
964 if (Subtarget.useCRBits()) {
965 setTargetDAGCombine(ISD::TRUNCATE);
966 setTargetDAGCombine(ISD::SETCC);
967 setTargetDAGCombine(ISD::SELECT_CC);
970 // Use reciprocal estimates.
971 if (TM.Options.UnsafeFPMath) {
972 setTargetDAGCombine(ISD::FDIV);
973 setTargetDAGCombine(ISD::FSQRT);
976 // Darwin long double math library functions have $LDBL128 appended.
977 if (Subtarget.isDarwin()) {
978 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
979 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
980 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
981 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
982 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
983 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
984 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
985 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
986 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
987 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
990 // With 32 condition bits, we don't need to sink (and duplicate) compares
991 // aggressively in CodeGenPrep.
992 if (Subtarget.useCRBits()) {
993 setHasMultipleConditionRegisters();
994 setJumpIsExpensive();
997 setMinFunctionAlignment(2);
998 if (Subtarget.isDarwin())
999 setPrefFunctionAlignment(4);
1001 switch (Subtarget.getDarwinDirective()) {
1005 case PPC::DIR_E500mc:
1006 case PPC::DIR_E5500:
1009 case PPC::DIR_PWR5X:
1011 case PPC::DIR_PWR6X:
1015 setPrefFunctionAlignment(4);
1016 setPrefLoopAlignment(4);
1020 if (Subtarget.enableMachineScheduler())
1021 setSchedulingPreference(Sched::Source);
1023 setSchedulingPreference(Sched::Hybrid);
1025 computeRegisterProperties(STI.getRegisterInfo());
1027 // The Freescale cores do better with aggressive inlining of memcpy and
1028 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1029 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1030 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1031 MaxStoresPerMemset = 32;
1032 MaxStoresPerMemsetOptSize = 16;
1033 MaxStoresPerMemcpy = 32;
1034 MaxStoresPerMemcpyOptSize = 8;
1035 MaxStoresPerMemmove = 32;
1036 MaxStoresPerMemmoveOptSize = 8;
1037 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1038 // The A2 also benefits from (very) aggressive inlining of memcpy and
1039 // friends. The overhead of a the function call, even when warm, can be
1040 // over one hundred cycles.
1041 MaxStoresPerMemset = 128;
1042 MaxStoresPerMemcpy = 128;
1043 MaxStoresPerMemmove = 128;
1047 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1048 /// the desired ByVal argument alignment.
1049 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1050 unsigned MaxMaxAlign) {
1051 if (MaxAlign == MaxMaxAlign)
1053 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1054 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1056 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1058 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1059 unsigned EltAlign = 0;
1060 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1061 if (EltAlign > MaxAlign)
1062 MaxAlign = EltAlign;
1063 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1064 for (auto *EltTy : STy->elements()) {
1065 unsigned EltAlign = 0;
1066 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1067 if (EltAlign > MaxAlign)
1068 MaxAlign = EltAlign;
1069 if (MaxAlign == MaxMaxAlign)
1075 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1076 /// function arguments in the caller parameter area.
1077 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1078 const DataLayout &DL) const {
1079 // Darwin passes everything on 4 byte boundary.
1080 if (Subtarget.isDarwin())
1083 // 16byte and wider vectors are passed on 16byte boundary.
1084 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1085 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1086 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1087 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1091 bool PPCTargetLowering::useSoftFloat() const {
1092 return Subtarget.useSoftFloat();
1095 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1096 switch ((PPCISD::NodeType)Opcode) {
1097 case PPCISD::FIRST_NUMBER: break;
1098 case PPCISD::FSEL: return "PPCISD::FSEL";
1099 case PPCISD::FCFID: return "PPCISD::FCFID";
1100 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1101 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1102 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1103 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1104 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1105 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1106 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1107 case PPCISD::FRE: return "PPCISD::FRE";
1108 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1109 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1110 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
1111 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
1112 case PPCISD::VPERM: return "PPCISD::VPERM";
1113 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1114 case PPCISD::XXINSERT: return "PPCISD::XXINSERT";
1115 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1116 case PPCISD::CMPB: return "PPCISD::CMPB";
1117 case PPCISD::Hi: return "PPCISD::Hi";
1118 case PPCISD::Lo: return "PPCISD::Lo";
1119 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1120 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1121 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1122 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1123 case PPCISD::SRL: return "PPCISD::SRL";
1124 case PPCISD::SRA: return "PPCISD::SRA";
1125 case PPCISD::SHL: return "PPCISD::SHL";
1126 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1127 case PPCISD::CALL: return "PPCISD::CALL";
1128 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1129 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1130 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1131 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1132 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1133 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1134 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1135 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1136 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1137 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1138 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1139 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1140 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1141 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1142 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1143 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1144 case PPCISD::VCMP: return "PPCISD::VCMP";
1145 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1146 case PPCISD::LBRX: return "PPCISD::LBRX";
1147 case PPCISD::STBRX: return "PPCISD::STBRX";
1148 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1149 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1150 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1151 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1152 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1153 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1154 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1155 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1156 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1157 case PPCISD::BDZ: return "PPCISD::BDZ";
1158 case PPCISD::MFFS: return "PPCISD::MFFS";
1159 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1160 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1161 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1162 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1163 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1164 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1165 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1166 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1167 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1168 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1169 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1170 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1171 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1172 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1173 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1174 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1175 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1176 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1177 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1178 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1179 case PPCISD::SC: return "PPCISD::SC";
1180 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1181 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1182 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1183 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1184 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1185 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1186 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1187 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1188 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1189 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1190 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1195 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1198 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1200 if (Subtarget.hasQPX())
1201 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1203 return VT.changeVectorElementTypeToInteger();
1206 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1207 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1211 //===----------------------------------------------------------------------===//
1212 // Node matching predicates, for use by the tblgen matching code.
1213 //===----------------------------------------------------------------------===//
1215 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1216 static bool isFloatingPointZero(SDValue Op) {
1217 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1218 return CFP->getValueAPF().isZero();
1219 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1220 // Maybe this has already been legalized into the constant pool?
1221 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1222 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1223 return CFP->getValueAPF().isZero();
1228 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1229 /// true if Op is undef or if it matches the specified value.
1230 static bool isConstantOrUndef(int Op, int Val) {
1231 return Op < 0 || Op == Val;
1234 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1235 /// VPKUHUM instruction.
1236 /// The ShuffleKind distinguishes between big-endian operations with
1237 /// two different inputs (0), either-endian operations with two identical
1238 /// inputs (1), and little-endian operations with two different inputs (2).
1239 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1240 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1241 SelectionDAG &DAG) {
1242 bool IsLE = DAG.getDataLayout().isLittleEndian();
1243 if (ShuffleKind == 0) {
1246 for (unsigned i = 0; i != 16; ++i)
1247 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1249 } else if (ShuffleKind == 2) {
1252 for (unsigned i = 0; i != 16; ++i)
1253 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1255 } else if (ShuffleKind == 1) {
1256 unsigned j = IsLE ? 0 : 1;
1257 for (unsigned i = 0; i != 8; ++i)
1258 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1259 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1265 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1266 /// VPKUWUM instruction.
1267 /// The ShuffleKind distinguishes between big-endian operations with
1268 /// two different inputs (0), either-endian operations with two identical
1269 /// inputs (1), and little-endian operations with two different inputs (2).
1270 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1271 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1272 SelectionDAG &DAG) {
1273 bool IsLE = DAG.getDataLayout().isLittleEndian();
1274 if (ShuffleKind == 0) {
1277 for (unsigned i = 0; i != 16; i += 2)
1278 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1279 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1281 } else if (ShuffleKind == 2) {
1284 for (unsigned i = 0; i != 16; i += 2)
1285 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1286 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1288 } else if (ShuffleKind == 1) {
1289 unsigned j = IsLE ? 0 : 2;
1290 for (unsigned i = 0; i != 8; i += 2)
1291 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1292 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1293 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1294 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1300 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1301 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1302 /// current subtarget.
1304 /// The ShuffleKind distinguishes between big-endian operations with
1305 /// two different inputs (0), either-endian operations with two identical
1306 /// inputs (1), and little-endian operations with two different inputs (2).
1307 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1308 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1309 SelectionDAG &DAG) {
1310 const PPCSubtarget& Subtarget =
1311 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1312 if (!Subtarget.hasP8Vector())
1315 bool IsLE = DAG.getDataLayout().isLittleEndian();
1316 if (ShuffleKind == 0) {
1319 for (unsigned i = 0; i != 16; i += 4)
1320 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1321 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1322 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1323 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1325 } else if (ShuffleKind == 2) {
1328 for (unsigned i = 0; i != 16; i += 4)
1329 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1330 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1331 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1332 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1334 } else if (ShuffleKind == 1) {
1335 unsigned j = IsLE ? 0 : 4;
1336 for (unsigned i = 0; i != 8; i += 4)
1337 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1338 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1339 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1340 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1341 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1342 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1343 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1344 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1350 /// isVMerge - Common function, used to match vmrg* shuffles.
1352 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1353 unsigned LHSStart, unsigned RHSStart) {
1354 if (N->getValueType(0) != MVT::v16i8)
1356 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1357 "Unsupported merge size!");
1359 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1360 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1361 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1362 LHSStart+j+i*UnitSize) ||
1363 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1364 RHSStart+j+i*UnitSize))
1370 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1371 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1372 /// The ShuffleKind distinguishes between big-endian merges with two
1373 /// different inputs (0), either-endian merges with two identical inputs (1),
1374 /// and little-endian merges with two different inputs (2). For the latter,
1375 /// the input operands are swapped (see PPCInstrAltivec.td).
1376 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1377 unsigned ShuffleKind, SelectionDAG &DAG) {
1378 if (DAG.getDataLayout().isLittleEndian()) {
1379 if (ShuffleKind == 1) // unary
1380 return isVMerge(N, UnitSize, 0, 0);
1381 else if (ShuffleKind == 2) // swapped
1382 return isVMerge(N, UnitSize, 0, 16);
1386 if (ShuffleKind == 1) // unary
1387 return isVMerge(N, UnitSize, 8, 8);
1388 else if (ShuffleKind == 0) // normal
1389 return isVMerge(N, UnitSize, 8, 24);
1395 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1396 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1397 /// The ShuffleKind distinguishes between big-endian merges with two
1398 /// different inputs (0), either-endian merges with two identical inputs (1),
1399 /// and little-endian merges with two different inputs (2). For the latter,
1400 /// the input operands are swapped (see PPCInstrAltivec.td).
1401 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1402 unsigned ShuffleKind, SelectionDAG &DAG) {
1403 if (DAG.getDataLayout().isLittleEndian()) {
1404 if (ShuffleKind == 1) // unary
1405 return isVMerge(N, UnitSize, 8, 8);
1406 else if (ShuffleKind == 2) // swapped
1407 return isVMerge(N, UnitSize, 8, 24);
1411 if (ShuffleKind == 1) // unary
1412 return isVMerge(N, UnitSize, 0, 0);
1413 else if (ShuffleKind == 0) // normal
1414 return isVMerge(N, UnitSize, 0, 16);
1421 * \brief Common function used to match vmrgew and vmrgow shuffles
1423 * The indexOffset determines whether to look for even or odd words in
1424 * the shuffle mask. This is based on the of the endianness of the target
1427 * - Use offset of 0 to check for odd elements
1428 * - Use offset of 4 to check for even elements
1430 * - Use offset of 0 to check for even elements
1431 * - Use offset of 4 to check for odd elements
1432 * A detailed description of the vector element ordering for little endian and
1433 * big endian can be found at
1434 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1435 * Targeting your applications - what little endian and big endian IBM XL C/C++
1436 * compiler differences mean to you
1438 * The mask to the shuffle vector instruction specifies the indices of the
1439 * elements from the two input vectors to place in the result. The elements are
1440 * numbered in array-access order, starting with the first vector. These vectors
1441 * are always of type v16i8, thus each vector will contain 16 elements of size
1442 * 8. More info on the shuffle vector can be found in the
1443 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1444 * Language Reference.
1446 * The RHSStartValue indicates whether the same input vectors are used (unary)
1447 * or two different input vectors are used, based on the following:
1448 * - If the instruction uses the same vector for both inputs, the range of the
1449 * indices will be 0 to 15. In this case, the RHSStart value passed should
1451 * - If the instruction has two different vectors then the range of the
1452 * indices will be 0 to 31. In this case, the RHSStart value passed should
1453 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1454 * to 31 specify elements in the second vector).
1456 * \param[in] N The shuffle vector SD Node to analyze
1457 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1458 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1459 * vector to the shuffle_vector instruction
1460 * \return true iff this shuffle vector represents an even or odd word merge
1462 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1463 unsigned RHSStartValue) {
1464 if (N->getValueType(0) != MVT::v16i8)
1467 for (unsigned i = 0; i < 2; ++i)
1468 for (unsigned j = 0; j < 4; ++j)
1469 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1470 i*RHSStartValue+j+IndexOffset) ||
1471 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1472 i*RHSStartValue+j+IndexOffset+8))
1478 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1479 * vmrgow instructions.
1481 * \param[in] N The shuffle vector SD Node to analyze
1482 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1483 * \param[in] ShuffleKind Identify the type of merge:
1484 * - 0 = big-endian merge with two different inputs;
1485 * - 1 = either-endian merge with two identical inputs;
1486 * - 2 = little-endian merge with two different inputs (inputs are swapped for
1487 * little-endian merges).
1488 * \param[in] DAG The current SelectionDAG
1489 * \return true iff this shuffle mask
1491 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1492 unsigned ShuffleKind, SelectionDAG &DAG) {
1493 if (DAG.getDataLayout().isLittleEndian()) {
1494 unsigned indexOffset = CheckEven ? 4 : 0;
1495 if (ShuffleKind == 1) // Unary
1496 return isVMerge(N, indexOffset, 0);
1497 else if (ShuffleKind == 2) // swapped
1498 return isVMerge(N, indexOffset, 16);
1503 unsigned indexOffset = CheckEven ? 0 : 4;
1504 if (ShuffleKind == 1) // Unary
1505 return isVMerge(N, indexOffset, 0);
1506 else if (ShuffleKind == 0) // Normal
1507 return isVMerge(N, indexOffset, 16);
1514 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1515 /// amount, otherwise return -1.
1516 /// The ShuffleKind distinguishes between big-endian operations with two
1517 /// different inputs (0), either-endian operations with two identical inputs
1518 /// (1), and little-endian operations with two different inputs (2). For the
1519 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1520 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1521 SelectionDAG &DAG) {
1522 if (N->getValueType(0) != MVT::v16i8)
1525 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1527 // Find the first non-undef value in the shuffle mask.
1529 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1532 if (i == 16) return -1; // all undef.
1534 // Otherwise, check to see if the rest of the elements are consecutively
1535 // numbered from this value.
1536 unsigned ShiftAmt = SVOp->getMaskElt(i);
1537 if (ShiftAmt < i) return -1;
1540 bool isLE = DAG.getDataLayout().isLittleEndian();
1542 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1543 // Check the rest of the elements to see if they are consecutive.
1544 for (++i; i != 16; ++i)
1545 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1547 } else if (ShuffleKind == 1) {
1548 // Check the rest of the elements to see if they are consecutive.
1549 for (++i; i != 16; ++i)
1550 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1556 ShiftAmt = 16 - ShiftAmt;
1561 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1562 /// specifies a splat of a single element that is suitable for input to
1563 /// VSPLTB/VSPLTH/VSPLTW.
1564 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1565 assert(N->getValueType(0) == MVT::v16i8 &&
1566 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1568 // The consecutive indices need to specify an element, not part of two
1569 // different elements. So abandon ship early if this isn't the case.
1570 if (N->getMaskElt(0) % EltSize != 0)
1573 // This is a splat operation if each element of the permute is the same, and
1574 // if the value doesn't reference the second vector.
1575 unsigned ElementBase = N->getMaskElt(0);
1577 // FIXME: Handle UNDEF elements too!
1578 if (ElementBase >= 16)
1581 // Check that the indices are consecutive, in the case of a multi-byte element
1582 // splatted with a v16i8 mask.
1583 for (unsigned i = 1; i != EltSize; ++i)
1584 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1587 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1588 if (N->getMaskElt(i) < 0) continue;
1589 for (unsigned j = 0; j != EltSize; ++j)
1590 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1596 // Check that the mask is shuffling words
1597 static bool isWordShuffleMask(ShuffleVectorSDNode *N) {
1598 for (unsigned i = 0; i < 4; ++i) {
1599 unsigned B0 = N->getMaskElt(i*4);
1600 unsigned B1 = N->getMaskElt(i*4+1);
1601 unsigned B2 = N->getMaskElt(i*4+2);
1602 unsigned B3 = N->getMaskElt(i*4+3);
1605 if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1612 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1613 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1614 if (!isWordShuffleMask(N))
1617 // Now we look at mask elements 0,4,8,12
1618 unsigned M0 = N->getMaskElt(0) / 4;
1619 unsigned M1 = N->getMaskElt(4) / 4;
1620 unsigned M2 = N->getMaskElt(8) / 4;
1621 unsigned M3 = N->getMaskElt(12) / 4;
1622 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1623 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1625 // Below, let H and L be arbitrary elements of the shuffle mask
1626 // where H is in the range [4,7] and L is in the range [0,3].
1627 // H, 1, 2, 3 or L, 5, 6, 7
1628 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1629 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1630 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1631 InsertAtByte = IsLE ? 12 : 0;
1635 // 0, H, 2, 3 or 4, L, 6, 7
1636 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1637 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1638 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1639 InsertAtByte = IsLE ? 8 : 4;
1643 // 0, 1, H, 3 or 4, 5, L, 7
1644 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1645 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1646 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1647 InsertAtByte = IsLE ? 4 : 8;
1651 // 0, 1, 2, H or 4, 5, 6, L
1652 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1653 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1654 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1655 InsertAtByte = IsLE ? 0 : 12;
1660 // If both vector operands for the shuffle are the same vector, the mask will
1661 // contain only elements from the first one and the second one will be undef.
1662 if (N->getOperand(1).isUndef()) {
1665 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1666 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1667 InsertAtByte = IsLE ? 12 : 0;
1670 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1671 InsertAtByte = IsLE ? 8 : 4;
1674 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1675 InsertAtByte = IsLE ? 4 : 8;
1678 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1679 InsertAtByte = IsLE ? 0 : 12;
1687 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1688 bool &Swap, bool IsLE) {
1689 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1690 // Ensure each byte index of the word is consecutive.
1691 if (!isWordShuffleMask(N))
1694 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1695 unsigned M0 = N->getMaskElt(0) / 4;
1696 unsigned M1 = N->getMaskElt(4) / 4;
1697 unsigned M2 = N->getMaskElt(8) / 4;
1698 unsigned M3 = N->getMaskElt(12) / 4;
1700 // If both vector operands for the shuffle are the same vector, the mask will
1701 // contain only elements from the first one and the second one will be undef.
1702 if (N->getOperand(1).isUndef()) {
1703 assert(M0 < 4 && "Indexing into an undef vector?");
1704 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1707 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1712 // Ensure each word index of the ShuffleVector Mask is consecutive.
1713 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1717 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1718 // Input vectors don't need to be swapped if the leading element
1719 // of the result is one of the 3 left elements of the second vector
1720 // (or if there is no shift to be done at all).
1722 ShiftElts = (8 - M0) % 8;
1723 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1724 // Input vectors need to be swapped if the leading element
1725 // of the result is one of the 3 left elements of the first vector
1726 // (or if we're shifting by 4 - thereby simply swapping the vectors).
1728 ShiftElts = (4 - M0) % 4;
1733 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1734 // Input vectors don't need to be swapped if the leading element
1735 // of the result is one of the 4 elements of the first vector.
1738 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1739 // Input vectors need to be swapped if the leading element
1740 // of the result is one of the 4 elements of the right vector.
1750 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1751 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1752 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1753 SelectionDAG &DAG) {
1754 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1755 assert(isSplatShuffleMask(SVOp, EltSize));
1756 if (DAG.getDataLayout().isLittleEndian())
1757 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1759 return SVOp->getMaskElt(0) / EltSize;
1762 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1763 /// by using a vspltis[bhw] instruction of the specified element size, return
1764 /// the constant being splatted. The ByteSize field indicates the number of
1765 /// bytes of each element [124] -> [bhw].
1766 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1767 SDValue OpVal(nullptr, 0);
1769 // If ByteSize of the splat is bigger than the element size of the
1770 // build_vector, then we have a case where we are checking for a splat where
1771 // multiple elements of the buildvector are folded together into a single
1772 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1773 unsigned EltSize = 16/N->getNumOperands();
1774 if (EltSize < ByteSize) {
1775 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1776 SDValue UniquedVals[4];
1777 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1779 // See if all of the elements in the buildvector agree across.
1780 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1781 if (N->getOperand(i).isUndef()) continue;
1782 // If the element isn't a constant, bail fully out.
1783 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1785 if (!UniquedVals[i&(Multiple-1)].getNode())
1786 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1787 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1788 return SDValue(); // no match.
1791 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1792 // either constant or undef values that are identical for each chunk. See
1793 // if these chunks can form into a larger vspltis*.
1795 // Check to see if all of the leading entries are either 0 or -1. If
1796 // neither, then this won't fit into the immediate field.
1797 bool LeadingZero = true;
1798 bool LeadingOnes = true;
1799 for (unsigned i = 0; i != Multiple-1; ++i) {
1800 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1802 LeadingZero &= isNullConstant(UniquedVals[i]);
1803 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1805 // Finally, check the least significant entry.
1807 if (!UniquedVals[Multiple-1].getNode())
1808 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
1809 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1810 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
1811 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1814 if (!UniquedVals[Multiple-1].getNode())
1815 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1816 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1817 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1818 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1824 // Check to see if this buildvec has a single non-undef value in its elements.
1825 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1826 if (N->getOperand(i).isUndef()) continue;
1827 if (!OpVal.getNode())
1828 OpVal = N->getOperand(i);
1829 else if (OpVal != N->getOperand(i))
1833 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1835 unsigned ValSizeInBytes = EltSize;
1837 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1838 Value = CN->getZExtValue();
1839 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1840 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1841 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1844 // If the splat value is larger than the element value, then we can never do
1845 // this splat. The only case that we could fit the replicated bits into our
1846 // immediate field for would be zero, and we prefer to use vxor for it.
1847 if (ValSizeInBytes < ByteSize) return SDValue();
1849 // If the element value is larger than the splat value, check if it consists
1850 // of a repeated bit pattern of size ByteSize.
1851 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1854 // Properly sign extend the value.
1855 int MaskVal = SignExtend32(Value, ByteSize * 8);
1857 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1858 if (MaskVal == 0) return SDValue();
1860 // Finally, if this value fits in a 5 bit sext field, return it
1861 if (SignExtend32<5>(MaskVal) == MaskVal)
1862 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1866 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1867 /// amount, otherwise return -1.
1868 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1869 EVT VT = N->getValueType(0);
1870 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1873 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1875 // Find the first non-undef value in the shuffle mask.
1877 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1880 if (i == 4) return -1; // all undef.
1882 // Otherwise, check to see if the rest of the elements are consecutively
1883 // numbered from this value.
1884 unsigned ShiftAmt = SVOp->getMaskElt(i);
1885 if (ShiftAmt < i) return -1;
1888 // Check the rest of the elements to see if they are consecutive.
1889 for (++i; i != 4; ++i)
1890 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1896 //===----------------------------------------------------------------------===//
1897 // Addressing Mode Selection
1898 //===----------------------------------------------------------------------===//
1900 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1901 /// or 64-bit immediate, and if the value can be accurately represented as a
1902 /// sign extension from a 16-bit value. If so, this returns true and the
1904 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1905 if (!isa<ConstantSDNode>(N))
1908 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1909 if (N->getValueType(0) == MVT::i32)
1910 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1912 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1914 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1915 return isIntS16Immediate(Op.getNode(), Imm);
1918 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1919 /// can be represented as an indexed [r+r] operation. Returns false if it
1920 /// can be more efficiently represented with [r+imm].
1921 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1923 SelectionDAG &DAG) const {
1925 if (N.getOpcode() == ISD::ADD) {
1926 if (isIntS16Immediate(N.getOperand(1), imm))
1927 return false; // r+i
1928 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1929 return false; // r+i
1931 Base = N.getOperand(0);
1932 Index = N.getOperand(1);
1934 } else if (N.getOpcode() == ISD::OR) {
1935 if (isIntS16Immediate(N.getOperand(1), imm))
1936 return false; // r+i can fold it if we can.
1938 // If this is an or of disjoint bitfields, we can codegen this as an add
1939 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1941 KnownBits LHSKnown, RHSKnown;
1942 DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1944 if (LHSKnown.Zero.getBoolValue()) {
1945 DAG.computeKnownBits(N.getOperand(1), RHSKnown);
1946 // If all of the bits are known zero on the LHS or RHS, the add won't
1948 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
1949 Base = N.getOperand(0);
1950 Index = N.getOperand(1);
1959 // If we happen to be doing an i64 load or store into a stack slot that has
1960 // less than a 4-byte alignment, then the frame-index elimination may need to
1961 // use an indexed load or store instruction (because the offset may not be a
1962 // multiple of 4). The extra register needed to hold the offset comes from the
1963 // register scavenger, and it is possible that the scavenger will need to use
1964 // an emergency spill slot. As a result, we need to make sure that a spill slot
1965 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1967 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1968 // FIXME: This does not handle the LWA case.
1972 // NOTE: We'll exclude negative FIs here, which come from argument
1973 // lowering, because there are no known test cases triggering this problem
1974 // using packed structures (or similar). We can remove this exclusion if
1975 // we find such a test case. The reason why this is so test-case driven is
1976 // because this entire 'fixup' is only to prevent crashes (from the
1977 // register scavenger) on not-really-valid inputs. For example, if we have:
1979 // %b = bitcast i1* %a to i64*
1980 // store i64* a, i64 b
1981 // then the store should really be marked as 'align 1', but is not. If it
1982 // were marked as 'align 1' then the indexed form would have been
1983 // instruction-selected initially, and the problem this 'fixup' is preventing
1984 // won't happen regardless.
1988 MachineFunction &MF = DAG.getMachineFunction();
1989 MachineFrameInfo &MFI = MF.getFrameInfo();
1991 unsigned Align = MFI.getObjectAlignment(FrameIdx);
1995 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1996 FuncInfo->setHasNonRISpills();
1999 /// Returns true if the address N can be represented by a base register plus
2000 /// a signed 16-bit displacement [r+imm], and if it is not better
2001 /// represented as reg+reg. If Aligned is true, only accept displacements
2002 /// suitable for STD and friends, i.e. multiples of 4.
2003 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2006 bool Aligned) const {
2007 // FIXME dl should come from parent load or store, not from address
2009 // If this can be more profitably realized as r+r, fail.
2010 if (SelectAddressRegReg(N, Disp, Base, DAG))
2013 if (N.getOpcode() == ISD::ADD) {
2015 if (isIntS16Immediate(N.getOperand(1), imm) &&
2016 (!Aligned || (imm & 3) == 0)) {
2017 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2018 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2019 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2020 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2022 Base = N.getOperand(0);
2024 return true; // [r+i]
2025 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2026 // Match LOAD (ADD (X, Lo(G))).
2027 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2028 && "Cannot handle constant offsets yet!");
2029 Disp = N.getOperand(1).getOperand(0); // The global address.
2030 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2031 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2032 Disp.getOpcode() == ISD::TargetConstantPool ||
2033 Disp.getOpcode() == ISD::TargetJumpTable);
2034 Base = N.getOperand(0);
2035 return true; // [&g+r]
2037 } else if (N.getOpcode() == ISD::OR) {
2039 if (isIntS16Immediate(N.getOperand(1), imm) &&
2040 (!Aligned || (imm & 3) == 0)) {
2041 // If this is an or of disjoint bitfields, we can codegen this as an add
2042 // (for better address arithmetic) if the LHS and RHS of the OR are
2043 // provably disjoint.
2045 DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2047 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2048 // If all of the bits are known zero on the LHS or RHS, the add won't
2050 if (FrameIndexSDNode *FI =
2051 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2052 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2053 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2055 Base = N.getOperand(0);
2057 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2061 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2062 // Loading from a constant address.
2064 // If this address fits entirely in a 16-bit sext immediate field, codegen
2067 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
2068 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2069 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2070 CN->getValueType(0));
2074 // Handle 32-bit sext immediates with LIS + addr mode.
2075 if ((CN->getValueType(0) == MVT::i32 ||
2076 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2077 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
2078 int Addr = (int)CN->getZExtValue();
2080 // Otherwise, break this down into an LIS + disp.
2081 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2083 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2085 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2086 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2091 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2092 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2093 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2094 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2097 return true; // [r+0]
2100 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2101 /// represented as an indexed [r+r] operation.
2102 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2104 SelectionDAG &DAG) const {
2105 // Check to see if we can easily represent this as an [r+r] address. This
2106 // will fail if it thinks that the address is more profitably represented as
2107 // reg+imm, e.g. where imm = 0.
2108 if (SelectAddressRegReg(N, Base, Index, DAG))
2111 // If the operand is an addition, always emit this as [r+r], since this is
2112 // better (for code size, and execution, as the memop does the add for free)
2113 // than emitting an explicit add.
2114 if (N.getOpcode() == ISD::ADD) {
2115 Base = N.getOperand(0);
2116 Index = N.getOperand(1);
2120 // Otherwise, do it the hard way, using R0 as the base register.
2121 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2127 /// getPreIndexedAddressParts - returns true by value, base pointer and
2128 /// offset pointer and addressing mode by reference if the node's address
2129 /// can be legally represented as pre-indexed load / store address.
2130 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2132 ISD::MemIndexedMode &AM,
2133 SelectionDAG &DAG) const {
2134 if (DisablePPCPreinc) return false;
2140 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2141 Ptr = LD->getBasePtr();
2142 VT = LD->getMemoryVT();
2143 Alignment = LD->getAlignment();
2144 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2145 Ptr = ST->getBasePtr();
2146 VT = ST->getMemoryVT();
2147 Alignment = ST->getAlignment();
2152 // PowerPC doesn't have preinc load/store instructions for vectors (except
2153 // for QPX, which does have preinc r+r forms).
2154 if (VT.isVector()) {
2155 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2157 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2163 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2164 // Common code will reject creating a pre-inc form if the base pointer
2165 // is a frame index, or if N is a store and the base pointer is either
2166 // the same as or a predecessor of the value being stored. Check for
2167 // those situations here, and try with swapped Base/Offset instead.
2170 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2173 SDValue Val = cast<StoreSDNode>(N)->getValue();
2174 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2179 std::swap(Base, Offset);
2185 // LDU/STU can only handle immediates that are a multiple of 4.
2186 if (VT != MVT::i64) {
2187 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2190 // LDU/STU need an address with at least 4-byte alignment.
2194 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2198 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2199 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2200 // sext i32 to i64 when addr mode is r+i.
2201 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2202 LD->getExtensionType() == ISD::SEXTLOAD &&
2203 isa<ConstantSDNode>(Offset))
2211 //===----------------------------------------------------------------------===//
2212 // LowerOperation implementation
2213 //===----------------------------------------------------------------------===//
2215 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2216 /// and LoOpFlags to the target MO flags.
2217 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2218 unsigned &HiOpFlags, unsigned &LoOpFlags,
2219 const GlobalValue *GV = nullptr) {
2220 HiOpFlags = PPCII::MO_HA;
2221 LoOpFlags = PPCII::MO_LO;
2223 // Don't use the pic base if not in PIC relocation model.
2225 HiOpFlags |= PPCII::MO_PIC_FLAG;
2226 LoOpFlags |= PPCII::MO_PIC_FLAG;
2229 // If this is a reference to a global value that requires a non-lazy-ptr, make
2230 // sure that instruction lowering adds it.
2231 if (GV && Subtarget.hasLazyResolverStub(GV)) {
2232 HiOpFlags |= PPCII::MO_NLP_FLAG;
2233 LoOpFlags |= PPCII::MO_NLP_FLAG;
2235 if (GV->hasHiddenVisibility()) {
2236 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2237 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2242 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2243 SelectionDAG &DAG) {
2245 EVT PtrVT = HiPart.getValueType();
2246 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2248 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2249 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2251 // With PIC, the first instruction is actually "GR+hi(&G)".
2253 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2254 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2256 // Generate non-pic code that has direct accesses to the constant pool.
2257 // The address of the global is just (hi(&g)+lo(&g)).
2258 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2261 static void setUsesTOCBasePtr(MachineFunction &MF) {
2262 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2263 FuncInfo->setUsesTOCBasePtr();
2266 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2267 setUsesTOCBasePtr(DAG.getMachineFunction());
2270 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2272 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2273 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2274 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2276 SDValue Ops[] = { GA, Reg };
2277 return DAG.getMemIntrinsicNode(
2278 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2279 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2283 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2284 SelectionDAG &DAG) const {
2285 EVT PtrVT = Op.getValueType();
2286 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2287 const Constant *C = CP->getConstVal();
2289 // 64-bit SVR4 ABI code is always position-independent.
2290 // The actual address of the GlobalValue is stored in the TOC.
2291 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2292 setUsesTOCBasePtr(DAG);
2293 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2294 return getTOCEntry(DAG, SDLoc(CP), true, GA);
2297 unsigned MOHiFlag, MOLoFlag;
2298 bool IsPIC = isPositionIndependent();
2299 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2301 if (IsPIC && Subtarget.isSVR4ABI()) {
2302 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2303 PPCII::MO_PIC_FLAG);
2304 return getTOCEntry(DAG, SDLoc(CP), false, GA);
2308 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2310 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2311 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2314 // For 64-bit PowerPC, prefer the more compact relative encodings.
2315 // This trades 32 bits per jump table entry for one or two instructions
2316 // on the jump site.
2317 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2318 if (isJumpTableRelative())
2319 return MachineJumpTableInfo::EK_LabelDifference32;
2321 return TargetLowering::getJumpTableEncoding();
2324 bool PPCTargetLowering::isJumpTableRelative() const {
2325 if (Subtarget.isPPC64())
2327 return TargetLowering::isJumpTableRelative();
2330 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2331 SelectionDAG &DAG) const {
2332 if (!Subtarget.isPPC64())
2333 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2335 switch (getTargetMachine().getCodeModel()) {
2336 case CodeModel::Default:
2337 case CodeModel::Small:
2338 case CodeModel::Medium:
2339 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2341 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2342 getPointerTy(DAG.getDataLayout()));
2347 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2349 MCContext &Ctx) const {
2350 if (!Subtarget.isPPC64())
2351 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2353 switch (getTargetMachine().getCodeModel()) {
2354 case CodeModel::Default:
2355 case CodeModel::Small:
2356 case CodeModel::Medium:
2357 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2359 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2363 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2364 EVT PtrVT = Op.getValueType();
2365 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2367 // 64-bit SVR4 ABI code is always position-independent.
2368 // The actual address of the GlobalValue is stored in the TOC.
2369 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2370 setUsesTOCBasePtr(DAG);
2371 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2372 return getTOCEntry(DAG, SDLoc(JT), true, GA);
2375 unsigned MOHiFlag, MOLoFlag;
2376 bool IsPIC = isPositionIndependent();
2377 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2379 if (IsPIC && Subtarget.isSVR4ABI()) {
2380 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2381 PPCII::MO_PIC_FLAG);
2382 return getTOCEntry(DAG, SDLoc(GA), false, GA);
2385 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2386 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2387 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2390 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2391 SelectionDAG &DAG) const {
2392 EVT PtrVT = Op.getValueType();
2393 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2394 const BlockAddress *BA = BASDN->getBlockAddress();
2396 // 64-bit SVR4 ABI code is always position-independent.
2397 // The actual BlockAddress is stored in the TOC.
2398 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2399 setUsesTOCBasePtr(DAG);
2400 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2401 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2404 unsigned MOHiFlag, MOLoFlag;
2405 bool IsPIC = isPositionIndependent();
2406 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2407 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2408 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2409 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2412 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2413 SelectionDAG &DAG) const {
2414 // FIXME: TLS addresses currently use medium model code sequences,
2415 // which is the most useful form. Eventually support for small and
2416 // large models could be added if users need it, at the cost of
2417 // additional complexity.
2418 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2419 if (DAG.getTarget().Options.EmulatedTLS)
2420 return LowerToTLSEmulatedModel(GA, DAG);
2423 const GlobalValue *GV = GA->getGlobal();
2424 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2425 bool is64bit = Subtarget.isPPC64();
2426 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2427 PICLevel::Level picLevel = M->getPICLevel();
2429 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2431 if (Model == TLSModel::LocalExec) {
2432 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2433 PPCII::MO_TPREL_HA);
2434 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2435 PPCII::MO_TPREL_LO);
2436 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2437 is64bit ? MVT::i64 : MVT::i32);
2438 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2439 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2442 if (Model == TLSModel::InitialExec) {
2443 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2444 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2448 setUsesTOCBasePtr(DAG);
2449 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2450 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2451 PtrVT, GOTReg, TGA);
2453 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2454 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2455 PtrVT, TGA, GOTPtr);
2456 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2459 if (Model == TLSModel::GeneralDynamic) {
2460 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2463 setUsesTOCBasePtr(DAG);
2464 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2465 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2468 if (picLevel == PICLevel::SmallPIC)
2469 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2471 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2473 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2477 if (Model == TLSModel::LocalDynamic) {
2478 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2481 setUsesTOCBasePtr(DAG);
2482 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2483 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2486 if (picLevel == PICLevel::SmallPIC)
2487 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2489 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2491 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2492 PtrVT, GOTPtr, TGA, TGA);
2493 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2494 PtrVT, TLSAddr, TGA);
2495 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2498 llvm_unreachable("Unknown TLS model!");
2501 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2502 SelectionDAG &DAG) const {
2503 EVT PtrVT = Op.getValueType();
2504 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2506 const GlobalValue *GV = GSDN->getGlobal();
2508 // 64-bit SVR4 ABI code is always position-independent.
2509 // The actual address of the GlobalValue is stored in the TOC.
2510 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2511 setUsesTOCBasePtr(DAG);
2512 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2513 return getTOCEntry(DAG, DL, true, GA);
2516 unsigned MOHiFlag, MOLoFlag;
2517 bool IsPIC = isPositionIndependent();
2518 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2520 if (IsPIC && Subtarget.isSVR4ABI()) {
2521 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2523 PPCII::MO_PIC_FLAG);
2524 return getTOCEntry(DAG, DL, false, GA);
2528 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2530 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2532 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2534 // If the global reference is actually to a non-lazy-pointer, we have to do an
2535 // extra load to get the address of the global.
2536 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2537 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2541 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2542 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2545 if (Op.getValueType() == MVT::v2i64) {
2546 // When the operands themselves are v2i64 values, we need to do something
2547 // special because VSX has no underlying comparison operations for these.
2548 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2549 // Equality can be handled by casting to the legal type for Altivec
2550 // comparisons, everything else needs to be expanded.
2551 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2552 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2553 DAG.getSetCC(dl, MVT::v4i32,
2554 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2555 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2562 // We handle most of these in the usual way.
2566 // If we're comparing for equality to zero, expose the fact that this is
2567 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2568 // fold the new nodes.
2569 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2572 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2573 // Leave comparisons against 0 and -1 alone for now, since they're usually
2574 // optimized. FIXME: revisit this when we can custom lower all setcc
2576 if (C->isAllOnesValue() || C->isNullValue())
2580 // If we have an integer seteq/setne, turn it into a compare against zero
2581 // by xor'ing the rhs with the lhs, which is faster than setting a
2582 // condition register, reading it back out, and masking the correct bit. The
2583 // normal approach here uses sub to do this instead of xor. Using xor exposes
2584 // the result to other bit-twiddling opportunities.
2585 EVT LHSVT = Op.getOperand(0).getValueType();
2586 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2587 EVT VT = Op.getValueType();
2588 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2590 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2595 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2596 SDNode *Node = Op.getNode();
2597 EVT VT = Node->getValueType(0);
2598 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2599 SDValue InChain = Node->getOperand(0);
2600 SDValue VAListPtr = Node->getOperand(1);
2601 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2604 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2607 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2608 VAListPtr, MachinePointerInfo(SV), MVT::i8);
2609 InChain = GprIndex.getValue(1);
2611 if (VT == MVT::i64) {
2612 // Check if GprIndex is even
2613 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2614 DAG.getConstant(1, dl, MVT::i32));
2615 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2616 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2617 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2618 DAG.getConstant(1, dl, MVT::i32));
2619 // Align GprIndex to be even if it isn't
2620 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2624 // fpr index is 1 byte after gpr
2625 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2626 DAG.getConstant(1, dl, MVT::i32));
2629 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2630 FprPtr, MachinePointerInfo(SV), MVT::i8);
2631 InChain = FprIndex.getValue(1);
2633 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2634 DAG.getConstant(8, dl, MVT::i32));
2636 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2637 DAG.getConstant(4, dl, MVT::i32));
2640 SDValue OverflowArea =
2641 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2642 InChain = OverflowArea.getValue(1);
2644 SDValue RegSaveArea =
2645 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2646 InChain = RegSaveArea.getValue(1);
2648 // select overflow_area if index > 8
2649 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2650 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2652 // adjustment constant gpr_index * 4/8
2653 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2654 VT.isInteger() ? GprIndex : FprIndex,
2655 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2658 // OurReg = RegSaveArea + RegConstant
2659 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2662 // Floating types are 32 bytes into RegSaveArea
2663 if (VT.isFloatingPoint())
2664 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2665 DAG.getConstant(32, dl, MVT::i32));
2667 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2668 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2669 VT.isInteger() ? GprIndex : FprIndex,
2670 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2673 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2674 VT.isInteger() ? VAListPtr : FprPtr,
2675 MachinePointerInfo(SV), MVT::i8);
2677 // determine if we should load from reg_save_area or overflow_area
2678 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2680 // increase overflow_area by 4/8 if gpr/fpr > 8
2681 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2682 DAG.getConstant(VT.isInteger() ? 4 : 8,
2685 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2688 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2689 MachinePointerInfo(), MVT::i32);
2691 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2694 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2695 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2697 // We have to copy the entire va_list struct:
2698 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2699 return DAG.getMemcpy(Op.getOperand(0), Op,
2700 Op.getOperand(1), Op.getOperand(2),
2701 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2702 false, MachinePointerInfo(), MachinePointerInfo());
2705 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2706 SelectionDAG &DAG) const {
2707 return Op.getOperand(0);
2710 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2711 SelectionDAG &DAG) const {
2712 SDValue Chain = Op.getOperand(0);
2713 SDValue Trmp = Op.getOperand(1); // trampoline
2714 SDValue FPtr = Op.getOperand(2); // nested function
2715 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2718 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2719 bool isPPC64 = (PtrVT == MVT::i64);
2720 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2722 TargetLowering::ArgListTy Args;
2723 TargetLowering::ArgListEntry Entry;
2725 Entry.Ty = IntPtrTy;
2726 Entry.Node = Trmp; Args.push_back(Entry);
2728 // TrampSize == (isPPC64 ? 48 : 40);
2729 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2730 isPPC64 ? MVT::i64 : MVT::i32);
2731 Args.push_back(Entry);
2733 Entry.Node = FPtr; Args.push_back(Entry);
2734 Entry.Node = Nest; Args.push_back(Entry);
2736 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2737 TargetLowering::CallLoweringInfo CLI(DAG);
2738 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2739 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2740 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2742 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2743 return CallResult.second;
2746 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2747 MachineFunction &MF = DAG.getMachineFunction();
2748 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2749 EVT PtrVT = getPointerTy(MF.getDataLayout());
2753 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2754 // vastart just stores the address of the VarArgsFrameIndex slot into the
2755 // memory location argument.
2756 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2757 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2758 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2759 MachinePointerInfo(SV));
2762 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2763 // We suppose the given va_list is already allocated.
2766 // char gpr; /* index into the array of 8 GPRs
2767 // * stored in the register save area
2768 // * gpr=0 corresponds to r3,
2769 // * gpr=1 to r4, etc.
2771 // char fpr; /* index into the array of 8 FPRs
2772 // * stored in the register save area
2773 // * fpr=0 corresponds to f1,
2774 // * fpr=1 to f2, etc.
2776 // char *overflow_arg_area;
2777 // /* location on stack that holds
2778 // * the next overflow argument
2780 // char *reg_save_area;
2781 // /* where r3:r10 and f1:f8 (if saved)
2786 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2787 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2788 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2790 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2793 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2794 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2796 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2797 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2799 uint64_t FPROffset = 1;
2800 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2802 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2804 // Store first byte : number of int regs
2805 SDValue firstStore =
2806 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2807 MachinePointerInfo(SV), MVT::i8);
2808 uint64_t nextOffset = FPROffset;
2809 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2812 // Store second byte : number of float regs
2813 SDValue secondStore =
2814 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2815 MachinePointerInfo(SV, nextOffset), MVT::i8);
2816 nextOffset += StackOffset;
2817 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2819 // Store second word : arguments given on stack
2820 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2821 MachinePointerInfo(SV, nextOffset));
2822 nextOffset += FrameOffset;
2823 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2825 // Store third word : arguments given in registers
2826 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2827 MachinePointerInfo(SV, nextOffset));
2830 #include "PPCGenCallingConv.inc"
2832 // Function whose sole purpose is to kill compiler warnings
2833 // stemming from unused functions included from PPCGenCallingConv.inc.
2834 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2835 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2838 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2839 CCValAssign::LocInfo &LocInfo,
2840 ISD::ArgFlagsTy &ArgFlags,
2845 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2847 CCValAssign::LocInfo &LocInfo,
2848 ISD::ArgFlagsTy &ArgFlags,
2850 static const MCPhysReg ArgRegs[] = {
2851 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2852 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2854 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2856 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2858 // Skip one register if the first unallocated register has an even register
2859 // number and there are still argument registers available which have not been
2860 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2861 // need to skip a register if RegNum is odd.
2862 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2863 State.AllocateReg(ArgRegs[RegNum]);
2866 // Always return false here, as this function only makes sure that the first
2867 // unallocated register has an odd register number and does not actually
2868 // allocate a register for the current argument.
2873 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2875 CCValAssign::LocInfo &LocInfo,
2876 ISD::ArgFlagsTy &ArgFlags,
2878 static const MCPhysReg ArgRegs[] = {
2879 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2880 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2882 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2884 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2885 int RegsLeft = NumArgRegs - RegNum;
2887 // Skip if there is not enough registers left for long double type (4 gpr regs
2888 // in soft float mode) and put long double argument on the stack.
2889 if (RegNum != NumArgRegs && RegsLeft < 4) {
2890 for (int i = 0; i < RegsLeft; i++) {
2891 State.AllocateReg(ArgRegs[RegNum + i]);
2898 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2900 CCValAssign::LocInfo &LocInfo,
2901 ISD::ArgFlagsTy &ArgFlags,
2903 static const MCPhysReg ArgRegs[] = {
2904 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2908 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2910 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2912 // If there is only one Floating-point register left we need to put both f64
2913 // values of a split ppc_fp128 value on the stack.
2914 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2915 State.AllocateReg(ArgRegs[RegNum]);
2918 // Always return false here, as this function only makes sure that the two f64
2919 // values a ppc_fp128 value is split into are both passed in registers or both
2920 // passed on the stack and does not actually allocate a register for the
2921 // current argument.
2925 /// FPR - The set of FP registers that should be allocated for arguments,
2927 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2928 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2929 PPC::F11, PPC::F12, PPC::F13};
2931 /// QFPR - The set of QPX registers that should be allocated for arguments.
2932 static const MCPhysReg QFPR[] = {
2933 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2934 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2936 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2938 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2939 unsigned PtrByteSize) {
2940 unsigned ArgSize = ArgVT.getStoreSize();
2941 if (Flags.isByVal())
2942 ArgSize = Flags.getByValSize();
2944 // Round up to multiples of the pointer size, except for array members,
2945 // which are always packed.
2946 if (!Flags.isInConsecutiveRegs())
2947 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2952 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2954 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2955 ISD::ArgFlagsTy Flags,
2956 unsigned PtrByteSize) {
2957 unsigned Align = PtrByteSize;
2959 // Altivec parameters are padded to a 16 byte boundary.
2960 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2961 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2962 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2963 ArgVT == MVT::v1i128)
2965 // QPX vector types stored in double-precision are padded to a 32 byte
2967 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2970 // ByVal parameters are aligned as requested.
2971 if (Flags.isByVal()) {
2972 unsigned BVAlign = Flags.getByValAlign();
2973 if (BVAlign > PtrByteSize) {
2974 if (BVAlign % PtrByteSize != 0)
2976 "ByVal alignment is not a multiple of the pointer size");
2982 // Array members are always packed to their original alignment.
2983 if (Flags.isInConsecutiveRegs()) {
2984 // If the array member was split into multiple registers, the first
2985 // needs to be aligned to the size of the full type. (Except for
2986 // ppcf128, which is only aligned as its f64 components.)
2987 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2988 Align = OrigVT.getStoreSize();
2990 Align = ArgVT.getStoreSize();
2996 /// CalculateStackSlotUsed - Return whether this argument will use its
2997 /// stack slot (instead of being passed in registers). ArgOffset,
2998 /// AvailableFPRs, and AvailableVRs must hold the current argument
2999 /// position, and will be updated to account for this argument.
3000 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3001 ISD::ArgFlagsTy Flags,
3002 unsigned PtrByteSize,
3003 unsigned LinkageSize,
3004 unsigned ParamAreaSize,
3005 unsigned &ArgOffset,
3006 unsigned &AvailableFPRs,
3007 unsigned &AvailableVRs, bool HasQPX) {
3008 bool UseMemory = false;
3010 // Respect alignment of argument on the stack.
3012 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3013 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3014 // If there's no space left in the argument save area, we must
3015 // use memory (this check also catches zero-sized arguments).
3016 if (ArgOffset >= LinkageSize + ParamAreaSize)
3019 // Allocate argument on the stack.
3020 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3021 if (Flags.isInConsecutiveRegsLast())
3022 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3023 // If we overran the argument save area, we must use memory
3024 // (this check catches arguments passed partially in memory)
3025 if (ArgOffset > LinkageSize + ParamAreaSize)
3028 // However, if the argument is actually passed in an FPR or a VR,
3029 // we don't use memory after all.
3030 if (!Flags.isByVal()) {
3031 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3032 // QPX registers overlap with the scalar FP registers.
3033 (HasQPX && (ArgVT == MVT::v4f32 ||
3034 ArgVT == MVT::v4f64 ||
3035 ArgVT == MVT::v4i1)))
3036 if (AvailableFPRs > 0) {
3040 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3041 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3042 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3043 ArgVT == MVT::v1i128)
3044 if (AvailableVRs > 0) {
3053 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3054 /// ensure minimum alignment required for target.
3055 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3056 unsigned NumBytes) {
3057 unsigned TargetAlign = Lowering->getStackAlignment();
3058 unsigned AlignMask = TargetAlign - 1;
3059 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3063 SDValue PPCTargetLowering::LowerFormalArguments(
3064 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3065 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3066 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3067 if (Subtarget.isSVR4ABI()) {
3068 if (Subtarget.isPPC64())
3069 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3072 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3075 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3080 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3081 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3082 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3083 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3085 // 32-bit SVR4 ABI Stack Frame Layout:
3086 // +-----------------------------------+
3087 // +--> | Back chain |
3088 // | +-----------------------------------+
3089 // | | Floating-point register save area |
3090 // | +-----------------------------------+
3091 // | | General register save area |
3092 // | +-----------------------------------+
3093 // | | CR save word |
3094 // | +-----------------------------------+
3095 // | | VRSAVE save word |
3096 // | +-----------------------------------+
3097 // | | Alignment padding |
3098 // | +-----------------------------------+
3099 // | | Vector register save area |
3100 // | +-----------------------------------+
3101 // | | Local variable space |
3102 // | +-----------------------------------+
3103 // | | Parameter list area |
3104 // | +-----------------------------------+
3105 // | | LR save word |
3106 // | +-----------------------------------+
3107 // SP--> +--- | Back chain |
3108 // +-----------------------------------+
3111 // System V Application Binary Interface PowerPC Processor Supplement
3112 // AltiVec Technology Programming Interface Manual
3114 MachineFunction &MF = DAG.getMachineFunction();
3115 MachineFrameInfo &MFI = MF.getFrameInfo();
3116 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3118 EVT PtrVT = getPointerTy(MF.getDataLayout());
3119 // Potential tail calls could cause overwriting of argument stack slots.
3120 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3121 (CallConv == CallingConv::Fast));
3122 unsigned PtrByteSize = 4;
3124 // Assign locations to all of the incoming arguments.
3125 SmallVector<CCValAssign, 16> ArgLocs;
3126 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3129 // Reserve space for the linkage area on the stack.
3130 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3131 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3133 CCInfo.PreAnalyzeFormalArguments(Ins);
3135 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3136 CCInfo.clearWasPPCF128();
3138 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3139 CCValAssign &VA = ArgLocs[i];
3141 // Arguments stored in registers.
3142 if (VA.isRegLoc()) {
3143 const TargetRegisterClass *RC;
3144 EVT ValVT = VA.getValVT();
3146 switch (ValVT.getSimpleVT().SimpleTy) {
3148 llvm_unreachable("ValVT not supported by formal arguments Lowering");
3151 RC = &PPC::GPRCRegClass;
3154 if (Subtarget.hasP8Vector())
3155 RC = &PPC::VSSRCRegClass;
3157 RC = &PPC::F4RCRegClass;
3160 if (Subtarget.hasVSX())
3161 RC = &PPC::VSFRCRegClass;
3163 RC = &PPC::F8RCRegClass;
3168 RC = &PPC::VRRCRegClass;
3171 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3175 RC = &PPC::VRRCRegClass;
3178 RC = &PPC::QFRCRegClass;
3181 RC = &PPC::QBRCRegClass;
3185 // Transform the arguments stored in physical registers into virtual ones.
3186 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3187 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3188 ValVT == MVT::i1 ? MVT::i32 : ValVT);
3190 if (ValVT == MVT::i1)
3191 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3193 InVals.push_back(ArgValue);
3195 // Argument stored in memory.
3196 assert(VA.isMemLoc());
3198 unsigned ArgSize = VA.getLocVT().getStoreSize();
3199 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3202 // Create load nodes to retrieve arguments from the stack.
3203 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3205 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3209 // Assign locations to all of the incoming aggregate by value arguments.
3210 // Aggregates passed by value are stored in the local variable space of the
3211 // caller's stack frame, right above the parameter list area.
3212 SmallVector<CCValAssign, 16> ByValArgLocs;
3213 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3214 ByValArgLocs, *DAG.getContext());
3216 // Reserve stack space for the allocations in CCInfo.
3217 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3219 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3221 // Area that is at least reserved in the caller of this function.
3222 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3223 MinReservedArea = std::max(MinReservedArea, LinkageSize);
3225 // Set the size that is at least reserved in caller of this function. Tail
3226 // call optimized function's reserved stack space needs to be aligned so that
3227 // taking the difference between two stack areas will result in an aligned
3230 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3231 FuncInfo->setMinReservedArea(MinReservedArea);
3233 SmallVector<SDValue, 8> MemOps;
3235 // If the function takes variable number of arguments, make a frame index for
3236 // the start of the first vararg value... for expansion of llvm.va_start.
3238 static const MCPhysReg GPArgRegs[] = {
3239 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3240 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3242 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3244 static const MCPhysReg FPArgRegs[] = {
3245 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3248 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3253 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3254 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3256 // Make room for NumGPArgRegs and NumFPArgRegs.
3257 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3258 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3260 FuncInfo->setVarArgsStackOffset(
3261 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3262 CCInfo.getNextStackOffset(), true));
3264 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3265 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3267 // The fixed integer arguments of a variadic function are stored to the
3268 // VarArgsFrameIndex on the stack so that they may be loaded by
3269 // dereferencing the result of va_next.
3270 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3271 // Get an existing live-in vreg, or add a new one.
3272 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3274 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3276 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3278 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3279 MemOps.push_back(Store);
3280 // Increment the address by four for the next argument to store
3281 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3282 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3285 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3287 // The double arguments are stored to the VarArgsFrameIndex
3289 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3290 // Get an existing live-in vreg, or add a new one.
3291 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3293 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3295 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3297 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3298 MemOps.push_back(Store);
3299 // Increment the address by eight for the next argument to store
3300 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3302 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3306 if (!MemOps.empty())
3307 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3312 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3313 // value to MVT::i64 and then truncate to the correct register size.
3314 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3315 EVT ObjectVT, SelectionDAG &DAG,
3317 const SDLoc &dl) const {
3319 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3320 DAG.getValueType(ObjectVT));
3321 else if (Flags.isZExt())
3322 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3323 DAG.getValueType(ObjectVT));
3325 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3328 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3329 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3330 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3331 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3332 // TODO: add description of PPC stack frame format, or at least some docs.
3334 bool isELFv2ABI = Subtarget.isELFv2ABI();
3335 bool isLittleEndian = Subtarget.isLittleEndian();
3336 MachineFunction &MF = DAG.getMachineFunction();
3337 MachineFrameInfo &MFI = MF.getFrameInfo();
3338 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3340 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3341 "fastcc not supported on varargs functions");
3343 EVT PtrVT = getPointerTy(MF.getDataLayout());
3344 // Potential tail calls could cause overwriting of argument stack slots.
3345 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3346 (CallConv == CallingConv::Fast));
3347 unsigned PtrByteSize = 8;
3348 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3350 static const MCPhysReg GPR[] = {
3351 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3352 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3354 static const MCPhysReg VR[] = {
3355 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3356 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3359 const unsigned Num_GPR_Regs = array_lengthof(GPR);
3360 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3361 const unsigned Num_VR_Regs = array_lengthof(VR);
3362 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3364 // Do a first pass over the arguments to determine whether the ABI
3365 // guarantees that our caller has allocated the parameter save area
3366 // on its stack frame. In the ELFv1 ABI, this is always the case;
3367 // in the ELFv2 ABI, it is true if this is a vararg function or if
3368 // any parameter is located in a stack slot.
3370 bool HasParameterArea = !isELFv2ABI || isVarArg;
3371 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3372 unsigned NumBytes = LinkageSize;
3373 unsigned AvailableFPRs = Num_FPR_Regs;
3374 unsigned AvailableVRs = Num_VR_Regs;
3375 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3376 if (Ins[i].Flags.isNest())
3379 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3380 PtrByteSize, LinkageSize, ParamAreaSize,
3381 NumBytes, AvailableFPRs, AvailableVRs,
3382 Subtarget.hasQPX()))
3383 HasParameterArea = true;
3386 // Add DAG nodes to load the arguments or copy them out of registers. On
3387 // entry to a function on PPC, the arguments start after the linkage area,
3388 // although the first ones are often in registers.
3390 unsigned ArgOffset = LinkageSize;
3391 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3392 unsigned &QFPR_idx = FPR_idx;
3393 SmallVector<SDValue, 8> MemOps;
3394 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3395 unsigned CurArgIdx = 0;
3396 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3398 bool needsLoad = false;
3399 EVT ObjectVT = Ins[ArgNo].VT;
3400 EVT OrigVT = Ins[ArgNo].ArgVT;
3401 unsigned ObjSize = ObjectVT.getStoreSize();
3402 unsigned ArgSize = ObjSize;
3403 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3404 if (Ins[ArgNo].isOrigArg()) {
3405 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3406 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3408 // We re-align the argument offset for each argument, except when using the
3409 // fast calling convention, when we need to make sure we do that only when
3410 // we'll actually use a stack slot.
3411 unsigned CurArgOffset, Align;
3412 auto ComputeArgOffset = [&]() {
3413 /* Respect alignment of argument on the stack. */
3414 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3415 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3416 CurArgOffset = ArgOffset;
3419 if (CallConv != CallingConv::Fast) {
3422 /* Compute GPR index associated with argument offset. */
3423 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3424 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3427 // FIXME the codegen can be much improved in some cases.
3428 // We do not have to keep everything in memory.
3429 if (Flags.isByVal()) {
3430 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3432 if (CallConv == CallingConv::Fast)
3435 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3436 ObjSize = Flags.getByValSize();
3437 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3438 // Empty aggregate parameters do not take up registers. Examples:
3442 // etc. However, we have to provide a place-holder in InVals, so
3443 // pretend we have an 8-byte item at the current address for that
3446 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3447 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3448 InVals.push_back(FIN);
3452 // Create a stack object covering all stack doublewords occupied
3453 // by the argument. If the argument is (fully or partially) on
3454 // the stack, or if the argument is fully in registers but the
3455 // caller has allocated the parameter save anyway, we can refer
3456 // directly to the caller's stack frame. Otherwise, create a
3457 // local copy in our own frame.
3459 if (HasParameterArea ||
3460 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3461 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3463 FI = MFI.CreateStackObject(ArgSize, Align, false);
3464 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3466 // Handle aggregates smaller than 8 bytes.
3467 if (ObjSize < PtrByteSize) {
3468 // The value of the object is its address, which differs from the
3469 // address of the enclosing doubleword on big-endian systems.
3471 if (!isLittleEndian) {
3472 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3473 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3475 InVals.push_back(Arg);
3477 if (GPR_idx != Num_GPR_Regs) {
3478 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3479 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3482 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3483 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3484 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3485 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3486 MachinePointerInfo(&*FuncArg), ObjType);
3488 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3489 // store the whole register as-is to the parameter save area
3491 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3492 MachinePointerInfo(&*FuncArg));
3495 MemOps.push_back(Store);
3497 // Whether we copied from a register or not, advance the offset
3498 // into the parameter save area by a full doubleword.
3499 ArgOffset += PtrByteSize;
3503 // The value of the object is its address, which is the address of
3504 // its first stack doubleword.
3505 InVals.push_back(FIN);
3507 // Store whatever pieces of the object are in registers to memory.
3508 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3509 if (GPR_idx == Num_GPR_Regs)
3512 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3513 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3516 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3517 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3519 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3520 MachinePointerInfo(&*FuncArg, j));
3521 MemOps.push_back(Store);
3524 ArgOffset += ArgSize;
3528 switch (ObjectVT.getSimpleVT().SimpleTy) {
3529 default: llvm_unreachable("Unhandled argument type!");
3533 if (Flags.isNest()) {
3534 // The 'nest' parameter, if any, is passed in R11.
3535 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3536 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3538 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3539 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3544 // These can be scalar arguments or elements of an integer array type
3545 // passed directly. Clang may use those instead of "byval" aggregate
3546 // types to avoid forcing arguments to memory unnecessarily.
3547 if (GPR_idx != Num_GPR_Regs) {
3548 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3549 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3551 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3552 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3553 // value to MVT::i64 and then truncate to the correct register size.
3554 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3556 if (CallConv == CallingConv::Fast)
3560 ArgSize = PtrByteSize;
3562 if (CallConv != CallingConv::Fast || needsLoad)
3568 // These can be scalar arguments or elements of a float array type
3569 // passed directly. The latter are used to implement ELFv2 homogenous
3570 // float aggregates.
3571 if (FPR_idx != Num_FPR_Regs) {
3574 if (ObjectVT == MVT::f32)
3575 VReg = MF.addLiveIn(FPR[FPR_idx],
3576 Subtarget.hasP8Vector()
3577 ? &PPC::VSSRCRegClass
3578 : &PPC::F4RCRegClass);
3580 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3581 ? &PPC::VSFRCRegClass
3582 : &PPC::F8RCRegClass);
3584 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3586 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3587 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3588 // once we support fp <-> gpr moves.
3590 // This can only ever happen in the presence of f32 array types,
3591 // since otherwise we never run out of FPRs before running out
3593 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3594 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3596 if (ObjectVT == MVT::f32) {
3597 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3598 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3599 DAG.getConstant(32, dl, MVT::i32));
3600 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3603 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3605 if (CallConv == CallingConv::Fast)
3611 // When passing an array of floats, the array occupies consecutive
3612 // space in the argument area; only round up to the next doubleword
3613 // at the end of the array. Otherwise, each float takes 8 bytes.
3614 if (CallConv != CallingConv::Fast || needsLoad) {
3615 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3616 ArgOffset += ArgSize;
3617 if (Flags.isInConsecutiveRegsLast())
3618 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3628 if (!Subtarget.hasQPX()) {
3629 // These can be scalar arguments or elements of a vector array type
3630 // passed directly. The latter are used to implement ELFv2 homogenous
3631 // vector aggregates.
3632 if (VR_idx != Num_VR_Regs) {
3633 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3634 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3637 if (CallConv == CallingConv::Fast)
3642 if (CallConv != CallingConv::Fast || needsLoad)
3647 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3648 "Invalid QPX parameter type");
3653 // QPX vectors are treated like their scalar floating-point subregisters
3654 // (except that they're larger).
3655 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3656 if (QFPR_idx != Num_QFPR_Regs) {
3657 const TargetRegisterClass *RC;
3658 switch (ObjectVT.getSimpleVT().SimpleTy) {
3659 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3660 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3661 default: RC = &PPC::QBRCRegClass; break;
3664 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3665 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3668 if (CallConv == CallingConv::Fast)
3672 if (CallConv != CallingConv::Fast || needsLoad)
3677 // We need to load the argument to a virtual register if we determined
3678 // above that we ran out of physical registers of the appropriate type.
3680 if (ObjSize < ArgSize && !isLittleEndian)
3681 CurArgOffset += ArgSize - ObjSize;
3682 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3683 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3684 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3687 InVals.push_back(ArgVal);
3690 // Area that is at least reserved in the caller of this function.
3691 unsigned MinReservedArea;
3692 if (HasParameterArea)
3693 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3695 MinReservedArea = LinkageSize;
3697 // Set the size that is at least reserved in caller of this function. Tail
3698 // call optimized functions' reserved stack space needs to be aligned so that
3699 // taking the difference between two stack areas will result in an aligned
3702 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3703 FuncInfo->setMinReservedArea(MinReservedArea);
3705 // If the function takes variable number of arguments, make a frame index for
3706 // the start of the first vararg value... for expansion of llvm.va_start.
3708 int Depth = ArgOffset;
3710 FuncInfo->setVarArgsFrameIndex(
3711 MFI.CreateFixedObject(PtrByteSize, Depth, true));
3712 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3714 // If this function is vararg, store any remaining integer argument regs
3715 // to their spots on the stack so that they may be loaded by dereferencing
3716 // the result of va_next.
3717 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3718 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3719 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3720 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3722 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3723 MemOps.push_back(Store);
3724 // Increment the address by four for the next argument to store
3725 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3726 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3730 if (!MemOps.empty())
3731 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3736 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3737 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3738 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3739 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3740 // TODO: add description of PPC stack frame format, or at least some docs.
3742 MachineFunction &MF = DAG.getMachineFunction();
3743 MachineFrameInfo &MFI = MF.getFrameInfo();
3744 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3746 EVT PtrVT = getPointerTy(MF.getDataLayout());
3747 bool isPPC64 = PtrVT == MVT::i64;
3748 // Potential tail calls could cause overwriting of argument stack slots.
3749 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3750 (CallConv == CallingConv::Fast));
3751 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3752 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3753 unsigned ArgOffset = LinkageSize;
3754 // Area that is at least reserved in caller of this function.
3755 unsigned MinReservedArea = ArgOffset;
3757 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3758 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3759 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3761 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3762 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3763 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3765 static const MCPhysReg VR[] = {
3766 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3767 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3770 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3771 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3772 const unsigned Num_VR_Regs = array_lengthof( VR);
3774 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3776 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3778 // In 32-bit non-varargs functions, the stack space for vectors is after the
3779 // stack space for non-vectors. We do not use this space unless we have
3780 // too many vectors to fit in registers, something that only occurs in
3781 // constructed examples:), but we have to walk the arglist to figure
3782 // that out...for the pathological case, compute VecArgOffset as the
3783 // start of the vector parameter area. Computing VecArgOffset is the
3784 // entire point of the following loop.
3785 unsigned VecArgOffset = ArgOffset;
3786 if (!isVarArg && !isPPC64) {
3787 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3789 EVT ObjectVT = Ins[ArgNo].VT;
3790 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3792 if (Flags.isByVal()) {
3793 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3794 unsigned ObjSize = Flags.getByValSize();
3796 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3797 VecArgOffset += ArgSize;
3801 switch(ObjectVT.getSimpleVT().SimpleTy) {
3802 default: llvm_unreachable("Unhandled argument type!");
3808 case MVT::i64: // PPC64
3810 // FIXME: We are guaranteed to be !isPPC64 at this point.
3811 // Does MVT::i64 apply?
3818 // Nothing to do, we're only looking at Nonvector args here.
3823 // We've found where the vector parameter area in memory is. Skip the
3824 // first 12 parameters; these don't use that memory.
3825 VecArgOffset = ((VecArgOffset+15)/16)*16;
3826 VecArgOffset += 12*16;
3828 // Add DAG nodes to load the arguments or copy them out of registers. On
3829 // entry to a function on PPC, the arguments start after the linkage area,
3830 // although the first ones are often in registers.
3832 SmallVector<SDValue, 8> MemOps;
3833 unsigned nAltivecParamsAtEnd = 0;
3834 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3835 unsigned CurArgIdx = 0;
3836 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3838 bool needsLoad = false;
3839 EVT ObjectVT = Ins[ArgNo].VT;
3840 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3841 unsigned ArgSize = ObjSize;
3842 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3843 if (Ins[ArgNo].isOrigArg()) {
3844 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3845 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3847 unsigned CurArgOffset = ArgOffset;
3849 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3850 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3851 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3852 if (isVarArg || isPPC64) {
3853 MinReservedArea = ((MinReservedArea+15)/16)*16;
3854 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3857 } else nAltivecParamsAtEnd++;
3859 // Calculate min reserved area.
3860 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3864 // FIXME the codegen can be much improved in some cases.
3865 // We do not have to keep everything in memory.
3866 if (Flags.isByVal()) {
3867 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3869 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3870 ObjSize = Flags.getByValSize();
3871 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3872 // Objects of size 1 and 2 are right justified, everything else is
3873 // left justified. This means the memory address is adjusted forwards.
3874 if (ObjSize==1 || ObjSize==2) {
3875 CurArgOffset = CurArgOffset + (4 - ObjSize);
3877 // The value of the object is its address.
3878 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3879 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3880 InVals.push_back(FIN);
3881 if (ObjSize==1 || ObjSize==2) {
3882 if (GPR_idx != Num_GPR_Regs) {
3885 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3887 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3888 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3889 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3891 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3892 MachinePointerInfo(&*FuncArg), ObjType);
3893 MemOps.push_back(Store);
3897 ArgOffset += PtrByteSize;
3901 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3902 // Store whatever pieces of the object are in registers
3903 // to memory. ArgOffset will be the address of the beginning
3905 if (GPR_idx != Num_GPR_Regs) {
3908 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3910 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3911 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3912 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3913 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3914 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3915 MachinePointerInfo(&*FuncArg, j));
3916 MemOps.push_back(Store);
3918 ArgOffset += PtrByteSize;
3920 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3927 switch (ObjectVT.getSimpleVT().SimpleTy) {
3928 default: llvm_unreachable("Unhandled argument type!");
3932 if (GPR_idx != Num_GPR_Regs) {
3933 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3934 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3936 if (ObjectVT == MVT::i1)
3937 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3942 ArgSize = PtrByteSize;
3944 // All int arguments reserve stack space in the Darwin ABI.
3945 ArgOffset += PtrByteSize;
3949 case MVT::i64: // PPC64
3950 if (GPR_idx != Num_GPR_Regs) {
3951 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3952 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3954 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3955 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3956 // value to MVT::i64 and then truncate to the correct register size.
3957 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3962 ArgSize = PtrByteSize;
3964 // All int arguments reserve stack space in the Darwin ABI.
3970 // Every 4 bytes of argument space consumes one of the GPRs available for
3971 // argument passing.
3972 if (GPR_idx != Num_GPR_Regs) {
3974 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3977 if (FPR_idx != Num_FPR_Regs) {
3980 if (ObjectVT == MVT::f32)
3981 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3983 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3985 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3991 // All FP arguments reserve stack space in the Darwin ABI.
3992 ArgOffset += isPPC64 ? 8 : ObjSize;
3998 // Note that vector arguments in registers don't reserve stack space,
3999 // except in varargs functions.
4000 if (VR_idx != Num_VR_Regs) {
4001 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4002 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4004 while ((ArgOffset % 16) != 0) {
4005 ArgOffset += PtrByteSize;
4006 if (GPR_idx != Num_GPR_Regs)
4010 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4014 if (!isVarArg && !isPPC64) {
4015 // Vectors go after all the nonvectors.
4016 CurArgOffset = VecArgOffset;
4019 // Vectors are aligned.
4020 ArgOffset = ((ArgOffset+15)/16)*16;
4021 CurArgOffset = ArgOffset;
4029 // We need to load the argument to a virtual register if we determined above
4030 // that we ran out of physical registers of the appropriate type.
4032 int FI = MFI.CreateFixedObject(ObjSize,
4033 CurArgOffset + (ArgSize - ObjSize),
4035 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4036 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4039 InVals.push_back(ArgVal);
4042 // Allow for Altivec parameters at the end, if needed.
4043 if (nAltivecParamsAtEnd) {
4044 MinReservedArea = ((MinReservedArea+15)/16)*16;
4045 MinReservedArea += 16*nAltivecParamsAtEnd;
4048 // Area that is at least reserved in the caller of this function.
4049 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4051 // Set the size that is at least reserved in caller of this function. Tail
4052 // call optimized functions' reserved stack space needs to be aligned so that
4053 // taking the difference between two stack areas will result in an aligned
4056 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4057 FuncInfo->setMinReservedArea(MinReservedArea);
4059 // If the function takes variable number of arguments, make a frame index for
4060 // the start of the first vararg value... for expansion of llvm.va_start.
4062 int Depth = ArgOffset;
4064 FuncInfo->setVarArgsFrameIndex(
4065 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4067 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4069 // If this function is vararg, store any remaining integer argument regs
4070 // to their spots on the stack so that they may be loaded by dereferencing
4071 // the result of va_next.
4072 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4076 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4078 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4080 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4082 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4083 MemOps.push_back(Store);
4084 // Increment the address by four for the next argument to store
4085 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4086 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4090 if (!MemOps.empty())
4091 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4096 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4097 /// adjusted to accommodate the arguments for the tailcall.
4098 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4099 unsigned ParamSize) {
4101 if (!isTailCall) return 0;
4103 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4104 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4105 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4106 // Remember only if the new adjustement is bigger.
4107 if (SPDiff < FI->getTailCallSPDelta())
4108 FI->setTailCallSPDelta(SPDiff);
4113 static bool isFunctionGlobalAddress(SDValue Callee);
4116 resideInSameSection(const Function *Caller, SDValue Callee,
4117 const TargetMachine &TM) {
4118 // If !G, Callee can be an external symbol.
4119 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4123 const GlobalValue *GV = G->getGlobal();
4124 if (!GV->isStrongDefinitionForLinker())
4127 // Any explicitly-specified sections and section prefixes must also match.
4128 // Also, if we're using -ffunction-sections, then each function is always in
4129 // a different section (the same is true for COMDAT functions).
4130 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4131 GV->getSection() != Caller->getSection())
4133 if (const auto *F = dyn_cast<Function>(GV)) {
4134 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4138 // If the callee might be interposed, then we can't assume the ultimate call
4139 // target will be in the same section. Even in cases where we can assume that
4140 // interposition won't happen, in any case where the linker might insert a
4141 // stub to allow for interposition, we must generate code as though
4142 // interposition might occur. To understand why this matters, consider a
4143 // situation where: a -> b -> c where the arrows indicate calls. b and c are
4144 // in the same section, but a is in a different module (i.e. has a different
4145 // TOC base pointer). If the linker allows for interposition between b and c,
4146 // then it will generate a stub for the call edge between b and c which will
4147 // save the TOC pointer into the designated stack slot allocated by b. If we
4148 // return true here, and therefore allow a tail call between b and c, that
4149 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4150 // pointer into the stack slot allocated by a (where the a -> b stub saved
4151 // a's TOC base pointer). If we're not considering a tail call, but rather,
4152 // whether a nop is needed after the call instruction in b, because the linker
4153 // will insert a stub, it might complain about a missing nop if we omit it
4154 // (although many don't complain in this case).
4155 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4162 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4163 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4164 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4166 const unsigned PtrByteSize = 8;
4167 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4169 static const MCPhysReg GPR[] = {
4170 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4171 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4173 static const MCPhysReg VR[] = {
4174 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4175 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4178 const unsigned NumGPRs = array_lengthof(GPR);
4179 const unsigned NumFPRs = 13;
4180 const unsigned NumVRs = array_lengthof(VR);
4181 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4183 unsigned NumBytes = LinkageSize;
4184 unsigned AvailableFPRs = NumFPRs;
4185 unsigned AvailableVRs = NumVRs;
4187 for (const ISD::OutputArg& Param : Outs) {
4188 if (Param.Flags.isNest()) continue;
4190 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4191 PtrByteSize, LinkageSize, ParamAreaSize,
4192 NumBytes, AvailableFPRs, AvailableVRs,
4193 Subtarget.hasQPX()))
4200 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4201 if (CS->arg_size() != CallerFn->arg_size())
4204 ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4205 ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4206 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4208 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4209 const Value* CalleeArg = *CalleeArgIter;
4210 const Value* CallerArg = &(*CallerArgIter);
4211 if (CalleeArg == CallerArg)
4214 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4215 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4217 // 1st argument of callee is undef and has the same type as caller.
4218 if (CalleeArg->getType() == CallerArg->getType() &&
4219 isa<UndefValue>(CalleeArg))
4229 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4231 CallingConv::ID CalleeCC,
4232 ImmutableCallSite *CS,
4234 const SmallVectorImpl<ISD::OutputArg> &Outs,
4235 const SmallVectorImpl<ISD::InputArg> &Ins,
4236 SelectionDAG& DAG) const {
4237 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4239 if (DisableSCO && !TailCallOpt) return false;
4241 // Variadic argument functions are not supported.
4242 if (isVarArg) return false;
4244 MachineFunction &MF = DAG.getMachineFunction();
4245 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4247 // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4248 // the same calling convention
4249 if (CallerCC != CalleeCC) return false;
4251 // SCO support C calling convention
4252 if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4255 // Caller contains any byval parameter is not supported.
4256 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4259 // Callee contains any byval parameter is not supported, too.
4260 // Note: This is a quick work around, because in some cases, e.g.
4261 // caller's stack size > callee's stack size, we are still able to apply
4262 // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4263 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4266 // No TCO/SCO on indirect call because Caller have to restore its TOC
4267 if (!isFunctionGlobalAddress(Callee) &&
4268 !isa<ExternalSymbolSDNode>(Callee))
4271 // Check if Callee resides in the same section, because for now, PPC64 SVR4
4272 // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4274 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4275 if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine()))
4278 // TCO allows altering callee ABI, so we don't have to check further.
4279 if (CalleeCC == CallingConv::Fast && TailCallOpt)
4282 if (DisableSCO) return false;
4284 // If callee use the same argument list that caller is using, then we can
4285 // apply SCO on this case. If it is not, then we need to check if callee needs
4286 // stack for passing arguments.
4287 if (!hasSameArgumentList(MF.getFunction(), CS) &&
4288 needStackSlotPassParameters(Subtarget, Outs)) {
4295 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4296 /// for tail call optimization. Targets which want to do tail call
4297 /// optimization should implement this function.
4299 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4300 CallingConv::ID CalleeCC,
4302 const SmallVectorImpl<ISD::InputArg> &Ins,
4303 SelectionDAG& DAG) const {
4304 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4307 // Variable argument functions are not supported.
4311 MachineFunction &MF = DAG.getMachineFunction();
4312 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4313 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4314 // Functions containing by val parameters are not supported.
4315 for (unsigned i = 0; i != Ins.size(); i++) {
4316 ISD::ArgFlagsTy Flags = Ins[i].Flags;
4317 if (Flags.isByVal()) return false;
4320 // Non-PIC/GOT tail calls are supported.
4321 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4324 // At the moment we can only do local tail calls (in same module, hidden
4325 // or protected) if we are generating PIC.
4326 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4327 return G->getGlobal()->hasHiddenVisibility()
4328 || G->getGlobal()->hasProtectedVisibility();
4334 /// isCallCompatibleAddress - Return the immediate to use if the specified
4335 /// 32-bit value is representable in the immediate field of a BxA instruction.
4336 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4337 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4338 if (!C) return nullptr;
4340 int Addr = C->getZExtValue();
4341 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
4342 SignExtend32<26>(Addr) != Addr)
4343 return nullptr; // Top 6 bits have to be sext of immediate.
4347 (int)C->getZExtValue() >> 2, SDLoc(Op),
4348 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4354 struct TailCallArgumentInfo {
4359 TailCallArgumentInfo() = default;
4362 } // end anonymous namespace
4364 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4365 static void StoreTailCallArgumentsToStackSlot(
4366 SelectionDAG &DAG, SDValue Chain,
4367 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4368 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4369 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4370 SDValue Arg = TailCallArgs[i].Arg;
4371 SDValue FIN = TailCallArgs[i].FrameIdxOp;
4372 int FI = TailCallArgs[i].FrameIdx;
4373 // Store relative to framepointer.
4374 MemOpChains.push_back(DAG.getStore(
4375 Chain, dl, Arg, FIN,
4376 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4380 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4381 /// the appropriate stack slot for the tail call optimized function call.
4382 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4383 SDValue OldRetAddr, SDValue OldFP,
4384 int SPDiff, const SDLoc &dl) {
4386 // Calculate the new stack slot for the return address.
4387 MachineFunction &MF = DAG.getMachineFunction();
4388 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4389 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4390 bool isPPC64 = Subtarget.isPPC64();
4391 int SlotSize = isPPC64 ? 8 : 4;
4392 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4393 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4394 NewRetAddrLoc, true);
4395 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4396 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4397 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4398 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4400 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4401 // slot as the FP is never overwritten.
4402 if (Subtarget.isDarwinABI()) {
4403 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4404 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4406 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4407 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4408 MachinePointerInfo::getFixedStack(
4409 DAG.getMachineFunction(), NewFPIdx));
4415 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4416 /// the position of the argument.
4418 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4419 SDValue Arg, int SPDiff, unsigned ArgOffset,
4420 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4421 int Offset = ArgOffset + SPDiff;
4422 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4423 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4424 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4425 SDValue FIN = DAG.getFrameIndex(FI, VT);
4426 TailCallArgumentInfo Info;
4428 Info.FrameIdxOp = FIN;
4430 TailCallArguments.push_back(Info);
4433 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4434 /// stack slot. Returns the chain as result and the loaded frame pointers in
4435 /// LROpOut/FPOpout. Used when tail calling.
4436 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4437 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4438 SDValue &FPOpOut, const SDLoc &dl) const {
4440 // Load the LR and FP stack slot for later adjusting.
4441 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4442 LROpOut = getReturnAddrFrameIndex(DAG);
4443 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4444 Chain = SDValue(LROpOut.getNode(), 1);
4446 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4447 // slot as the FP is never overwritten.
4448 if (Subtarget.isDarwinABI()) {
4449 FPOpOut = getFramePointerFrameIndex(DAG);
4450 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4451 Chain = SDValue(FPOpOut.getNode(), 1);
4457 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4458 /// by "Src" to address "Dst" of size "Size". Alignment information is
4459 /// specified by the specific parameter attribute. The copy will be passed as
4460 /// a byval function parameter.
4461 /// Sometimes what we are copying is the end of a larger object, the part that
4462 /// does not fit in registers.
4463 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4464 SDValue Chain, ISD::ArgFlagsTy Flags,
4465 SelectionDAG &DAG, const SDLoc &dl) {
4466 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4467 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4468 false, false, false, MachinePointerInfo(),
4469 MachinePointerInfo());
4472 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4474 static void LowerMemOpCallTo(
4475 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4476 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4477 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4478 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4479 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4484 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4486 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4487 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4488 DAG.getConstant(ArgOffset, dl, PtrVT));
4490 MemOpChains.push_back(
4491 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4492 // Calculate and remember argument location.
4493 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4498 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4499 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4501 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4502 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4503 // might overwrite each other in case of tail call optimization.
4504 SmallVector<SDValue, 8> MemOpChains2;
4505 // Do not flag preceding copytoreg stuff together with the following stuff.
4507 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4509 if (!MemOpChains2.empty())
4510 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4512 // Store the return address to the appropriate stack slot.
4513 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4515 // Emit callseq_end just before tailcall node.
4516 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4517 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4518 InFlag = Chain.getValue(1);
4521 // Is this global address that of a function that can be called by name? (as
4522 // opposed to something that must hold a descriptor for an indirect call).
4523 static bool isFunctionGlobalAddress(SDValue Callee) {
4524 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4525 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4526 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4529 return G->getGlobal()->getValueType()->isFunctionTy();
4536 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4537 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4538 bool isPatchPoint, bool hasNest,
4539 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4540 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4541 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4542 bool isPPC64 = Subtarget.isPPC64();
4543 bool isSVR4ABI = Subtarget.isSVR4ABI();
4544 bool isELFv2ABI = Subtarget.isELFv2ABI();
4546 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4547 NodeTys.push_back(MVT::Other); // Returns a chain
4548 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
4550 unsigned CallOpc = PPCISD::CALL;
4552 bool needIndirectCall = true;
4553 if (!isSVR4ABI || !isPPC64)
4554 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4555 // If this is an absolute destination address, use the munged value.
4556 Callee = SDValue(Dest, 0);
4557 needIndirectCall = false;
4560 // PC-relative references to external symbols should go through $stub, unless
4561 // we're building with the leopard linker or later, which automatically
4562 // synthesizes these stubs.
4563 const TargetMachine &TM = DAG.getTarget();
4564 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4565 const GlobalValue *GV = nullptr;
4566 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4567 GV = G->getGlobal();
4568 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4569 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4571 if (isFunctionGlobalAddress(Callee)) {
4572 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4573 // A call to a TLS address is actually an indirect call to a
4574 // thread-specific pointer.
4575 unsigned OpFlags = 0;
4577 OpFlags = PPCII::MO_PLT;
4579 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4580 // every direct call is) turn it into a TargetGlobalAddress /
4581 // TargetExternalSymbol node so that legalize doesn't hack it.
4582 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4583 Callee.getValueType(), 0, OpFlags);
4584 needIndirectCall = false;
4587 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4588 unsigned char OpFlags = 0;
4591 OpFlags = PPCII::MO_PLT;
4593 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4595 needIndirectCall = false;
4599 // We'll form an invalid direct call when lowering a patchpoint; the full
4600 // sequence for an indirect call is complicated, and many of the
4601 // instructions introduced might have side effects (and, thus, can't be
4602 // removed later). The call itself will be removed as soon as the
4603 // argument/return lowering is complete, so the fact that it has the wrong
4604 // kind of operands should not really matter.
4605 needIndirectCall = false;
4608 if (needIndirectCall) {
4609 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
4610 // to do the call, we can't use PPCISD::CALL.
4611 SDValue MTCTROps[] = {Chain, Callee, InFlag};
4613 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4614 // Function pointers in the 64-bit SVR4 ABI do not point to the function
4615 // entry point, but to the function descriptor (the function entry point
4616 // address is part of the function descriptor though).
4617 // The function descriptor is a three doubleword structure with the
4618 // following fields: function entry point, TOC base address and
4619 // environment pointer.
4620 // Thus for a call through a function pointer, the following actions need
4622 // 1. Save the TOC of the caller in the TOC save area of its stack
4623 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4624 // 2. Load the address of the function entry point from the function
4626 // 3. Load the TOC of the callee from the function descriptor into r2.
4627 // 4. Load the environment pointer from the function descriptor into
4629 // 5. Branch to the function entry point address.
4630 // 6. On return of the callee, the TOC of the caller needs to be
4631 // restored (this is done in FinishCall()).
4633 // The loads are scheduled at the beginning of the call sequence, and the
4634 // register copies are flagged together to ensure that no other
4635 // operations can be scheduled in between. E.g. without flagging the
4636 // copies together, a TOC access in the caller could be scheduled between
4637 // the assignment of the callee TOC and the branch to the callee, which
4638 // results in the TOC access going through the TOC of the callee instead
4639 // of going through the TOC of the caller, which leads to incorrect code.
4641 // Load the address of the function entry point from the function
4643 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4644 if (LDChain.getValueType() == MVT::Glue)
4645 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4647 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4648 ? (MachineMemOperand::MODereferenceable |
4649 MachineMemOperand::MOInvariant)
4650 : MachineMemOperand::MONone;
4652 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4653 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4654 /* Alignment = */ 8, MMOFlags);
4656 // Load environment pointer into r11.
4657 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4658 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4659 SDValue LoadEnvPtr =
4660 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4661 /* Alignment = */ 8, MMOFlags);
4663 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4664 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4666 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4667 /* Alignment = */ 8, MMOFlags);
4669 setUsesTOCBasePtr(DAG);
4670 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4672 Chain = TOCVal.getValue(0);
4673 InFlag = TOCVal.getValue(1);
4675 // If the function call has an explicit 'nest' parameter, it takes the
4676 // place of the environment pointer.
4678 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4681 Chain = EnvVal.getValue(0);
4682 InFlag = EnvVal.getValue(1);
4685 MTCTROps[0] = Chain;
4686 MTCTROps[1] = LoadFuncPtr;
4687 MTCTROps[2] = InFlag;
4690 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4691 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4692 InFlag = Chain.getValue(1);
4695 NodeTys.push_back(MVT::Other);
4696 NodeTys.push_back(MVT::Glue);
4697 Ops.push_back(Chain);
4698 CallOpc = PPCISD::BCTRL;
4699 Callee.setNode(nullptr);
4700 // Add use of X11 (holding environment pointer)
4701 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4702 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4703 // Add CTR register as callee so a bctr can be emitted later.
4705 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4708 // If this is a direct call, pass the chain and the callee.
4709 if (Callee.getNode()) {
4710 Ops.push_back(Chain);
4711 Ops.push_back(Callee);
4713 // If this is a tail call add stack pointer delta.
4715 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4717 // Add argument registers to the end of the list so that they are known live
4719 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4720 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4721 RegsToPass[i].second.getValueType()));
4723 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4725 if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4726 setUsesTOCBasePtr(DAG);
4727 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4733 SDValue PPCTargetLowering::LowerCallResult(
4734 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4735 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4736 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4737 SmallVector<CCValAssign, 16> RVLocs;
4738 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4740 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4742 // Copy all of the result registers out of their specified physreg.
4743 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4744 CCValAssign &VA = RVLocs[i];
4745 assert(VA.isRegLoc() && "Can only return in registers!");
4747 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4748 VA.getLocReg(), VA.getLocVT(), InFlag);
4749 Chain = Val.getValue(1);
4750 InFlag = Val.getValue(2);
4752 switch (VA.getLocInfo()) {
4753 default: llvm_unreachable("Unknown loc info!");
4754 case CCValAssign::Full: break;
4755 case CCValAssign::AExt:
4756 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4758 case CCValAssign::ZExt:
4759 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4760 DAG.getValueType(VA.getValVT()));
4761 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4763 case CCValAssign::SExt:
4764 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4765 DAG.getValueType(VA.getValVT()));
4766 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4770 InVals.push_back(Val);
4776 SDValue PPCTargetLowering::FinishCall(
4777 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4778 bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4779 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4780 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4781 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4782 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4783 std::vector<EVT> NodeTys;
4784 SmallVector<SDValue, 8> Ops;
4785 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4786 SPDiff, isTailCall, isPatchPoint, hasNest,
4787 RegsToPass, Ops, NodeTys, CS, Subtarget);
4789 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4790 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4791 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4793 // When performing tail call optimization the callee pops its arguments off
4794 // the stack. Account for this here so these bytes can be pushed back on in
4795 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4796 int BytesCalleePops =
4797 (CallConv == CallingConv::Fast &&
4798 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4800 // Add a register mask operand representing the call-preserved registers.
4801 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4802 const uint32_t *Mask =
4803 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4804 assert(Mask && "Missing call preserved mask for calling convention");
4805 Ops.push_back(DAG.getRegisterMask(Mask));
4807 if (InFlag.getNode())
4808 Ops.push_back(InFlag);
4812 assert(((Callee.getOpcode() == ISD::Register &&
4813 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4814 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4815 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4816 isa<ConstantSDNode>(Callee)) &&
4817 "Expecting an global address, external symbol, absolute value or register");
4819 DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4820 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4823 // Add a NOP immediately after the branch instruction when using the 64-bit
4824 // SVR4 ABI. At link time, if caller and callee are in a different module and
4825 // thus have a different TOC, the call will be replaced with a call to a stub
4826 // function which saves the current TOC, loads the TOC of the callee and
4827 // branches to the callee. The NOP will be replaced with a load instruction
4828 // which restores the TOC of the caller from the TOC save slot of the current
4829 // stack frame. If caller and callee belong to the same module (and have the
4830 // same TOC), the NOP will remain unchanged.
4832 MachineFunction &MF = DAG.getMachineFunction();
4833 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4835 if (CallOpc == PPCISD::BCTRL) {
4836 // This is a call through a function pointer.
4837 // Restore the caller TOC from the save area into R2.
4838 // See PrepareCall() for more information about calls through function
4839 // pointers in the 64-bit SVR4 ABI.
4840 // We are using a target-specific load with r2 hard coded, because the
4841 // result of a target-independent load would never go directly into r2,
4842 // since r2 is a reserved register (which prevents the register allocator
4843 // from allocating it), resulting in an additional register being
4844 // allocated and an unnecessary move instruction being generated.
4845 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4847 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4848 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4849 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4850 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4851 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4853 // The address needs to go after the chain input but before the flag (or
4854 // any other variadic arguments).
4855 Ops.insert(std::next(Ops.begin()), AddTOC);
4856 } else if (CallOpc == PPCISD::CALL &&
4857 !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) {
4858 // Otherwise insert NOP for non-local calls.
4859 CallOpc = PPCISD::CALL_NOP;
4863 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4864 InFlag = Chain.getValue(1);
4866 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4867 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4870 InFlag = Chain.getValue(1);
4872 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4873 Ins, dl, DAG, InVals);
4877 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4878 SmallVectorImpl<SDValue> &InVals) const {
4879 SelectionDAG &DAG = CLI.DAG;
4881 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4882 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4883 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4884 SDValue Chain = CLI.Chain;
4885 SDValue Callee = CLI.Callee;
4886 bool &isTailCall = CLI.IsTailCall;
4887 CallingConv::ID CallConv = CLI.CallConv;
4888 bool isVarArg = CLI.IsVarArg;
4889 bool isPatchPoint = CLI.IsPatchPoint;
4890 ImmutableCallSite *CS = CLI.CS;
4893 if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4895 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4897 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4898 isVarArg, Outs, Ins, DAG);
4900 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4904 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4907 assert(isa<GlobalAddressSDNode>(Callee) &&
4908 "Callee should be an llvm::Function object.");
4910 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4911 const unsigned Width = 80 - strlen("TCO caller: ")
4912 - strlen(", callee linkage: 0, 0");
4913 dbgs() << "TCO caller: "
4914 << left_justify(DAG.getMachineFunction().getName(), Width)
4915 << ", callee linkage: "
4916 << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4921 if (!isTailCall && CS && CS->isMustTailCall())
4922 report_fatal_error("failed to perform tail call elimination on a call "
4923 "site marked musttail");
4925 // When long calls (i.e. indirect calls) are always used, calls are always
4926 // made via function pointer. If we have a function name, first translate it
4928 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4930 Callee = LowerGlobalAddress(Callee, DAG);
4932 if (Subtarget.isSVR4ABI()) {
4933 if (Subtarget.isPPC64())
4934 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4935 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4936 dl, DAG, InVals, CS);
4938 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4939 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4940 dl, DAG, InVals, CS);
4943 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4944 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4945 dl, DAG, InVals, CS);
4948 SDValue PPCTargetLowering::LowerCall_32SVR4(
4949 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4950 bool isTailCall, bool isPatchPoint,
4951 const SmallVectorImpl<ISD::OutputArg> &Outs,
4952 const SmallVectorImpl<SDValue> &OutVals,
4953 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4954 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4955 ImmutableCallSite *CS) const {
4956 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4957 // of the 32-bit SVR4 ABI stack frame layout.
4959 assert((CallConv == CallingConv::C ||
4960 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4962 unsigned PtrByteSize = 4;
4964 MachineFunction &MF = DAG.getMachineFunction();
4966 // Mark this function as potentially containing a function that contains a
4967 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4968 // and restoring the callers stack pointer in this functions epilog. This is
4969 // done because by tail calling the called function might overwrite the value
4970 // in this function's (MF) stack pointer stack slot 0(SP).
4971 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4972 CallConv == CallingConv::Fast)
4973 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4975 // Count how many bytes are to be pushed on the stack, including the linkage
4976 // area, parameter list area and the part of the local variable space which
4977 // contains copies of aggregates which are passed by value.
4979 // Assign locations to all of the outgoing arguments.
4980 SmallVector<CCValAssign, 16> ArgLocs;
4981 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4983 // Reserve space for the linkage area on the stack.
4984 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4987 CCInfo.PreAnalyzeCallOperands(Outs);
4990 // Handle fixed and variable vector arguments differently.
4991 // Fixed vector arguments go into registers as long as registers are
4992 // available. Variable vector arguments always go into memory.
4993 unsigned NumArgs = Outs.size();
4995 for (unsigned i = 0; i != NumArgs; ++i) {
4996 MVT ArgVT = Outs[i].VT;
4997 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5000 if (Outs[i].IsFixed) {
5001 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5004 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5010 errs() << "Call operand #" << i << " has unhandled type "
5011 << EVT(ArgVT).getEVTString() << "\n";
5013 llvm_unreachable(nullptr);
5017 // All arguments are treated the same.
5018 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5020 CCInfo.clearWasPPCF128();
5022 // Assign locations to all of the outgoing aggregate by value arguments.
5023 SmallVector<CCValAssign, 16> ByValArgLocs;
5024 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5026 // Reserve stack space for the allocations in CCInfo.
5027 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5029 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5031 // Size of the linkage area, parameter list area and the part of the local
5032 // space variable where copies of aggregates which are passed by value are
5034 unsigned NumBytes = CCByValInfo.getNextStackOffset();
5036 // Calculate by how many bytes the stack has to be adjusted in case of tail
5037 // call optimization.
5038 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5040 // Adjust the stack pointer for the new arguments...
5041 // These operations are automatically eliminated by the prolog/epilog pass
5042 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5043 SDValue CallSeqStart = Chain;
5045 // Load the return address and frame pointer so it can be moved somewhere else
5048 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5050 // Set up a copy of the stack pointer for use loading and storing any
5051 // arguments that may not fit in the registers available for argument
5053 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5055 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5056 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5057 SmallVector<SDValue, 8> MemOpChains;
5059 bool seenFloatArg = false;
5060 // Walk the register/memloc assignments, inserting copies/loads.
5061 for (unsigned i = 0, j = 0, e = ArgLocs.size();
5064 CCValAssign &VA = ArgLocs[i];
5065 SDValue Arg = OutVals[i];
5066 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5068 if (Flags.isByVal()) {
5069 // Argument is an aggregate which is passed by value, thus we need to
5070 // create a copy of it in the local variable space of the current stack
5071 // frame (which is the stack frame of the caller) and pass the address of
5072 // this copy to the callee.
5073 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5074 CCValAssign &ByValVA = ByValArgLocs[j++];
5075 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5077 // Memory reserved in the local variable space of the callers stack frame.
5078 unsigned LocMemOffset = ByValVA.getLocMemOffset();
5080 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5081 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5084 // Create a copy of the argument in the local area of the current
5086 SDValue MemcpyCall =
5087 CreateCopyOfByValArgument(Arg, PtrOff,
5088 CallSeqStart.getNode()->getOperand(0),
5091 // This must go outside the CALLSEQ_START..END.
5092 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5094 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5095 NewCallSeqStart.getNode());
5096 Chain = CallSeqStart = NewCallSeqStart;
5098 // Pass the address of the aggregate copy on the stack either in a
5099 // physical register or in the parameter list area of the current stack
5100 // frame to the callee.
5104 if (VA.isRegLoc()) {
5105 if (Arg.getValueType() == MVT::i1)
5106 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5108 seenFloatArg |= VA.getLocVT().isFloatingPoint();
5109 // Put argument in a physical register.
5110 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5112 // Put argument in the parameter list area of the current stack frame.
5113 assert(VA.isMemLoc());
5114 unsigned LocMemOffset = VA.getLocMemOffset();
5117 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5118 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5121 MemOpChains.push_back(
5122 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5124 // Calculate and remember argument location.
5125 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5131 if (!MemOpChains.empty())
5132 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5134 // Build a sequence of copy-to-reg nodes chained together with token chain
5135 // and flag operands which copy the outgoing args into the appropriate regs.
5137 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5138 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5139 RegsToPass[i].second, InFlag);
5140 InFlag = Chain.getValue(1);
5143 // Set CR bit 6 to true if this is a vararg call with floating args passed in
5146 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5147 SDValue Ops[] = { Chain, InFlag };
5149 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5150 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5152 InFlag = Chain.getValue(1);
5156 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5159 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5160 /* unused except on PPC64 ELFv1 */ false, DAG,
5161 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5162 NumBytes, Ins, InVals, CS);
5165 // Copy an argument into memory, being careful to do this outside the
5166 // call sequence for the call to which the argument belongs.
5167 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5168 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5169 SelectionDAG &DAG, const SDLoc &dl) const {
5170 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5171 CallSeqStart.getNode()->getOperand(0),
5173 // The MEMCPY must go outside the CALLSEQ_START..END.
5174 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5175 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5177 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5178 NewCallSeqStart.getNode());
5179 return NewCallSeqStart;
5182 SDValue PPCTargetLowering::LowerCall_64SVR4(
5183 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5184 bool isTailCall, bool isPatchPoint,
5185 const SmallVectorImpl<ISD::OutputArg> &Outs,
5186 const SmallVectorImpl<SDValue> &OutVals,
5187 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5188 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5189 ImmutableCallSite *CS) const {
5190 bool isELFv2ABI = Subtarget.isELFv2ABI();
5191 bool isLittleEndian = Subtarget.isLittleEndian();
5192 unsigned NumOps = Outs.size();
5193 bool hasNest = false;
5194 bool IsSibCall = false;
5196 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5197 unsigned PtrByteSize = 8;
5199 MachineFunction &MF = DAG.getMachineFunction();
5201 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5204 // Mark this function as potentially containing a function that contains a
5205 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5206 // and restoring the callers stack pointer in this functions epilog. This is
5207 // done because by tail calling the called function might overwrite the value
5208 // in this function's (MF) stack pointer stack slot 0(SP).
5209 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5210 CallConv == CallingConv::Fast)
5211 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5213 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5214 "fastcc not supported on varargs functions");
5216 // Count how many bytes are to be pushed on the stack, including the linkage
5217 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
5218 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5219 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5220 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5221 unsigned NumBytes = LinkageSize;
5222 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5223 unsigned &QFPR_idx = FPR_idx;
5225 static const MCPhysReg GPR[] = {
5226 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5227 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5229 static const MCPhysReg VR[] = {
5230 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5231 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5234 const unsigned NumGPRs = array_lengthof(GPR);
5235 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5236 const unsigned NumVRs = array_lengthof(VR);
5237 const unsigned NumQFPRs = NumFPRs;
5239 // On ELFv2, we can avoid allocating the parameter area if all the arguments
5240 // can be passed to the callee in registers.
5241 // For the fast calling convention, there is another check below.
5242 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5243 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5244 if (!HasParameterArea) {
5245 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5246 unsigned AvailableFPRs = NumFPRs;
5247 unsigned AvailableVRs = NumVRs;
5248 unsigned NumBytesTmp = NumBytes;
5249 for (unsigned i = 0; i != NumOps; ++i) {
5250 if (Outs[i].Flags.isNest()) continue;
5251 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5252 PtrByteSize, LinkageSize, ParamAreaSize,
5253 NumBytesTmp, AvailableFPRs, AvailableVRs,
5254 Subtarget.hasQPX()))
5255 HasParameterArea = true;
5259 // When using the fast calling convention, we don't provide backing for
5260 // arguments that will be in registers.
5261 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5263 // Add up all the space actually used.
5264 for (unsigned i = 0; i != NumOps; ++i) {
5265 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5266 EVT ArgVT = Outs[i].VT;
5267 EVT OrigVT = Outs[i].ArgVT;
5272 if (CallConv == CallingConv::Fast) {
5273 if (Flags.isByVal())
5274 NumGPRsUsed += (Flags.getByValSize()+7)/8;
5276 switch (ArgVT.getSimpleVT().SimpleTy) {
5277 default: llvm_unreachable("Unexpected ValueType for argument!");
5281 if (++NumGPRsUsed <= NumGPRs)
5290 if (++NumVRsUsed <= NumVRs)
5294 // When using QPX, this is handled like a FP register, otherwise, it
5295 // is an Altivec register.
5296 if (Subtarget.hasQPX()) {
5297 if (++NumFPRsUsed <= NumFPRs)
5300 if (++NumVRsUsed <= NumVRs)
5306 case MVT::v4f64: // QPX
5307 case MVT::v4i1: // QPX
5308 if (++NumFPRsUsed <= NumFPRs)
5314 /* Respect alignment of argument on the stack. */
5316 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5317 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5319 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5320 if (Flags.isInConsecutiveRegsLast())
5321 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5324 unsigned NumBytesActuallyUsed = NumBytes;
5326 // In the old ELFv1 ABI,
5327 // the prolog code of the callee may store up to 8 GPR argument registers to
5328 // the stack, allowing va_start to index over them in memory if its varargs.
5329 // Because we cannot tell if this is needed on the caller side, we have to
5330 // conservatively assume that it is needed. As such, make sure we have at
5331 // least enough stack space for the caller to store the 8 GPRs.
5332 // In the ELFv2 ABI, we allocate the parameter area iff a callee
5333 // really requires memory operands, e.g. a vararg function.
5334 if (HasParameterArea)
5335 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5337 NumBytes = LinkageSize;
5339 // Tail call needs the stack to be aligned.
5340 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5341 CallConv == CallingConv::Fast)
5342 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5346 // Calculate by how many bytes the stack has to be adjusted in case of tail
5347 // call optimization.
5349 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5351 // To protect arguments on the stack from being clobbered in a tail call,
5352 // force all the loads to happen before doing any other lowering.
5354 Chain = DAG.getStackArgumentTokenFactor(Chain);
5356 // Adjust the stack pointer for the new arguments...
5357 // These operations are automatically eliminated by the prolog/epilog pass
5359 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5360 SDValue CallSeqStart = Chain;
5362 // Load the return address and frame pointer so it can be move somewhere else
5365 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5367 // Set up a copy of the stack pointer for use loading and storing any
5368 // arguments that may not fit in the registers available for argument
5370 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5372 // Figure out which arguments are going to go in registers, and which in
5373 // memory. Also, if this is a vararg function, floating point operations
5374 // must be stored to our stack, and loaded into integer regs as well, if
5375 // any integer regs are available for argument passing.
5376 unsigned ArgOffset = LinkageSize;
5378 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5379 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5381 SmallVector<SDValue, 8> MemOpChains;
5382 for (unsigned i = 0; i != NumOps; ++i) {
5383 SDValue Arg = OutVals[i];
5384 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5385 EVT ArgVT = Outs[i].VT;
5386 EVT OrigVT = Outs[i].ArgVT;
5388 // PtrOff will be used to store the current argument to the stack if a
5389 // register cannot be found for it.
5392 // We re-align the argument offset for each argument, except when using the
5393 // fast calling convention, when we need to make sure we do that only when
5394 // we'll actually use a stack slot.
5395 auto ComputePtrOff = [&]() {
5396 /* Respect alignment of argument on the stack. */
5398 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5399 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5401 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5403 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5406 if (CallConv != CallingConv::Fast) {
5409 /* Compute GPR index associated with argument offset. */
5410 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5411 GPR_idx = std::min(GPR_idx, NumGPRs);
5414 // Promote integers to 64-bit values.
5415 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5416 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5417 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5418 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5421 // FIXME memcpy is used way more than necessary. Correctness first.
5422 // Note: "by value" is code for passing a structure by value, not
5424 if (Flags.isByVal()) {
5425 // Note: Size includes alignment padding, so
5426 // struct x { short a; char b; }
5427 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
5428 // These are the proper values we need for right-justifying the
5429 // aggregate in a parameter register.
5430 unsigned Size = Flags.getByValSize();
5432 // An empty aggregate parameter takes up no storage and no
5437 if (CallConv == CallingConv::Fast)
5440 // All aggregates smaller than 8 bytes must be passed right-justified.
5441 if (Size==1 || Size==2 || Size==4) {
5442 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5443 if (GPR_idx != NumGPRs) {
5444 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5445 MachinePointerInfo(), VT);
5446 MemOpChains.push_back(Load.getValue(1));
5447 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5449 ArgOffset += PtrByteSize;
5454 if (GPR_idx == NumGPRs && Size < 8) {
5455 SDValue AddPtr = PtrOff;
5456 if (!isLittleEndian) {
5457 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5458 PtrOff.getValueType());
5459 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5461 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5464 ArgOffset += PtrByteSize;
5467 // Copy entire object into memory. There are cases where gcc-generated
5468 // code assumes it is there, even if it could be put entirely into
5469 // registers. (This is not what the doc says.)
5471 // FIXME: The above statement is likely due to a misunderstanding of the
5472 // documents. All arguments must be copied into the parameter area BY
5473 // THE CALLEE in the event that the callee takes the address of any
5474 // formal argument. That has not yet been implemented. However, it is
5475 // reasonable to use the stack area as a staging area for the register
5478 // Skip this for small aggregates, as we will use the same slot for a
5479 // right-justified copy, below.
5481 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5485 // When a register is available, pass a small aggregate right-justified.
5486 if (Size < 8 && GPR_idx != NumGPRs) {
5487 // The easiest way to get this right-justified in a register
5488 // is to copy the structure into the rightmost portion of a
5489 // local variable slot, then load the whole slot into the
5491 // FIXME: The memcpy seems to produce pretty awful code for
5492 // small aggregates, particularly for packed ones.
5493 // FIXME: It would be preferable to use the slot in the
5494 // parameter save area instead of a new local variable.
5495 SDValue AddPtr = PtrOff;
5496 if (!isLittleEndian) {
5497 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5498 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5500 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5504 // Load the slot into the register.
5506 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5507 MemOpChains.push_back(Load.getValue(1));
5508 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5510 // Done with this argument.
5511 ArgOffset += PtrByteSize;
5515 // For aggregates larger than PtrByteSize, copy the pieces of the
5516 // object that fit into registers from the parameter save area.
5517 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5518 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5519 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5520 if (GPR_idx != NumGPRs) {
5522 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5523 MemOpChains.push_back(Load.getValue(1));
5524 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5525 ArgOffset += PtrByteSize;
5527 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5534 switch (Arg.getSimpleValueType().SimpleTy) {
5535 default: llvm_unreachable("Unexpected ValueType for argument!");
5539 if (Flags.isNest()) {
5540 // The 'nest' parameter, if any, is passed in R11.
5541 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5546 // These can be scalar arguments or elements of an integer array type
5547 // passed directly. Clang may use those instead of "byval" aggregate
5548 // types to avoid forcing arguments to memory unnecessarily.
5549 if (GPR_idx != NumGPRs) {
5550 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5552 if (CallConv == CallingConv::Fast)
5555 assert(HasParameterArea &&
5556 "Parameter area must exist to pass an argument in memory.");
5557 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5558 true, isTailCall, false, MemOpChains,
5559 TailCallArguments, dl);
5560 if (CallConv == CallingConv::Fast)
5561 ArgOffset += PtrByteSize;
5563 if (CallConv != CallingConv::Fast)
5564 ArgOffset += PtrByteSize;
5568 // These can be scalar arguments or elements of a float array type
5569 // passed directly. The latter are used to implement ELFv2 homogenous
5570 // float aggregates.
5572 // Named arguments go into FPRs first, and once they overflow, the
5573 // remaining arguments go into GPRs and then the parameter save area.
5574 // Unnamed arguments for vararg functions always go to GPRs and
5575 // then the parameter save area. For now, put all arguments to vararg
5576 // routines always in both locations (FPR *and* GPR or stack slot).
5577 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5578 bool NeededLoad = false;
5580 // First load the argument into the next available FPR.
5581 if (FPR_idx != NumFPRs)
5582 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5584 // Next, load the argument into GPR or stack slot if needed.
5585 if (!NeedGPROrStack)
5587 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5588 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5589 // once we support fp <-> gpr moves.
5591 // In the non-vararg case, this can only ever happen in the
5592 // presence of f32 array types, since otherwise we never run
5593 // out of FPRs before running out of GPRs.
5596 // Double values are always passed in a single GPR.
5597 if (Arg.getValueType() != MVT::f32) {
5598 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5600 // Non-array float values are extended and passed in a GPR.
5601 } else if (!Flags.isInConsecutiveRegs()) {
5602 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5603 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5605 // If we have an array of floats, we collect every odd element
5606 // together with its predecessor into one GPR.
5607 } else if (ArgOffset % PtrByteSize != 0) {
5609 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5610 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5611 if (!isLittleEndian)
5613 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5615 // The final element, if even, goes into the first half of a GPR.
5616 } else if (Flags.isInConsecutiveRegsLast()) {
5617 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5618 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5619 if (!isLittleEndian)
5620 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5621 DAG.getConstant(32, dl, MVT::i32));
5623 // Non-final even elements are skipped; they will be handled
5624 // together the with subsequent argument on the next go-around.
5628 if (ArgVal.getNode())
5629 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5631 if (CallConv == CallingConv::Fast)
5634 // Single-precision floating-point values are mapped to the
5635 // second (rightmost) word of the stack doubleword.
5636 if (Arg.getValueType() == MVT::f32 &&
5637 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5638 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5639 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5642 assert(HasParameterArea &&
5643 "Parameter area must exist to pass an argument in memory.");
5644 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5645 true, isTailCall, false, MemOpChains,
5646 TailCallArguments, dl);
5650 // When passing an array of floats, the array occupies consecutive
5651 // space in the argument area; only round up to the next doubleword
5652 // at the end of the array. Otherwise, each float takes 8 bytes.
5653 if (CallConv != CallingConv::Fast || NeededLoad) {
5654 ArgOffset += (Arg.getValueType() == MVT::f32 &&
5655 Flags.isInConsecutiveRegs()) ? 4 : 8;
5656 if (Flags.isInConsecutiveRegsLast())
5657 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5668 if (!Subtarget.hasQPX()) {
5669 // These can be scalar arguments or elements of a vector array type
5670 // passed directly. The latter are used to implement ELFv2 homogenous
5671 // vector aggregates.
5673 // For a varargs call, named arguments go into VRs or on the stack as
5674 // usual; unnamed arguments always go to the stack or the corresponding
5675 // GPRs when within range. For now, we always put the value in both
5676 // locations (or even all three).
5678 assert(HasParameterArea &&
5679 "Parameter area must exist if we have a varargs call.");
5680 // We could elide this store in the case where the object fits
5681 // entirely in R registers. Maybe later.
5683 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5684 MemOpChains.push_back(Store);
5685 if (VR_idx != NumVRs) {
5687 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5688 MemOpChains.push_back(Load.getValue(1));
5689 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5692 for (unsigned i=0; i<16; i+=PtrByteSize) {
5693 if (GPR_idx == NumGPRs)
5695 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5696 DAG.getConstant(i, dl, PtrVT));
5698 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5699 MemOpChains.push_back(Load.getValue(1));
5700 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5705 // Non-varargs Altivec params go into VRs or on the stack.
5706 if (VR_idx != NumVRs) {
5707 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5709 if (CallConv == CallingConv::Fast)
5712 assert(HasParameterArea &&
5713 "Parameter area must exist to pass an argument in memory.");
5714 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5715 true, isTailCall, true, MemOpChains,
5716 TailCallArguments, dl);
5717 if (CallConv == CallingConv::Fast)
5721 if (CallConv != CallingConv::Fast)
5726 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5727 "Invalid QPX parameter type");
5732 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5734 assert(HasParameterArea &&
5735 "Parameter area must exist if we have a varargs call.");
5736 // We could elide this store in the case where the object fits
5737 // entirely in R registers. Maybe later.
5739 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5740 MemOpChains.push_back(Store);
5741 if (QFPR_idx != NumQFPRs) {
5742 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5743 PtrOff, MachinePointerInfo());
5744 MemOpChains.push_back(Load.getValue(1));
5745 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5747 ArgOffset += (IsF32 ? 16 : 32);
5748 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5749 if (GPR_idx == NumGPRs)
5751 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5752 DAG.getConstant(i, dl, PtrVT));
5754 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5755 MemOpChains.push_back(Load.getValue(1));
5756 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5761 // Non-varargs QPX params go into registers or on the stack.
5762 if (QFPR_idx != NumQFPRs) {
5763 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5765 if (CallConv == CallingConv::Fast)
5768 assert(HasParameterArea &&
5769 "Parameter area must exist to pass an argument in memory.");
5770 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5771 true, isTailCall, true, MemOpChains,
5772 TailCallArguments, dl);
5773 if (CallConv == CallingConv::Fast)
5774 ArgOffset += (IsF32 ? 16 : 32);
5777 if (CallConv != CallingConv::Fast)
5778 ArgOffset += (IsF32 ? 16 : 32);
5784 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5785 "mismatch in size of parameter area");
5786 (void)NumBytesActuallyUsed;
5788 if (!MemOpChains.empty())
5789 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5791 // Check if this is an indirect call (MTCTR/BCTRL).
5792 // See PrepareCall() for more information about calls through function
5793 // pointers in the 64-bit SVR4 ABI.
5794 if (!isTailCall && !isPatchPoint &&
5795 !isFunctionGlobalAddress(Callee) &&
5796 !isa<ExternalSymbolSDNode>(Callee)) {
5797 // Load r2 into a virtual register and store it to the TOC save area.
5798 setUsesTOCBasePtr(DAG);
5799 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5800 // TOC save area offset.
5801 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5802 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5803 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5804 Chain = DAG.getStore(
5805 Val.getValue(1), dl, Val, AddPtr,
5806 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5807 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5808 // This does not mean the MTCTR instruction must use R12; it's easier
5809 // to model this as an extra parameter, so do that.
5810 if (isELFv2ABI && !isPatchPoint)
5811 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5814 // Build a sequence of copy-to-reg nodes chained together with token chain
5815 // and flag operands which copy the outgoing args into the appropriate regs.
5817 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5818 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5819 RegsToPass[i].second, InFlag);
5820 InFlag = Chain.getValue(1);
5823 if (isTailCall && !IsSibCall)
5824 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5827 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5828 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5829 SPDiff, NumBytes, Ins, InVals, CS);
5832 SDValue PPCTargetLowering::LowerCall_Darwin(
5833 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5834 bool isTailCall, bool isPatchPoint,
5835 const SmallVectorImpl<ISD::OutputArg> &Outs,
5836 const SmallVectorImpl<SDValue> &OutVals,
5837 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5838 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5839 ImmutableCallSite *CS) const {
5840 unsigned NumOps = Outs.size();
5842 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5843 bool isPPC64 = PtrVT == MVT::i64;
5844 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5846 MachineFunction &MF = DAG.getMachineFunction();
5848 // Mark this function as potentially containing a function that contains a
5849 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5850 // and restoring the callers stack pointer in this functions epilog. This is
5851 // done because by tail calling the called function might overwrite the value
5852 // in this function's (MF) stack pointer stack slot 0(SP).
5853 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5854 CallConv == CallingConv::Fast)
5855 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5857 // Count how many bytes are to be pushed on the stack, including the linkage
5858 // area, and parameter passing area. We start with 24/48 bytes, which is
5859 // prereserved space for [SP][CR][LR][3 x unused].
5860 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5861 unsigned NumBytes = LinkageSize;
5863 // Add up all the space actually used.
5864 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5865 // they all go in registers, but we must reserve stack space for them for
5866 // possible use by the caller. In varargs or 64-bit calls, parameters are
5867 // assigned stack space in order, with padding so Altivec parameters are
5869 unsigned nAltivecParamsAtEnd = 0;
5870 for (unsigned i = 0; i != NumOps; ++i) {
5871 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5872 EVT ArgVT = Outs[i].VT;
5873 // Varargs Altivec parameters are padded to a 16 byte boundary.
5874 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5875 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5876 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5877 if (!isVarArg && !isPPC64) {
5878 // Non-varargs Altivec parameters go after all the non-Altivec
5879 // parameters; handle those later so we know how much padding we need.
5880 nAltivecParamsAtEnd++;
5883 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5884 NumBytes = ((NumBytes+15)/16)*16;
5886 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5889 // Allow for Altivec parameters at the end, if needed.
5890 if (nAltivecParamsAtEnd) {
5891 NumBytes = ((NumBytes+15)/16)*16;
5892 NumBytes += 16*nAltivecParamsAtEnd;
5895 // The prolog code of the callee may store up to 8 GPR argument registers to
5896 // the stack, allowing va_start to index over them in memory if its varargs.
5897 // Because we cannot tell if this is needed on the caller side, we have to
5898 // conservatively assume that it is needed. As such, make sure we have at
5899 // least enough stack space for the caller to store the 8 GPRs.
5900 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5902 // Tail call needs the stack to be aligned.
5903 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5904 CallConv == CallingConv::Fast)
5905 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5907 // Calculate by how many bytes the stack has to be adjusted in case of tail
5908 // call optimization.
5909 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5911 // To protect arguments on the stack from being clobbered in a tail call,
5912 // force all the loads to happen before doing any other lowering.
5914 Chain = DAG.getStackArgumentTokenFactor(Chain);
5916 // Adjust the stack pointer for the new arguments...
5917 // These operations are automatically eliminated by the prolog/epilog pass
5918 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5919 SDValue CallSeqStart = Chain;
5921 // Load the return address and frame pointer so it can be move somewhere else
5924 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5926 // Set up a copy of the stack pointer for use loading and storing any
5927 // arguments that may not fit in the registers available for argument
5931 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5933 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5935 // Figure out which arguments are going to go in registers, and which in
5936 // memory. Also, if this is a vararg function, floating point operations
5937 // must be stored to our stack, and loaded into integer regs as well, if
5938 // any integer regs are available for argument passing.
5939 unsigned ArgOffset = LinkageSize;
5940 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5942 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5943 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5944 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5946 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5947 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5948 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5950 static const MCPhysReg VR[] = {
5951 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5952 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5954 const unsigned NumGPRs = array_lengthof(GPR_32);
5955 const unsigned NumFPRs = 13;
5956 const unsigned NumVRs = array_lengthof(VR);
5958 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5960 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5961 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5963 SmallVector<SDValue, 8> MemOpChains;
5964 for (unsigned i = 0; i != NumOps; ++i) {
5965 SDValue Arg = OutVals[i];
5966 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5968 // PtrOff will be used to store the current argument to the stack if a
5969 // register cannot be found for it.
5972 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5974 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5976 // On PPC64, promote integers to 64-bit values.
5977 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5978 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5979 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5980 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5983 // FIXME memcpy is used way more than necessary. Correctness first.
5984 // Note: "by value" is code for passing a structure by value, not
5986 if (Flags.isByVal()) {
5987 unsigned Size = Flags.getByValSize();
5988 // Very small objects are passed right-justified. Everything else is
5989 // passed left-justified.
5990 if (Size==1 || Size==2) {
5991 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5992 if (GPR_idx != NumGPRs) {
5993 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5994 MachinePointerInfo(), VT);
5995 MemOpChains.push_back(Load.getValue(1));
5996 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5998 ArgOffset += PtrByteSize;
6000 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6001 PtrOff.getValueType());
6002 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6003 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6006 ArgOffset += PtrByteSize;
6010 // Copy entire object into memory. There are cases where gcc-generated
6011 // code assumes it is there, even if it could be put entirely into
6012 // registers. (This is not what the doc says.)
6013 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6017 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6018 // copy the pieces of the object that fit into registers from the
6019 // parameter save area.
6020 for (unsigned j=0; j<Size; j+=PtrByteSize) {
6021 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6022 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6023 if (GPR_idx != NumGPRs) {
6025 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6026 MemOpChains.push_back(Load.getValue(1));
6027 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6028 ArgOffset += PtrByteSize;
6030 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6037 switch (Arg.getSimpleValueType().SimpleTy) {
6038 default: llvm_unreachable("Unexpected ValueType for argument!");
6042 if (GPR_idx != NumGPRs) {
6043 if (Arg.getValueType() == MVT::i1)
6044 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6046 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6048 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6049 isPPC64, isTailCall, false, MemOpChains,
6050 TailCallArguments, dl);
6052 ArgOffset += PtrByteSize;
6056 if (FPR_idx != NumFPRs) {
6057 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6061 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6062 MemOpChains.push_back(Store);
6064 // Float varargs are always shadowed in available integer registers
6065 if (GPR_idx != NumGPRs) {
6067 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6068 MemOpChains.push_back(Load.getValue(1));
6069 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6071 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6072 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6073 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6075 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6076 MemOpChains.push_back(Load.getValue(1));
6077 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6080 // If we have any FPRs remaining, we may also have GPRs remaining.
6081 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6083 if (GPR_idx != NumGPRs)
6085 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6086 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
6090 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6091 isPPC64, isTailCall, false, MemOpChains,
6092 TailCallArguments, dl);
6096 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6103 // These go aligned on the stack, or in the corresponding R registers
6104 // when within range. The Darwin PPC ABI doc claims they also go in
6105 // V registers; in fact gcc does this only for arguments that are
6106 // prototyped, not for those that match the ... We do it for all
6107 // arguments, seems to work.
6108 while (ArgOffset % 16 !=0) {
6109 ArgOffset += PtrByteSize;
6110 if (GPR_idx != NumGPRs)
6113 // We could elide this store in the case where the object fits
6114 // entirely in R registers. Maybe later.
6115 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6116 DAG.getConstant(ArgOffset, dl, PtrVT));
6118 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6119 MemOpChains.push_back(Store);
6120 if (VR_idx != NumVRs) {
6122 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6123 MemOpChains.push_back(Load.getValue(1));
6124 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6127 for (unsigned i=0; i<16; i+=PtrByteSize) {
6128 if (GPR_idx == NumGPRs)
6130 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6131 DAG.getConstant(i, dl, PtrVT));
6133 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6134 MemOpChains.push_back(Load.getValue(1));
6135 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6140 // Non-varargs Altivec params generally go in registers, but have
6141 // stack space allocated at the end.
6142 if (VR_idx != NumVRs) {
6143 // Doesn't have GPR space allocated.
6144 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6145 } else if (nAltivecParamsAtEnd==0) {
6146 // We are emitting Altivec params in order.
6147 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6148 isPPC64, isTailCall, true, MemOpChains,
6149 TailCallArguments, dl);
6155 // If all Altivec parameters fit in registers, as they usually do,
6156 // they get stack space following the non-Altivec parameters. We
6157 // don't track this here because nobody below needs it.
6158 // If there are more Altivec parameters than fit in registers emit
6160 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6162 // Offset is aligned; skip 1st 12 params which go in V registers.
6163 ArgOffset = ((ArgOffset+15)/16)*16;
6165 for (unsigned i = 0; i != NumOps; ++i) {
6166 SDValue Arg = OutVals[i];
6167 EVT ArgType = Outs[i].VT;
6168 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6169 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6172 // We are emitting Altivec params in order.
6173 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6174 isPPC64, isTailCall, true, MemOpChains,
6175 TailCallArguments, dl);
6182 if (!MemOpChains.empty())
6183 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6185 // On Darwin, R12 must contain the address of an indirect callee. This does
6186 // not mean the MTCTR instruction must use R12; it's easier to model this as
6187 // an extra parameter, so do that.
6189 !isFunctionGlobalAddress(Callee) &&
6190 !isa<ExternalSymbolSDNode>(Callee) &&
6191 !isBLACompatibleAddress(Callee, DAG))
6192 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6193 PPC::R12), Callee));
6195 // Build a sequence of copy-to-reg nodes chained together with token chain
6196 // and flag operands which copy the outgoing args into the appropriate regs.
6198 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6199 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6200 RegsToPass[i].second, InFlag);
6201 InFlag = Chain.getValue(1);
6205 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6208 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6209 /* unused except on PPC64 ELFv1 */ false, DAG,
6210 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6211 NumBytes, Ins, InVals, CS);
6215 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6216 MachineFunction &MF, bool isVarArg,
6217 const SmallVectorImpl<ISD::OutputArg> &Outs,
6218 LLVMContext &Context) const {
6219 SmallVector<CCValAssign, 16> RVLocs;
6220 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6221 return CCInfo.CheckReturn(Outs, RetCC_PPC);
6225 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6227 const SmallVectorImpl<ISD::OutputArg> &Outs,
6228 const SmallVectorImpl<SDValue> &OutVals,
6229 const SDLoc &dl, SelectionDAG &DAG) const {
6230 SmallVector<CCValAssign, 16> RVLocs;
6231 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6233 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6236 SmallVector<SDValue, 4> RetOps(1, Chain);
6238 // Copy the result values into the output registers.
6239 for (unsigned i = 0; i != RVLocs.size(); ++i) {
6240 CCValAssign &VA = RVLocs[i];
6241 assert(VA.isRegLoc() && "Can only return in registers!");
6243 SDValue Arg = OutVals[i];
6245 switch (VA.getLocInfo()) {
6246 default: llvm_unreachable("Unknown loc info!");
6247 case CCValAssign::Full: break;
6248 case CCValAssign::AExt:
6249 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6251 case CCValAssign::ZExt:
6252 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6254 case CCValAssign::SExt:
6255 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6259 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6260 Flag = Chain.getValue(1);
6261 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6264 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6265 const MCPhysReg *I =
6266 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6270 if (PPC::G8RCRegClass.contains(*I))
6271 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6272 else if (PPC::F8RCRegClass.contains(*I))
6273 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6274 else if (PPC::CRRCRegClass.contains(*I))
6275 RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6276 else if (PPC::VRRCRegClass.contains(*I))
6277 RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6279 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6283 RetOps[0] = Chain; // Update chain.
6285 // Add the flag if we have it.
6287 RetOps.push_back(Flag);
6289 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6293 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6294 SelectionDAG &DAG) const {
6297 // Get the corect type for integers.
6298 EVT IntVT = Op.getValueType();
6301 SDValue Chain = Op.getOperand(0);
6302 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6303 // Build a DYNAREAOFFSET node.
6304 SDValue Ops[2] = {Chain, FPSIdx};
6305 SDVTList VTs = DAG.getVTList(IntVT);
6306 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6309 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6310 SelectionDAG &DAG) const {
6311 // When we pop the dynamic allocation we need to restore the SP link.
6314 // Get the corect type for pointers.
6315 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6317 // Construct the stack pointer operand.
6318 bool isPPC64 = Subtarget.isPPC64();
6319 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6320 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6322 // Get the operands for the STACKRESTORE.
6323 SDValue Chain = Op.getOperand(0);
6324 SDValue SaveSP = Op.getOperand(1);
6326 // Load the old link SP.
6327 SDValue LoadLinkSP =
6328 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6330 // Restore the stack pointer.
6331 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6333 // Store the old link SP.
6334 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6337 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6338 MachineFunction &MF = DAG.getMachineFunction();
6339 bool isPPC64 = Subtarget.isPPC64();
6340 EVT PtrVT = getPointerTy(MF.getDataLayout());
6342 // Get current frame pointer save index. The users of this index will be
6343 // primarily DYNALLOC instructions.
6344 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6345 int RASI = FI->getReturnAddrSaveIndex();
6347 // If the frame pointer save index hasn't been defined yet.
6349 // Find out what the fix offset of the frame pointer save area.
6350 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6351 // Allocate the frame index for frame pointer save area.
6352 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6354 FI->setReturnAddrSaveIndex(RASI);
6356 return DAG.getFrameIndex(RASI, PtrVT);
6360 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6361 MachineFunction &MF = DAG.getMachineFunction();
6362 bool isPPC64 = Subtarget.isPPC64();
6363 EVT PtrVT = getPointerTy(MF.getDataLayout());
6365 // Get current frame pointer save index. The users of this index will be
6366 // primarily DYNALLOC instructions.
6367 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6368 int FPSI = FI->getFramePointerSaveIndex();
6370 // If the frame pointer save index hasn't been defined yet.
6372 // Find out what the fix offset of the frame pointer save area.
6373 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6374 // Allocate the frame index for frame pointer save area.
6375 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6377 FI->setFramePointerSaveIndex(FPSI);
6379 return DAG.getFrameIndex(FPSI, PtrVT);
6382 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6383 SelectionDAG &DAG) const {
6385 SDValue Chain = Op.getOperand(0);
6386 SDValue Size = Op.getOperand(1);
6389 // Get the corect type for pointers.
6390 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6392 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6393 DAG.getConstant(0, dl, PtrVT), Size);
6394 // Construct a node for the frame pointer save index.
6395 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6396 // Build a DYNALLOC node.
6397 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6398 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6399 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6402 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6403 SelectionDAG &DAG) const {
6404 MachineFunction &MF = DAG.getMachineFunction();
6406 bool isPPC64 = Subtarget.isPPC64();
6407 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6409 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6410 return DAG.getFrameIndex(FI, PtrVT);
6413 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6414 SelectionDAG &DAG) const {
6416 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6417 DAG.getVTList(MVT::i32, MVT::Other),
6418 Op.getOperand(0), Op.getOperand(1));
6421 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6422 SelectionDAG &DAG) const {
6424 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6425 Op.getOperand(0), Op.getOperand(1));
6428 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6429 if (Op.getValueType().isVector())
6430 return LowerVectorLoad(Op, DAG);
6432 assert(Op.getValueType() == MVT::i1 &&
6433 "Custom lowering only for i1 loads");
6435 // First, load 8 bits into 32 bits, then truncate to 1 bit.
6438 LoadSDNode *LD = cast<LoadSDNode>(Op);
6440 SDValue Chain = LD->getChain();
6441 SDValue BasePtr = LD->getBasePtr();
6442 MachineMemOperand *MMO = LD->getMemOperand();
6445 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6446 BasePtr, MVT::i8, MMO);
6447 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6449 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6450 return DAG.getMergeValues(Ops, dl);
6453 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6454 if (Op.getOperand(1).getValueType().isVector())
6455 return LowerVectorStore(Op, DAG);
6457 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6458 "Custom lowering only for i1 stores");
6460 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6463 StoreSDNode *ST = cast<StoreSDNode>(Op);
6465 SDValue Chain = ST->getChain();
6466 SDValue BasePtr = ST->getBasePtr();
6467 SDValue Value = ST->getValue();
6468 MachineMemOperand *MMO = ST->getMemOperand();
6470 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6472 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6475 // FIXME: Remove this once the ANDI glue bug is fixed:
6476 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6477 assert(Op.getValueType() == MVT::i1 &&
6478 "Custom lowering only for i1 results");
6481 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6485 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6487 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6488 // Not FP? Not a fsel.
6489 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6490 !Op.getOperand(2).getValueType().isFloatingPoint())
6493 // We might be able to do better than this under some circumstances, but in
6494 // general, fsel-based lowering of select is a finite-math-only optimization.
6495 // For more information, see section F.3 of the 2.06 ISA specification.
6496 if (!DAG.getTarget().Options.NoInfsFPMath ||
6497 !DAG.getTarget().Options.NoNaNsFPMath)
6499 // TODO: Propagate flags from the select rather than global settings.
6501 Flags.setNoInfs(true);
6502 Flags.setNoNaNs(true);
6504 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6506 EVT ResVT = Op.getValueType();
6507 EVT CmpVT = Op.getOperand(0).getValueType();
6508 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6509 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
6512 // If the RHS of the comparison is a 0.0, we don't need to do the
6513 // subtraction at all.
6515 if (isFloatingPointZero(RHS))
6517 default: break; // SETUO etc aren't handled by fsel.
6521 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6522 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6523 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6524 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6525 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6526 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6527 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6530 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6533 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6534 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6535 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6538 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6541 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6542 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6543 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6544 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6549 default: break; // SETUO etc aren't handled by fsel.
6553 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6554 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6555 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6556 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6557 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6558 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6559 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6560 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6563 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6564 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6565 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6566 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6569 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6570 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6571 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6572 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6575 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6576 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6577 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6578 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6581 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6582 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6583 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6584 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6589 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6591 const SDLoc &dl) const {
6592 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6593 SDValue Src = Op.getOperand(0);
6594 if (Src.getValueType() == MVT::f32)
6595 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6598 switch (Op.getSimpleValueType().SimpleTy) {
6599 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6602 Op.getOpcode() == ISD::FP_TO_SINT
6604 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6608 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6609 "i64 FP_TO_UINT is supported only with FPCVT");
6610 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6616 // Convert the FP value to an int value through memory.
6617 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6618 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6619 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6620 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6621 MachinePointerInfo MPI =
6622 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6624 // Emit a store to the stack slot.
6627 MachineFunction &MF = DAG.getMachineFunction();
6628 MachineMemOperand *MMO =
6629 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6630 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6631 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6632 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6634 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6636 // Result is a load from the stack slot. If loading 4 bytes, make sure to
6637 // add in a bias on big endian.
6638 if (Op.getValueType() == MVT::i32 && !i32Stack) {
6639 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6640 DAG.getConstant(4, dl, FIPtr.getValueType()));
6641 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6649 /// \brief Custom lowers floating point to integer conversions to use
6650 /// the direct move instructions available in ISA 2.07 to avoid the
6651 /// need for load/store combinations.
6652 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6654 const SDLoc &dl) const {
6655 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6656 SDValue Src = Op.getOperand(0);
6658 if (Src.getValueType() == MVT::f32)
6659 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6662 switch (Op.getSimpleValueType().SimpleTy) {
6663 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6666 Op.getOpcode() == ISD::FP_TO_SINT
6668 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6670 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6673 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6674 "i64 FP_TO_UINT is supported only with FPCVT");
6675 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6678 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6684 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6685 const SDLoc &dl) const {
6686 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6687 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6690 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6692 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6693 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6696 // We're trying to insert a regular store, S, and then a load, L. If the
6697 // incoming value, O, is a load, we might just be able to have our load use the
6698 // address used by O. However, we don't know if anything else will store to
6699 // that address before we can load from it. To prevent this situation, we need
6700 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6701 // the same chain operand as O, we create a token factor from the chain results
6702 // of O and L, and we replace all uses of O's chain result with that token
6703 // factor (see spliceIntoChain below for this last part).
6704 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6707 ISD::LoadExtType ET) const {
6709 if (ET == ISD::NON_EXTLOAD &&
6710 (Op.getOpcode() == ISD::FP_TO_UINT ||
6711 Op.getOpcode() == ISD::FP_TO_SINT) &&
6712 isOperationLegalOrCustom(Op.getOpcode(),
6713 Op.getOperand(0).getValueType())) {
6715 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6719 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6720 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6721 LD->isNonTemporal())
6723 if (LD->getMemoryVT() != MemVT)
6726 RLI.Ptr = LD->getBasePtr();
6727 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6728 assert(LD->getAddressingMode() == ISD::PRE_INC &&
6729 "Non-pre-inc AM on PPC?");
6730 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6734 RLI.Chain = LD->getChain();
6735 RLI.MPI = LD->getPointerInfo();
6736 RLI.IsDereferenceable = LD->isDereferenceable();
6737 RLI.IsInvariant = LD->isInvariant();
6738 RLI.Alignment = LD->getAlignment();
6739 RLI.AAInfo = LD->getAAInfo();
6740 RLI.Ranges = LD->getRanges();
6742 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6746 // Given the head of the old chain, ResChain, insert a token factor containing
6747 // it and NewResChain, and make users of ResChain now be users of that token
6749 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6750 SDValue NewResChain,
6751 SelectionDAG &DAG) const {
6755 SDLoc dl(NewResChain);
6757 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6758 NewResChain, DAG.getUNDEF(MVT::Other));
6759 assert(TF.getNode() != NewResChain.getNode() &&
6760 "A new TF really is required here");
6762 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6763 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6766 /// \brief Analyze profitability of direct move
6767 /// prefer float load to int load plus direct move
6768 /// when there is no integer use of int load
6769 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6770 SDNode *Origin = Op.getOperand(0).getNode();
6771 if (Origin->getOpcode() != ISD::LOAD)
6774 // If there is no LXSIBZX/LXSIHZX, like Power8,
6775 // prefer direct move if the memory size is 1 or 2 bytes.
6776 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6777 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6780 for (SDNode::use_iterator UI = Origin->use_begin(),
6781 UE = Origin->use_end();
6784 // Only look at the users of the loaded value.
6785 if (UI.getUse().get().getResNo() != 0)
6788 if (UI->getOpcode() != ISD::SINT_TO_FP &&
6789 UI->getOpcode() != ISD::UINT_TO_FP)
6796 /// \brief Custom lowers integer to floating point conversions to use
6797 /// the direct move instructions available in ISA 2.07 to avoid the
6798 /// need for load/store combinations.
6799 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6801 const SDLoc &dl) const {
6802 assert((Op.getValueType() == MVT::f32 ||
6803 Op.getValueType() == MVT::f64) &&
6804 "Invalid floating point type as target of conversion");
6805 assert(Subtarget.hasFPCVT() &&
6806 "Int to FP conversions with direct moves require FPCVT");
6808 SDValue Src = Op.getOperand(0);
6809 bool SinglePrec = Op.getValueType() == MVT::f32;
6810 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6811 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6812 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6813 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6816 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6818 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6821 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6822 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6828 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6829 SelectionDAG &DAG) const {
6832 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6833 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6836 SDValue Value = Op.getOperand(0);
6837 // The values are now known to be -1 (false) or 1 (true). To convert this
6838 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6839 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6840 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6842 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6844 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6846 if (Op.getValueType() != MVT::v4f64)
6847 Value = DAG.getNode(ISD::FP_ROUND, dl,
6848 Op.getValueType(), Value,
6849 DAG.getIntPtrConstant(1, dl));
6853 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6854 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6857 if (Op.getOperand(0).getValueType() == MVT::i1)
6858 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6859 DAG.getConstantFP(1.0, dl, Op.getValueType()),
6860 DAG.getConstantFP(0.0, dl, Op.getValueType()));
6862 // If we have direct moves, we can do all the conversion, skip the store/load
6863 // however, without FPCVT we can't do most conversions.
6864 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6865 Subtarget.isPPC64() && Subtarget.hasFPCVT())
6866 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6868 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6869 "UINT_TO_FP is supported only with FPCVT");
6871 // If we have FCFIDS, then use it when converting to single-precision.
6872 // Otherwise, convert to double-precision and then round.
6873 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6874 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6876 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6878 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6882 if (Op.getOperand(0).getValueType() == MVT::i64) {
6883 SDValue SINT = Op.getOperand(0);
6884 // When converting to single-precision, we actually need to convert
6885 // to double-precision first and then round to single-precision.
6886 // To avoid double-rounding effects during that operation, we have
6887 // to prepare the input operand. Bits that might be truncated when
6888 // converting to double-precision are replaced by a bit that won't
6889 // be lost at this stage, but is below the single-precision rounding
6892 // However, if -enable-unsafe-fp-math is in effect, accept double
6893 // rounding to avoid the extra overhead.
6894 if (Op.getValueType() == MVT::f32 &&
6895 !Subtarget.hasFPCVT() &&
6896 !DAG.getTarget().Options.UnsafeFPMath) {
6898 // Twiddle input to make sure the low 11 bits are zero. (If this
6899 // is the case, we are guaranteed the value will fit into the 53 bit
6900 // mantissa of an IEEE double-precision value without rounding.)
6901 // If any of those low 11 bits were not zero originally, make sure
6902 // bit 12 (value 2048) is set instead, so that the final rounding
6903 // to single-precision gets the correct result.
6904 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6905 SINT, DAG.getConstant(2047, dl, MVT::i64));
6906 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6907 Round, DAG.getConstant(2047, dl, MVT::i64));
6908 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6909 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6910 Round, DAG.getConstant(-2048, dl, MVT::i64));
6912 // However, we cannot use that value unconditionally: if the magnitude
6913 // of the input value is small, the bit-twiddling we did above might
6914 // end up visibly changing the output. Fortunately, in that case, we
6915 // don't need to twiddle bits since the original input will convert
6916 // exactly to double-precision floating-point already. Therefore,
6917 // construct a conditional to use the original value if the top 11
6918 // bits are all sign-bit copies, and use the rounded value computed
6920 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6921 SINT, DAG.getConstant(53, dl, MVT::i32));
6922 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6923 Cond, DAG.getConstant(1, dl, MVT::i64));
6924 Cond = DAG.getSetCC(dl, MVT::i32,
6925 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6927 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6933 MachineFunction &MF = DAG.getMachineFunction();
6934 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6935 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6936 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6937 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6938 } else if (Subtarget.hasLFIWAX() &&
6939 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6940 MachineMemOperand *MMO =
6941 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6942 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6943 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6944 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6945 DAG.getVTList(MVT::f64, MVT::Other),
6946 Ops, MVT::i32, MMO);
6947 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6948 } else if (Subtarget.hasFPCVT() &&
6949 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6950 MachineMemOperand *MMO =
6951 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6952 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6953 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6954 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6955 DAG.getVTList(MVT::f64, MVT::Other),
6956 Ops, MVT::i32, MMO);
6957 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6958 } else if (((Subtarget.hasLFIWAX() &&
6959 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6960 (Subtarget.hasFPCVT() &&
6961 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6962 SINT.getOperand(0).getValueType() == MVT::i32) {
6963 MachineFrameInfo &MFI = MF.getFrameInfo();
6964 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6966 int FrameIdx = MFI.CreateStackObject(4, 4, false);
6967 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6970 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6971 MachinePointerInfo::getFixedStack(
6972 DAG.getMachineFunction(), FrameIdx));
6974 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6975 "Expected an i32 store");
6980 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6983 MachineMemOperand *MMO =
6984 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6985 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6986 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6987 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6988 PPCISD::LFIWZX : PPCISD::LFIWAX,
6989 dl, DAG.getVTList(MVT::f64, MVT::Other),
6990 Ops, MVT::i32, MMO);
6992 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6994 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6996 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6997 FP = DAG.getNode(ISD::FP_ROUND, dl,
6998 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7002 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7003 "Unhandled INT_TO_FP type in custom expander!");
7004 // Since we only generate this in 64-bit mode, we can take advantage of
7005 // 64-bit registers. In particular, sign extend the input value into the
7006 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7007 // then lfd it and fcfid it.
7008 MachineFunction &MF = DAG.getMachineFunction();
7009 MachineFrameInfo &MFI = MF.getFrameInfo();
7010 EVT PtrVT = getPointerTy(MF.getDataLayout());
7013 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7016 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7018 int FrameIdx = MFI.CreateStackObject(4, 4, false);
7019 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7022 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7023 MachinePointerInfo::getFixedStack(
7024 DAG.getMachineFunction(), FrameIdx));
7026 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7027 "Expected an i32 store");
7032 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7036 MachineMemOperand *MMO =
7037 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7038 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7039 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7040 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7041 PPCISD::LFIWZX : PPCISD::LFIWAX,
7042 dl, DAG.getVTList(MVT::f64, MVT::Other),
7043 Ops, MVT::i32, MMO);
7045 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7047 assert(Subtarget.isPPC64() &&
7048 "i32->FP without LFIWAX supported only on PPC64");
7050 int FrameIdx = MFI.CreateStackObject(8, 8, false);
7051 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7053 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7056 // STD the extended value into the stack slot.
7057 SDValue Store = DAG.getStore(
7058 DAG.getEntryNode(), dl, Ext64, FIdx,
7059 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7061 // Load the value as a double.
7063 MVT::f64, dl, Store, FIdx,
7064 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7067 // FCFID it and return it.
7068 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7069 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7070 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7071 DAG.getIntPtrConstant(0, dl));
7075 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7076 SelectionDAG &DAG) const {
7079 The rounding mode is in bits 30:31 of FPSR, and has the following
7086 FLT_ROUNDS, on the other hand, expects the following:
7093 To perform the conversion, we do:
7094 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7097 MachineFunction &MF = DAG.getMachineFunction();
7098 EVT VT = Op.getValueType();
7099 EVT PtrVT = getPointerTy(MF.getDataLayout());
7101 // Save FP Control Word to register
7103 MVT::f64, // return register
7104 MVT::Glue // unused in this context
7106 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7108 // Save FP register to stack slot
7109 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7110 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7111 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7112 MachinePointerInfo());
7114 // Load FP Control Word from low 32 bits of stack slot.
7115 SDValue Four = DAG.getConstant(4, dl, PtrVT);
7116 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7117 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7119 // Transform as necessary
7121 DAG.getNode(ISD::AND, dl, MVT::i32,
7122 CWD, DAG.getConstant(3, dl, MVT::i32));
7124 DAG.getNode(ISD::SRL, dl, MVT::i32,
7125 DAG.getNode(ISD::AND, dl, MVT::i32,
7126 DAG.getNode(ISD::XOR, dl, MVT::i32,
7127 CWD, DAG.getConstant(3, dl, MVT::i32)),
7128 DAG.getConstant(3, dl, MVT::i32)),
7129 DAG.getConstant(1, dl, MVT::i32));
7132 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7134 return DAG.getNode((VT.getSizeInBits() < 16 ?
7135 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7138 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7139 EVT VT = Op.getValueType();
7140 unsigned BitWidth = VT.getSizeInBits();
7142 assert(Op.getNumOperands() == 3 &&
7143 VT == Op.getOperand(1).getValueType() &&
7146 // Expand into a bunch of logical ops. Note that these ops
7147 // depend on the PPC behavior for oversized shift amounts.
7148 SDValue Lo = Op.getOperand(0);
7149 SDValue Hi = Op.getOperand(1);
7150 SDValue Amt = Op.getOperand(2);
7151 EVT AmtVT = Amt.getValueType();
7153 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7154 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7155 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7156 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7157 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7158 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7159 DAG.getConstant(-BitWidth, dl, AmtVT));
7160 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7161 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7162 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7163 SDValue OutOps[] = { OutLo, OutHi };
7164 return DAG.getMergeValues(OutOps, dl);
7167 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7168 EVT VT = Op.getValueType();
7170 unsigned BitWidth = VT.getSizeInBits();
7171 assert(Op.getNumOperands() == 3 &&
7172 VT == Op.getOperand(1).getValueType() &&
7175 // Expand into a bunch of logical ops. Note that these ops
7176 // depend on the PPC behavior for oversized shift amounts.
7177 SDValue Lo = Op.getOperand(0);
7178 SDValue Hi = Op.getOperand(1);
7179 SDValue Amt = Op.getOperand(2);
7180 EVT AmtVT = Amt.getValueType();
7182 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7183 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7184 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7185 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7186 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7187 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7188 DAG.getConstant(-BitWidth, dl, AmtVT));
7189 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7190 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7191 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7192 SDValue OutOps[] = { OutLo, OutHi };
7193 return DAG.getMergeValues(OutOps, dl);
7196 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7198 EVT VT = Op.getValueType();
7199 unsigned BitWidth = VT.getSizeInBits();
7200 assert(Op.getNumOperands() == 3 &&
7201 VT == Op.getOperand(1).getValueType() &&
7204 // Expand into a bunch of logical ops, followed by a select_cc.
7205 SDValue Lo = Op.getOperand(0);
7206 SDValue Hi = Op.getOperand(1);
7207 SDValue Amt = Op.getOperand(2);
7208 EVT AmtVT = Amt.getValueType();
7210 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7211 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7212 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7213 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7214 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7215 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7216 DAG.getConstant(-BitWidth, dl, AmtVT));
7217 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7218 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7219 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7220 Tmp4, Tmp6, ISD::SETLE);
7221 SDValue OutOps[] = { OutLo, OutHi };
7222 return DAG.getMergeValues(OutOps, dl);
7225 //===----------------------------------------------------------------------===//
7226 // Vector related lowering.
7229 /// BuildSplatI - Build a canonical splati of Val with an element size of
7230 /// SplatSize. Cast the result to VT.
7231 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7232 SelectionDAG &DAG, const SDLoc &dl) {
7233 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7235 static const MVT VTys[] = { // canonical VT to use for each size.
7236 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7239 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7241 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7245 EVT CanonicalVT = VTys[SplatSize-1];
7247 // Build a canonical splat for this value.
7248 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7251 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7252 /// specified intrinsic ID.
7253 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7254 const SDLoc &dl, EVT DestVT = MVT::Other) {
7255 if (DestVT == MVT::Other) DestVT = Op.getValueType();
7256 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7257 DAG.getConstant(IID, dl, MVT::i32), Op);
7260 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7261 /// specified intrinsic ID.
7262 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7263 SelectionDAG &DAG, const SDLoc &dl,
7264 EVT DestVT = MVT::Other) {
7265 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7266 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7267 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7270 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7271 /// specified intrinsic ID.
7272 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7273 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7274 EVT DestVT = MVT::Other) {
7275 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7276 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7277 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7280 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7281 /// amount. The result has the specified value type.
7282 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7283 SelectionDAG &DAG, const SDLoc &dl) {
7284 // Force LHS/RHS to be the right type.
7285 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7286 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7289 for (unsigned i = 0; i != 16; ++i)
7291 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7292 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7295 /// Do we have an efficient pattern in a .td file for this node?
7297 /// \param V - pointer to the BuildVectorSDNode being matched
7298 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7300 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7301 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7302 /// the opposite is true (expansion is beneficial) are:
7303 /// - The node builds a vector out of integers that are not 32 or 64-bits
7304 /// - The node builds a vector out of constants
7305 /// - The node is a "load-and-splat"
7306 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7307 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7308 bool HasDirectMove) {
7309 EVT VecVT = V->getValueType(0);
7310 bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 ||
7311 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7315 bool IsSplat = true;
7316 bool IsLoad = false;
7317 SDValue Op0 = V->getOperand(0);
7319 // This function is called in a block that confirms the node is not a constant
7320 // splat. So a constant BUILD_VECTOR here means the vector is built out of
7321 // different constants.
7322 if (V->isConstant())
7324 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7325 if (V->getOperand(i).isUndef())
7327 // We want to expand nodes that represent load-and-splat even if the
7328 // loaded value is a floating point truncation or conversion to int.
7329 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7330 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7331 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7332 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7333 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7334 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7335 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7337 // If the operands are different or the input is not a load and has more
7338 // uses than just this BV node, then it isn't a splat.
7339 if (V->getOperand(i) != Op0 ||
7340 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7343 return !(IsSplat && IsLoad);
7346 // If this is a case we can't handle, return null and let the default
7347 // expansion code take care of it. If we CAN select this case, and if it
7348 // selects to a single instruction, return Op. Otherwise, if we can codegen
7349 // this case more efficiently than a constant pool load, lower it to the
7350 // sequence of ops that should be used.
7351 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7352 SelectionDAG &DAG) const {
7354 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7355 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7357 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7358 // We first build an i32 vector, load it into a QPX register,
7359 // then convert it to a floating-point vector and compare it
7360 // to a zero vector to get the boolean result.
7361 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7362 int FrameIdx = MFI.CreateStackObject(16, 16, false);
7363 MachinePointerInfo PtrInfo =
7364 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7365 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7366 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7368 assert(BVN->getNumOperands() == 4 &&
7369 "BUILD_VECTOR for v4i1 does not have 4 operands");
7371 bool IsConst = true;
7372 for (unsigned i = 0; i < 4; ++i) {
7373 if (BVN->getOperand(i).isUndef()) continue;
7374 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7382 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7384 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7387 for (unsigned i = 0; i < 4; ++i) {
7388 if (BVN->getOperand(i).isUndef())
7389 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7390 else if (isNullConstant(BVN->getOperand(i)))
7396 Constant *CP = ConstantVector::get(CV);
7397 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7398 16 /* alignment */);
7400 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7401 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7402 return DAG.getMemIntrinsicNode(
7403 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7404 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7407 SmallVector<SDValue, 4> Stores;
7408 for (unsigned i = 0; i < 4; ++i) {
7409 if (BVN->getOperand(i).isUndef()) continue;
7411 unsigned Offset = 4*i;
7412 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7413 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7415 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7416 if (StoreSize > 4) {
7418 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7419 PtrInfo.getWithOffset(Offset), MVT::i32));
7421 SDValue StoreValue = BVN->getOperand(i);
7423 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7425 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7426 PtrInfo.getWithOffset(Offset)));
7431 if (!Stores.empty())
7432 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7434 StoreChain = DAG.getEntryNode();
7436 // Now load from v4i32 into the QPX register; this will extend it to
7437 // v4i64 but not yet convert it to a floating point. Nevertheless, this
7438 // is typed as v4f64 because the QPX register integer states are not
7439 // explicitly represented.
7441 SDValue Ops[] = {StoreChain,
7442 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7444 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7446 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7447 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7448 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7449 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7452 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7454 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7457 // All other QPX vectors are handled by generic code.
7458 if (Subtarget.hasQPX())
7461 // Check if this is a splat of a constant value.
7462 APInt APSplatBits, APSplatUndef;
7463 unsigned SplatBitSize;
7465 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7466 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7467 SplatBitSize > 32) {
7468 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7469 // lowered to VSX instructions under certain conditions.
7470 // Without VSX, there is no pattern more efficient than expanding the node.
7471 if (Subtarget.hasVSX() &&
7472 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove()))
7477 unsigned SplatBits = APSplatBits.getZExtValue();
7478 unsigned SplatUndef = APSplatUndef.getZExtValue();
7479 unsigned SplatSize = SplatBitSize / 8;
7481 // First, handle single instruction cases.
7484 if (SplatBits == 0) {
7485 // Canonicalize all zero vectors to be v4i32.
7486 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7487 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7488 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7493 // We have XXSPLTIB for constant splats one byte wide
7494 if (Subtarget.hasP9Vector() && SplatSize == 1) {
7495 // This is a splat of 1-byte elements with some elements potentially undef.
7496 // Rather than trying to match undef in the SDAG patterns, ensure that all
7497 // elements are the same constant.
7498 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7499 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7501 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7502 if (Op.getValueType() != MVT::v16i8)
7503 return DAG.getBitcast(Op.getValueType(), NewBV);
7509 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7510 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7512 if (SextVal >= -16 && SextVal <= 15)
7513 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7515 // Two instruction sequences.
7517 // If this value is in the range [-32,30] and is even, use:
7518 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7519 // If this value is in the range [17,31] and is odd, use:
7520 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7521 // If this value is in the range [-31,-17] and is odd, use:
7522 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7523 // Note the last two are three-instruction sequences.
7524 if (SextVal >= -32 && SextVal <= 31) {
7525 // To avoid having these optimizations undone by constant folding,
7526 // we convert to a pseudo that will be expanded later into one of
7528 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7529 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7530 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7531 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7532 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7533 if (VT == Op.getValueType())
7536 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7539 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
7540 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
7542 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7543 // Make -1 and vspltisw -1:
7544 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7546 // Make the VSLW intrinsic, computing 0x8000_0000.
7547 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7550 // xor by OnesV to invert it.
7551 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7552 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7555 // Check to see if this is a wide variety of vsplti*, binop self cases.
7556 static const signed char SplatCsts[] = {
7557 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7558 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7561 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7562 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7563 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
7564 int i = SplatCsts[idx];
7566 // Figure out what shift amount will be used by altivec if shifted by i in
7568 unsigned TypeShiftAmt = i & (SplatBitSize-1);
7570 // vsplti + shl self.
7571 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7572 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7573 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7574 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7575 Intrinsic::ppc_altivec_vslw
7577 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7578 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7581 // vsplti + srl self.
7582 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7583 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7584 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7585 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7586 Intrinsic::ppc_altivec_vsrw
7588 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7589 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7592 // vsplti + sra self.
7593 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7594 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7595 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7596 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7597 Intrinsic::ppc_altivec_vsraw
7599 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7600 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7603 // vsplti + rol self.
7604 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7605 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7606 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7607 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7608 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7609 Intrinsic::ppc_altivec_vrlw
7611 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7612 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7615 // t = vsplti c, result = vsldoi t, t, 1
7616 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7617 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7618 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7619 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7621 // t = vsplti c, result = vsldoi t, t, 2
7622 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7623 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7624 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7625 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7627 // t = vsplti c, result = vsldoi t, t, 3
7628 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7629 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7630 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7631 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7638 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7639 /// the specified operations to build the shuffle.
7640 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7641 SDValue RHS, SelectionDAG &DAG,
7643 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7644 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7645 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7648 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7660 if (OpNum == OP_COPY) {
7661 if (LHSID == (1*9+2)*9+3) return LHS;
7662 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7666 SDValue OpLHS, OpRHS;
7667 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7668 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7672 default: llvm_unreachable("Unknown i32 permute!");
7674 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
7675 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7676 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
7677 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7680 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7681 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7682 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7683 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7686 for (unsigned i = 0; i != 16; ++i)
7687 ShufIdxs[i] = (i&3)+0;
7690 for (unsigned i = 0; i != 16; ++i)
7691 ShufIdxs[i] = (i&3)+4;
7694 for (unsigned i = 0; i != 16; ++i)
7695 ShufIdxs[i] = (i&3)+8;
7698 for (unsigned i = 0; i != 16; ++i)
7699 ShufIdxs[i] = (i&3)+12;
7702 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7704 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7706 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7708 EVT VT = OpLHS.getValueType();
7709 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7710 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7711 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7712 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7715 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
7716 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
7717 /// return the code it can be lowered into. Worst case, it can always be
7718 /// lowered into a vperm.
7719 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7720 SelectionDAG &DAG) const {
7722 SDValue V1 = Op.getOperand(0);
7723 SDValue V2 = Op.getOperand(1);
7724 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7725 EVT VT = Op.getValueType();
7726 bool isLittleEndian = Subtarget.isLittleEndian();
7728 unsigned ShiftElts, InsertAtByte;
7730 if (Subtarget.hasP9Vector() &&
7731 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7735 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7736 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7738 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7739 DAG.getConstant(ShiftElts, dl, MVT::i32));
7740 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7741 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7742 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7744 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7745 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7746 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7750 if (Subtarget.hasVSX() &&
7751 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
7754 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7756 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
7758 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
7759 DAG.getConstant(ShiftElts, dl, MVT::i32));
7760 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
7763 if (Subtarget.hasVSX()) {
7764 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7765 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7767 // If the source for the shuffle is a scalar_to_vector that came from a
7768 // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7769 if (Subtarget.hasP9Vector() &&
7770 ((isLittleEndian && SplatIdx == 3) ||
7771 (!isLittleEndian && SplatIdx == 0))) {
7772 SDValue Src = V1.getOperand(0);
7773 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7774 Src.getOperand(0).getOpcode() == ISD::LOAD &&
7775 Src.getOperand(0).hasOneUse())
7778 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7779 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7780 DAG.getConstant(SplatIdx, dl, MVT::i32));
7781 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7784 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7785 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7786 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7787 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7788 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7792 if (Subtarget.hasQPX()) {
7793 if (VT.getVectorNumElements() != 4)
7796 if (V2.isUndef()) V2 = V1;
7798 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7799 if (AlignIdx != -1) {
7800 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7801 DAG.getConstant(AlignIdx, dl, MVT::i32));
7802 } else if (SVOp->isSplat()) {
7803 int SplatIdx = SVOp->getSplatIndex();
7804 if (SplatIdx >= 4) {
7809 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7810 DAG.getConstant(SplatIdx, dl, MVT::i32));
7813 // Lower this into a qvgpci/qvfperm pair.
7815 // Compute the qvgpci literal
7817 for (unsigned i = 0; i < 4; ++i) {
7818 int m = SVOp->getMaskElt(i);
7819 unsigned mm = m >= 0 ? (unsigned) m : i;
7820 idx |= mm << (3-i)*3;
7823 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7824 DAG.getConstant(idx, dl, MVT::i32));
7825 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7828 // Cases that are handled by instructions that take permute immediates
7829 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7830 // selected by the instruction selector.
7832 if (PPC::isSplatShuffleMask(SVOp, 1) ||
7833 PPC::isSplatShuffleMask(SVOp, 2) ||
7834 PPC::isSplatShuffleMask(SVOp, 4) ||
7835 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7836 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7837 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7838 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7839 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7840 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7841 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7842 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7843 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7844 (Subtarget.hasP8Altivec() && (
7845 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7846 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7847 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7852 // Altivec has a variety of "shuffle immediates" that take two vector inputs
7853 // and produce a fixed permutation. If any of these match, do not lower to
7855 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7856 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7857 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7858 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7859 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7860 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7861 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7862 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7863 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7864 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7865 (Subtarget.hasP8Altivec() && (
7866 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7867 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7868 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7871 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
7872 // perfect shuffle table to emit an optimal matching sequence.
7873 ArrayRef<int> PermMask = SVOp->getMask();
7875 unsigned PFIndexes[4];
7876 bool isFourElementShuffle = true;
7877 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7878 unsigned EltNo = 8; // Start out undef.
7879 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
7880 if (PermMask[i*4+j] < 0)
7881 continue; // Undef, ignore it.
7883 unsigned ByteSource = PermMask[i*4+j];
7884 if ((ByteSource & 3) != j) {
7885 isFourElementShuffle = false;
7890 EltNo = ByteSource/4;
7891 } else if (EltNo != ByteSource/4) {
7892 isFourElementShuffle = false;
7896 PFIndexes[i] = EltNo;
7899 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7900 // perfect shuffle vector to determine if it is cost effective to do this as
7901 // discrete instructions, or whether we should use a vperm.
7902 // For now, we skip this for little endian until such time as we have a
7903 // little-endian perfect shuffle table.
7904 if (isFourElementShuffle && !isLittleEndian) {
7905 // Compute the index in the perfect shuffle table.
7906 unsigned PFTableIndex =
7907 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7909 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7910 unsigned Cost = (PFEntry >> 30);
7912 // Determining when to avoid vperm is tricky. Many things affect the cost
7913 // of vperm, particularly how many times the perm mask needs to be computed.
7914 // For example, if the perm mask can be hoisted out of a loop or is already
7915 // used (perhaps because there are multiple permutes with the same shuffle
7916 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
7917 // the loop requires an extra register.
7919 // As a compromise, we only emit discrete instructions if the shuffle can be
7920 // generated in 3 or fewer operations. When we have loop information
7921 // available, if this block is within a loop, we should avoid using vperm
7922 // for 3-operation perms and use a constant pool load instead.
7924 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7927 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7928 // vector that will get spilled to the constant pool.
7929 if (V2.isUndef()) V2 = V1;
7931 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7932 // that it is in input element units, not in bytes. Convert now.
7934 // For little endian, the order of the input vectors is reversed, and
7935 // the permutation mask is complemented with respect to 31. This is
7936 // necessary to produce proper semantics with the big-endian-biased vperm
7938 EVT EltVT = V1.getValueType().getVectorElementType();
7939 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7941 SmallVector<SDValue, 16> ResultMask;
7942 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7943 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7945 for (unsigned j = 0; j != BytesPerElement; ++j)
7947 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7950 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7954 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7956 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7959 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7963 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7964 /// vector comparison. If it is, return true and fill in Opc/isDot with
7965 /// information about the intrinsic.
7966 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7967 bool &isDot, const PPCSubtarget &Subtarget) {
7968 unsigned IntrinsicID =
7969 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7972 switch (IntrinsicID) {
7975 // Comparison predicates.
7976 case Intrinsic::ppc_altivec_vcmpbfp_p:
7980 case Intrinsic::ppc_altivec_vcmpeqfp_p:
7984 case Intrinsic::ppc_altivec_vcmpequb_p:
7988 case Intrinsic::ppc_altivec_vcmpequh_p:
7992 case Intrinsic::ppc_altivec_vcmpequw_p:
7996 case Intrinsic::ppc_altivec_vcmpequd_p:
7997 if (Subtarget.hasP8Altivec()) {
8003 case Intrinsic::ppc_altivec_vcmpneb_p:
8004 case Intrinsic::ppc_altivec_vcmpneh_p:
8005 case Intrinsic::ppc_altivec_vcmpnew_p:
8006 case Intrinsic::ppc_altivec_vcmpnezb_p:
8007 case Intrinsic::ppc_altivec_vcmpnezh_p:
8008 case Intrinsic::ppc_altivec_vcmpnezw_p:
8009 if (Subtarget.hasP9Altivec()) {
8010 switch (IntrinsicID) {
8012 llvm_unreachable("Unknown comparison intrinsic.");
8013 case Intrinsic::ppc_altivec_vcmpneb_p:
8016 case Intrinsic::ppc_altivec_vcmpneh_p:
8019 case Intrinsic::ppc_altivec_vcmpnew_p:
8022 case Intrinsic::ppc_altivec_vcmpnezb_p:
8025 case Intrinsic::ppc_altivec_vcmpnezh_p:
8028 case Intrinsic::ppc_altivec_vcmpnezw_p:
8036 case Intrinsic::ppc_altivec_vcmpgefp_p:
8040 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8044 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8048 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8052 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8056 case Intrinsic::ppc_altivec_vcmpgtsd_p:
8057 if (Subtarget.hasP8Altivec()) {
8063 case Intrinsic::ppc_altivec_vcmpgtub_p:
8067 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8071 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8075 case Intrinsic::ppc_altivec_vcmpgtud_p:
8076 if (Subtarget.hasP8Altivec()) {
8083 // VSX predicate comparisons use the same infrastructure
8084 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8085 case Intrinsic::ppc_vsx_xvcmpgedp_p:
8086 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8087 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8088 case Intrinsic::ppc_vsx_xvcmpgesp_p:
8089 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8090 if (Subtarget.hasVSX()) {
8091 switch (IntrinsicID) {
8092 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8095 case Intrinsic::ppc_vsx_xvcmpgedp_p:
8098 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8101 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8104 case Intrinsic::ppc_vsx_xvcmpgesp_p:
8107 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8116 // Normal Comparisons.
8117 case Intrinsic::ppc_altivec_vcmpbfp:
8120 case Intrinsic::ppc_altivec_vcmpeqfp:
8123 case Intrinsic::ppc_altivec_vcmpequb:
8126 case Intrinsic::ppc_altivec_vcmpequh:
8129 case Intrinsic::ppc_altivec_vcmpequw:
8132 case Intrinsic::ppc_altivec_vcmpequd:
8133 if (Subtarget.hasP8Altivec())
8138 case Intrinsic::ppc_altivec_vcmpneb:
8139 case Intrinsic::ppc_altivec_vcmpneh:
8140 case Intrinsic::ppc_altivec_vcmpnew:
8141 case Intrinsic::ppc_altivec_vcmpnezb:
8142 case Intrinsic::ppc_altivec_vcmpnezh:
8143 case Intrinsic::ppc_altivec_vcmpnezw:
8144 if (Subtarget.hasP9Altivec())
8145 switch (IntrinsicID) {
8147 llvm_unreachable("Unknown comparison intrinsic.");
8148 case Intrinsic::ppc_altivec_vcmpneb:
8151 case Intrinsic::ppc_altivec_vcmpneh:
8154 case Intrinsic::ppc_altivec_vcmpnew:
8157 case Intrinsic::ppc_altivec_vcmpnezb:
8160 case Intrinsic::ppc_altivec_vcmpnezh:
8163 case Intrinsic::ppc_altivec_vcmpnezw:
8170 case Intrinsic::ppc_altivec_vcmpgefp:
8173 case Intrinsic::ppc_altivec_vcmpgtfp:
8176 case Intrinsic::ppc_altivec_vcmpgtsb:
8179 case Intrinsic::ppc_altivec_vcmpgtsh:
8182 case Intrinsic::ppc_altivec_vcmpgtsw:
8185 case Intrinsic::ppc_altivec_vcmpgtsd:
8186 if (Subtarget.hasP8Altivec())
8191 case Intrinsic::ppc_altivec_vcmpgtub:
8194 case Intrinsic::ppc_altivec_vcmpgtuh:
8197 case Intrinsic::ppc_altivec_vcmpgtuw:
8200 case Intrinsic::ppc_altivec_vcmpgtud:
8201 if (Subtarget.hasP8Altivec())
8210 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8211 /// lower, do it, otherwise return null.
8212 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8213 SelectionDAG &DAG) const {
8214 unsigned IntrinsicID =
8215 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8217 if (IntrinsicID == Intrinsic::thread_pointer) {
8218 // Reads the thread pointer register, used for __builtin_thread_pointer.
8219 bool is64bit = Subtarget.isPPC64();
8220 return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
8221 is64bit ? MVT::i64 : MVT::i32);
8224 // If this is a lowered altivec predicate compare, CompareOpc is set to the
8225 // opcode number of the comparison.
8229 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8230 return SDValue(); // Don't custom lower most intrinsics.
8232 // If this is a non-dot comparison, make the VCMP node and we are done.
8234 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8235 Op.getOperand(1), Op.getOperand(2),
8236 DAG.getConstant(CompareOpc, dl, MVT::i32));
8237 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8240 // Create the PPCISD altivec 'dot' comparison node.
8242 Op.getOperand(2), // LHS
8243 Op.getOperand(3), // RHS
8244 DAG.getConstant(CompareOpc, dl, MVT::i32)
8246 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8247 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8249 // Now that we have the comparison, emit a copy from the CR to a GPR.
8250 // This is flagged to the above dot comparison.
8251 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8252 DAG.getRegister(PPC::CR6, MVT::i32),
8253 CompNode.getValue(1));
8255 // Unpack the result based on how the target uses it.
8256 unsigned BitNo; // Bit # of CR6.
8257 bool InvertBit; // Invert result?
8258 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8259 default: // Can't happen, don't crash on invalid number though.
8260 case 0: // Return the value of the EQ bit of CR6.
8261 BitNo = 0; InvertBit = false;
8263 case 1: // Return the inverted value of the EQ bit of CR6.
8264 BitNo = 0; InvertBit = true;
8266 case 2: // Return the value of the LT bit of CR6.
8267 BitNo = 2; InvertBit = false;
8269 case 3: // Return the inverted value of the LT bit of CR6.
8270 BitNo = 2; InvertBit = true;
8274 // Shift the bit into the low position.
8275 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8276 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8278 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8279 DAG.getConstant(1, dl, MVT::i32));
8281 // If we are supposed to, toggle the bit.
8283 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8284 DAG.getConstant(1, dl, MVT::i32));
8288 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8289 SelectionDAG &DAG) const {
8290 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8291 // the beginning of the argument list.
8292 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8294 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8295 case Intrinsic::ppc_cfence: {
8296 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
8297 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8298 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8299 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8300 Op.getOperand(ArgStart + 1)),
8310 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8311 SelectionDAG &DAG) const {
8313 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8314 // instructions), but for smaller types, we need to first extend up to v2i32
8315 // before doing going farther.
8316 if (Op.getValueType() == MVT::v2i64) {
8317 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8318 if (ExtVT != MVT::v2i32) {
8319 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8320 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8321 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8322 ExtVT.getVectorElementType(), 4)));
8323 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8324 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8325 DAG.getValueType(MVT::v2i32));
8334 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8335 SelectionDAG &DAG) const {
8337 // Create a stack slot that is 16-byte aligned.
8338 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8339 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8340 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8341 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8343 // Store the input value into Value#0 of the stack slot.
8344 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8345 MachinePointerInfo());
8347 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8350 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8351 SelectionDAG &DAG) const {
8352 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8353 "Should only be called for ISD::INSERT_VECTOR_ELT");
8354 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8355 // We have legal lowering for constant indices but not for variable ones.
8361 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8362 SelectionDAG &DAG) const {
8364 SDNode *N = Op.getNode();
8366 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8367 "Unknown extract_vector_elt type");
8369 SDValue Value = N->getOperand(0);
8371 // The first part of this is like the store lowering except that we don't
8372 // need to track the chain.
8374 // The values are now known to be -1 (false) or 1 (true). To convert this
8375 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8376 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8377 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8379 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8380 // understand how to form the extending load.
8381 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8383 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8385 // Now convert to an integer and store.
8386 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8387 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8390 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8391 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8392 MachinePointerInfo PtrInfo =
8393 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8394 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8395 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8397 SDValue StoreChain = DAG.getEntryNode();
8398 SDValue Ops[] = {StoreChain,
8399 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8401 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8403 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8404 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8406 // Extract the value requested.
8407 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8408 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8409 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8412 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8414 if (!Subtarget.useCRBits())
8417 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8420 /// Lowering for QPX v4i1 loads
8421 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8422 SelectionDAG &DAG) const {
8424 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8425 SDValue LoadChain = LN->getChain();
8426 SDValue BasePtr = LN->getBasePtr();
8428 if (Op.getValueType() == MVT::v4f64 ||
8429 Op.getValueType() == MVT::v4f32) {
8430 EVT MemVT = LN->getMemoryVT();
8431 unsigned Alignment = LN->getAlignment();
8433 // If this load is properly aligned, then it is legal.
8434 if (Alignment >= MemVT.getStoreSize())
8437 EVT ScalarVT = Op.getValueType().getScalarType(),
8438 ScalarMemVT = MemVT.getScalarType();
8439 unsigned Stride = ScalarMemVT.getStoreSize();
8441 SDValue Vals[4], LoadChains[4];
8442 for (unsigned Idx = 0; Idx < 4; ++Idx) {
8444 if (ScalarVT != ScalarMemVT)
8445 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8447 LN->getPointerInfo().getWithOffset(Idx * Stride),
8448 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8449 LN->getMemOperand()->getFlags(), LN->getAAInfo());
8451 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8452 LN->getPointerInfo().getWithOffset(Idx * Stride),
8453 MinAlign(Alignment, Idx * Stride),
8454 LN->getMemOperand()->getFlags(), LN->getAAInfo());
8456 if (Idx == 0 && LN->isIndexed()) {
8457 assert(LN->getAddressingMode() == ISD::PRE_INC &&
8458 "Unknown addressing mode on vector load");
8459 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8460 LN->getAddressingMode());
8464 LoadChains[Idx] = Load.getValue(1);
8466 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8467 DAG.getConstant(Stride, dl,
8468 BasePtr.getValueType()));
8471 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8472 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8474 if (LN->isIndexed()) {
8475 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8476 return DAG.getMergeValues(RetOps, dl);
8479 SDValue RetOps[] = { Value, TF };
8480 return DAG.getMergeValues(RetOps, dl);
8483 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8484 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8486 // To lower v4i1 from a byte array, we load the byte elements of the
8487 // vector and then reuse the BUILD_VECTOR logic.
8489 SDValue VectElmts[4], VectElmtChains[4];
8490 for (unsigned i = 0; i < 4; ++i) {
8491 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8492 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8494 VectElmts[i] = DAG.getExtLoad(
8495 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8496 LN->getPointerInfo().getWithOffset(i), MVT::i8,
8497 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8498 VectElmtChains[i] = VectElmts[i].getValue(1);
8501 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8502 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8504 SDValue RVals[] = { Value, LoadChain };
8505 return DAG.getMergeValues(RVals, dl);
8508 /// Lowering for QPX v4i1 stores
8509 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8510 SelectionDAG &DAG) const {
8512 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8513 SDValue StoreChain = SN->getChain();
8514 SDValue BasePtr = SN->getBasePtr();
8515 SDValue Value = SN->getValue();
8517 if (Value.getValueType() == MVT::v4f64 ||
8518 Value.getValueType() == MVT::v4f32) {
8519 EVT MemVT = SN->getMemoryVT();
8520 unsigned Alignment = SN->getAlignment();
8522 // If this store is properly aligned, then it is legal.
8523 if (Alignment >= MemVT.getStoreSize())
8526 EVT ScalarVT = Value.getValueType().getScalarType(),
8527 ScalarMemVT = MemVT.getScalarType();
8528 unsigned Stride = ScalarMemVT.getStoreSize();
8531 for (unsigned Idx = 0; Idx < 4; ++Idx) {
8532 SDValue Ex = DAG.getNode(
8533 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8534 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8536 if (ScalarVT != ScalarMemVT)
8538 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8539 SN->getPointerInfo().getWithOffset(Idx * Stride),
8540 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8541 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8543 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8544 SN->getPointerInfo().getWithOffset(Idx * Stride),
8545 MinAlign(Alignment, Idx * Stride),
8546 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8548 if (Idx == 0 && SN->isIndexed()) {
8549 assert(SN->getAddressingMode() == ISD::PRE_INC &&
8550 "Unknown addressing mode on vector store");
8551 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8552 SN->getAddressingMode());
8555 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8556 DAG.getConstant(Stride, dl,
8557 BasePtr.getValueType()));
8558 Stores[Idx] = Store;
8561 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8563 if (SN->isIndexed()) {
8564 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8565 return DAG.getMergeValues(RetOps, dl);
8571 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8572 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8574 // The values are now known to be -1 (false) or 1 (true). To convert this
8575 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8576 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8577 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8579 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8580 // understand how to form the extending load.
8581 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8583 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8585 // Now convert to an integer and store.
8586 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8587 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8590 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8591 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8592 MachinePointerInfo PtrInfo =
8593 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8594 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8595 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8597 SDValue Ops[] = {StoreChain,
8598 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8600 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8602 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8603 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8605 // Move data into the byte array.
8606 SDValue Loads[4], LoadChains[4];
8607 for (unsigned i = 0; i < 4; ++i) {
8608 unsigned Offset = 4*i;
8609 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8610 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8612 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8613 PtrInfo.getWithOffset(Offset));
8614 LoadChains[i] = Loads[i].getValue(1);
8617 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8620 for (unsigned i = 0; i < 4; ++i) {
8621 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8622 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8624 Stores[i] = DAG.getTruncStore(
8625 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8626 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8630 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8635 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8637 if (Op.getValueType() == MVT::v4i32) {
8638 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8640 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
8641 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8643 SDValue RHSSwap = // = vrlw RHS, 16
8644 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8646 // Shrinkify inputs to v8i16.
8647 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8648 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8649 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8651 // Low parts multiplied together, generating 32-bit results (we ignore the
8653 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8654 LHS, RHS, DAG, dl, MVT::v4i32);
8656 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8657 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8658 // Shift the high parts up 16 bits.
8659 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8661 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8662 } else if (Op.getValueType() == MVT::v8i16) {
8663 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8665 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8667 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8668 LHS, RHS, Zero, DAG, dl);
8669 } else if (Op.getValueType() == MVT::v16i8) {
8670 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8671 bool isLittleEndian = Subtarget.isLittleEndian();
8673 // Multiply the even 8-bit parts, producing 16-bit sums.
8674 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8675 LHS, RHS, DAG, dl, MVT::v8i16);
8676 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8678 // Multiply the odd 8-bit parts, producing 16-bit sums.
8679 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8680 LHS, RHS, DAG, dl, MVT::v8i16);
8681 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8683 // Merge the results together. Because vmuleub and vmuloub are
8684 // instructions with a big-endian bias, we must reverse the
8685 // element numbering and reverse the meaning of "odd" and "even"
8686 // when generating little endian code.
8688 for (unsigned i = 0; i != 8; ++i) {
8689 if (isLittleEndian) {
8691 Ops[i*2+1] = 2*i+16;
8694 Ops[i*2+1] = 2*i+1+16;
8698 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8700 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8702 llvm_unreachable("Unknown mul to lower!");
8706 /// LowerOperation - Provide custom lowering hooks for some operations.
8708 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8709 switch (Op.getOpcode()) {
8710 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8711 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8712 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8713 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8714 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8715 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8716 case ISD::SETCC: return LowerSETCC(Op, DAG);
8717 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
8718 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
8720 return LowerVASTART(Op, DAG);
8723 return LowerVAARG(Op, DAG);
8726 return LowerVACOPY(Op, DAG);
8728 case ISD::STACKRESTORE:
8729 return LowerSTACKRESTORE(Op, DAG);
8731 case ISD::DYNAMIC_STACKALLOC:
8732 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8734 case ISD::GET_DYNAMIC_AREA_OFFSET:
8735 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8737 case ISD::EH_DWARF_CFA:
8738 return LowerEH_DWARF_CFA(Op, DAG);
8740 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
8741 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
8743 case ISD::LOAD: return LowerLOAD(Op, DAG);
8744 case ISD::STORE: return LowerSTORE(Op, DAG);
8745 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
8746 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8747 case ISD::FP_TO_UINT:
8748 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
8750 case ISD::UINT_TO_FP:
8751 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8752 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8754 // Lower 64-bit shifts.
8755 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
8756 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
8757 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
8759 // Vector-related lowering.
8760 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8761 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8762 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8763 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8764 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
8765 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8766 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8767 case ISD::MUL: return LowerMUL(Op, DAG);
8769 // For counter-based loop handling.
8770 case ISD::INTRINSIC_W_CHAIN: return SDValue();
8772 // Frame & Return address.
8773 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8774 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8776 case ISD::INTRINSIC_VOID:
8777 return LowerINTRINSIC_VOID(Op, DAG);
8781 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8782 SmallVectorImpl<SDValue>&Results,
8783 SelectionDAG &DAG) const {
8785 switch (N->getOpcode()) {
8787 llvm_unreachable("Do not know how to custom type legalize this operation!");
8788 case ISD::READCYCLECOUNTER: {
8789 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8790 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8792 Results.push_back(RTB);
8793 Results.push_back(RTB.getValue(1));
8794 Results.push_back(RTB.getValue(2));
8797 case ISD::INTRINSIC_W_CHAIN: {
8798 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8799 Intrinsic::ppc_is_decremented_ctr_nonzero)
8802 assert(N->getValueType(0) == MVT::i1 &&
8803 "Unexpected result type for CTR decrement intrinsic");
8804 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8805 N->getValueType(0));
8806 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8807 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8810 Results.push_back(NewInt);
8811 Results.push_back(NewInt.getValue(1));
8815 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8818 EVT VT = N->getValueType(0);
8820 if (VT == MVT::i64) {
8821 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8823 Results.push_back(NewNode);
8824 Results.push_back(NewNode.getValue(1));
8828 case ISD::FP_ROUND_INREG: {
8829 assert(N->getValueType(0) == MVT::ppcf128);
8830 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8831 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8832 MVT::f64, N->getOperand(0),
8833 DAG.getIntPtrConstant(0, dl));
8834 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8835 MVT::f64, N->getOperand(0),
8836 DAG.getIntPtrConstant(1, dl));
8838 // Add the two halves of the long double in round-to-zero mode.
8839 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8841 // We know the low half is about to be thrown away, so just use something
8843 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8847 case ISD::FP_TO_SINT:
8848 case ISD::FP_TO_UINT:
8849 // LowerFP_TO_INT() can only handle f32 and f64.
8850 if (N->getOperand(0).getValueType() == MVT::ppcf128)
8852 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8857 //===----------------------------------------------------------------------===//
8858 // Other Lowering Code
8859 //===----------------------------------------------------------------------===//
8861 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8862 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8863 Function *Func = Intrinsic::getDeclaration(M, Id);
8864 return Builder.CreateCall(Func, {});
8867 // The mappings for emitLeading/TrailingFence is taken from
8868 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8869 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8871 AtomicOrdering Ord) const {
8872 if (Ord == AtomicOrdering::SequentiallyConsistent)
8873 return callIntrinsic(Builder, Intrinsic::ppc_sync);
8874 if (isReleaseOrStronger(Ord))
8875 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8879 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8881 AtomicOrdering Ord) const {
8882 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
8883 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8884 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8885 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8886 if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
8887 return Builder.CreateCall(
8888 Intrinsic::getDeclaration(
8889 Builder.GetInsertBlock()->getParent()->getParent(),
8890 Intrinsic::ppc_cfence, {Inst->getType()}),
8892 // FIXME: Can use isync for rmw operation.
8893 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8899 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8900 unsigned AtomicSize,
8903 unsigned CmpPred) const {
8904 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8905 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8907 auto LoadMnemonic = PPC::LDARX;
8908 auto StoreMnemonic = PPC::STDCX;
8909 switch (AtomicSize) {
8911 llvm_unreachable("Unexpected size of atomic entity");
8913 LoadMnemonic = PPC::LBARX;
8914 StoreMnemonic = PPC::STBCX;
8915 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8918 LoadMnemonic = PPC::LHARX;
8919 StoreMnemonic = PPC::STHCX;
8920 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8923 LoadMnemonic = PPC::LWARX;
8924 StoreMnemonic = PPC::STWCX;
8927 LoadMnemonic = PPC::LDARX;
8928 StoreMnemonic = PPC::STDCX;
8932 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8933 MachineFunction *F = BB->getParent();
8934 MachineFunction::iterator It = ++BB->getIterator();
8936 unsigned dest = MI.getOperand(0).getReg();
8937 unsigned ptrA = MI.getOperand(1).getReg();
8938 unsigned ptrB = MI.getOperand(2).getReg();
8939 unsigned incr = MI.getOperand(3).getReg();
8940 DebugLoc dl = MI.getDebugLoc();
8942 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8943 MachineBasicBlock *loop2MBB =
8944 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8945 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8946 F->insert(It, loopMBB);
8948 F->insert(It, loop2MBB);
8949 F->insert(It, exitMBB);
8950 exitMBB->splice(exitMBB->begin(), BB,
8951 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8952 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8954 MachineRegisterInfo &RegInfo = F->getRegInfo();
8955 unsigned TmpReg = (!BinOpcode) ? incr :
8956 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8957 : &PPC::GPRCRegClass);
8961 // fallthrough --> loopMBB
8962 BB->addSuccessor(loopMBB);
8965 // l[wd]arx dest, ptr
8966 // add r0, dest, incr
8967 // st[wd]cx. r0, ptr
8969 // fallthrough --> exitMBB
8973 // l[wd]arx dest, ptr
8974 // cmpl?[wd] incr, dest
8977 // st[wd]cx. dest, ptr
8979 // fallthrough --> exitMBB
8982 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8983 .addReg(ptrA).addReg(ptrB);
8985 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8987 // Signed comparisons of byte or halfword values must be sign-extended.
8988 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8989 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8990 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8991 ExtReg).addReg(dest);
8992 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8993 .addReg(incr).addReg(ExtReg);
8995 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8996 .addReg(incr).addReg(dest);
8998 BuildMI(BB, dl, TII->get(PPC::BCC))
8999 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9000 BB->addSuccessor(loop2MBB);
9001 BB->addSuccessor(exitMBB);
9004 BuildMI(BB, dl, TII->get(StoreMnemonic))
9005 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9006 BuildMI(BB, dl, TII->get(PPC::BCC))
9007 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9008 BB->addSuccessor(loopMBB);
9009 BB->addSuccessor(exitMBB);
9018 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
9019 MachineBasicBlock *BB,
9020 bool is8bit, // operation
9023 unsigned CmpPred) const {
9024 // If we support part-word atomic mnemonics, just use them
9025 if (Subtarget.hasPartwordAtomics())
9026 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
9027 CmpOpcode, CmpPred);
9029 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9030 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9031 // In 64 bit mode we have to use 64 bits for addresses, even though the
9032 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
9033 // registers without caring whether they're 32 or 64, but here we're
9034 // doing actual arithmetic on the addresses.
9035 bool is64bit = Subtarget.isPPC64();
9036 bool isLittleEndian = Subtarget.isLittleEndian();
9037 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9039 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9040 MachineFunction *F = BB->getParent();
9041 MachineFunction::iterator It = ++BB->getIterator();
9043 unsigned dest = MI.getOperand(0).getReg();
9044 unsigned ptrA = MI.getOperand(1).getReg();
9045 unsigned ptrB = MI.getOperand(2).getReg();
9046 unsigned incr = MI.getOperand(3).getReg();
9047 DebugLoc dl = MI.getDebugLoc();
9049 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9050 MachineBasicBlock *loop2MBB =
9051 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9052 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9053 F->insert(It, loopMBB);
9055 F->insert(It, loop2MBB);
9056 F->insert(It, exitMBB);
9057 exitMBB->splice(exitMBB->begin(), BB,
9058 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9059 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9061 MachineRegisterInfo &RegInfo = F->getRegInfo();
9062 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9063 : &PPC::GPRCRegClass;
9064 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9065 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9067 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9068 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
9069 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9070 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9071 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9072 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9073 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
9074 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9075 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9077 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
9081 // fallthrough --> loopMBB
9082 BB->addSuccessor(loopMBB);
9084 // The 4-byte load must be aligned, while a char or short may be
9085 // anywhere in the word. Hence all this nasty bookkeeping code.
9086 // add ptr1, ptrA, ptrB [copy if ptrA==0]
9087 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9088 // xori shift, shift1, 24 [16]
9089 // rlwinm ptr, ptr1, 0, 0, 29
9090 // slw incr2, incr, shift
9091 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9092 // slw mask, mask2, shift
9094 // lwarx tmpDest, ptr
9095 // add tmp, tmpDest, incr2
9096 // andc tmp2, tmpDest, mask
9097 // and tmp3, tmp, mask
9098 // or tmp4, tmp3, tmp2
9101 // fallthrough --> exitMBB
9102 // srw dest, tmpDest, shift
9103 if (ptrA != ZeroReg) {
9104 Ptr1Reg = RegInfo.createVirtualRegister(RC);
9105 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9106 .addReg(ptrA).addReg(ptrB);
9110 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9111 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9112 if (!isLittleEndian)
9113 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9114 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9116 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9117 .addReg(Ptr1Reg).addImm(0).addImm(61);
9119 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9120 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9121 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9122 .addReg(incr).addReg(ShiftReg);
9124 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9126 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9127 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9129 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9130 .addReg(Mask2Reg).addReg(ShiftReg);
9133 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9134 .addReg(ZeroReg).addReg(PtrReg);
9136 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9137 .addReg(Incr2Reg).addReg(TmpDestReg);
9138 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9139 .addReg(TmpDestReg).addReg(MaskReg);
9140 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9141 .addReg(TmpReg).addReg(MaskReg);
9143 // For unsigned comparisons, we can directly compare the shifted values.
9144 // For signed comparisons we shift and sign extend.
9145 unsigned SReg = RegInfo.createVirtualRegister(RC);
9146 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9147 .addReg(TmpDestReg).addReg(MaskReg);
9148 unsigned ValueReg = SReg;
9149 unsigned CmpReg = Incr2Reg;
9150 if (CmpOpcode == PPC::CMPW) {
9151 ValueReg = RegInfo.createVirtualRegister(RC);
9152 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9153 .addReg(SReg).addReg(ShiftReg);
9154 unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9155 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9157 ValueReg = ValueSReg;
9160 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9161 .addReg(CmpReg).addReg(ValueReg);
9162 BuildMI(BB, dl, TII->get(PPC::BCC))
9163 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9164 BB->addSuccessor(loop2MBB);
9165 BB->addSuccessor(exitMBB);
9168 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9169 .addReg(Tmp3Reg).addReg(Tmp2Reg);
9170 BuildMI(BB, dl, TII->get(PPC::STWCX))
9171 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9172 BuildMI(BB, dl, TII->get(PPC::BCC))
9173 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9174 BB->addSuccessor(loopMBB);
9175 BB->addSuccessor(exitMBB);
9180 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9185 llvm::MachineBasicBlock *
9186 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9187 MachineBasicBlock *MBB) const {
9188 DebugLoc DL = MI.getDebugLoc();
9189 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9190 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9192 MachineFunction *MF = MBB->getParent();
9193 MachineRegisterInfo &MRI = MF->getRegInfo();
9195 const BasicBlock *BB = MBB->getBasicBlock();
9196 MachineFunction::iterator I = ++MBB->getIterator();
9199 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9200 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9202 unsigned DstReg = MI.getOperand(0).getReg();
9203 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9204 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9205 unsigned mainDstReg = MRI.createVirtualRegister(RC);
9206 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9208 MVT PVT = getPointerTy(MF->getDataLayout());
9209 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9210 "Invalid Pointer Size!");
9211 // For v = setjmp(buf), we generate
9214 // SjLjSetup mainMBB
9220 // buf[LabelOffset] = LR
9224 // v = phi(main, restore)
9227 MachineBasicBlock *thisMBB = MBB;
9228 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9229 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9230 MF->insert(I, mainMBB);
9231 MF->insert(I, sinkMBB);
9233 MachineInstrBuilder MIB;
9235 // Transfer the remainder of BB and its successor edges to sinkMBB.
9236 sinkMBB->splice(sinkMBB->begin(), MBB,
9237 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9238 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9240 // Note that the structure of the jmp_buf used here is not compatible
9241 // with that used by libc, and is not designed to be. Specifically, it
9242 // stores only those 'reserved' registers that LLVM does not otherwise
9243 // understand how to spill. Also, by convention, by the time this
9244 // intrinsic is called, Clang has already stored the frame address in the
9245 // first slot of the buffer and stack address in the third. Following the
9246 // X86 target code, we'll store the jump address in the second slot. We also
9247 // need to save the TOC pointer (R2) to handle jumps between shared
9248 // libraries, and that will be stored in the fourth slot. The thread
9249 // identifier (R13) is not affected.
9252 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9253 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9254 const int64_t BPOffset = 4 * PVT.getStoreSize();
9256 // Prepare IP either in reg.
9257 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9258 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9259 unsigned BufReg = MI.getOperand(1).getReg();
9261 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9262 setUsesTOCBasePtr(*MBB->getParent());
9263 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9267 MIB.setMemRefs(MMOBegin, MMOEnd);
9270 // Naked functions never have a base pointer, and so we use r1. For all
9271 // other functions, this decision must be delayed until during PEI.
9273 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9274 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9276 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9278 MIB = BuildMI(*thisMBB, MI, DL,
9279 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9283 MIB.setMemRefs(MMOBegin, MMOEnd);
9286 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9287 MIB.addRegMask(TRI->getNoPreservedMask());
9289 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9291 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9293 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9295 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9296 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9301 BuildMI(mainMBB, DL,
9302 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9305 if (Subtarget.isPPC64()) {
9306 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9308 .addImm(LabelOffset)
9311 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9313 .addImm(LabelOffset)
9317 MIB.setMemRefs(MMOBegin, MMOEnd);
9319 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9320 mainMBB->addSuccessor(sinkMBB);
9323 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9324 TII->get(PPC::PHI), DstReg)
9325 .addReg(mainDstReg).addMBB(mainMBB)
9326 .addReg(restoreDstReg).addMBB(thisMBB);
9328 MI.eraseFromParent();
9333 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9334 MachineBasicBlock *MBB) const {
9335 DebugLoc DL = MI.getDebugLoc();
9336 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9338 MachineFunction *MF = MBB->getParent();
9339 MachineRegisterInfo &MRI = MF->getRegInfo();
9342 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9343 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9345 MVT PVT = getPointerTy(MF->getDataLayout());
9346 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9347 "Invalid Pointer Size!");
9349 const TargetRegisterClass *RC =
9350 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9351 unsigned Tmp = MRI.createVirtualRegister(RC);
9352 // Since FP is only updated here but NOT referenced, it's treated as GPR.
9353 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9354 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9358 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9361 MachineInstrBuilder MIB;
9363 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9364 const int64_t SPOffset = 2 * PVT.getStoreSize();
9365 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9366 const int64_t BPOffset = 4 * PVT.getStoreSize();
9368 unsigned BufReg = MI.getOperand(0).getReg();
9370 // Reload FP (the jumped-to function may not have had a
9371 // frame pointer, and if so, then its r31 will be restored
9373 if (PVT == MVT::i64) {
9374 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9378 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9382 MIB.setMemRefs(MMOBegin, MMOEnd);
9385 if (PVT == MVT::i64) {
9386 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9387 .addImm(LabelOffset)
9390 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9391 .addImm(LabelOffset)
9394 MIB.setMemRefs(MMOBegin, MMOEnd);
9397 if (PVT == MVT::i64) {
9398 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9402 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9406 MIB.setMemRefs(MMOBegin, MMOEnd);
9409 if (PVT == MVT::i64) {
9410 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9414 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9418 MIB.setMemRefs(MMOBegin, MMOEnd);
9421 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9422 setUsesTOCBasePtr(*MBB->getParent());
9423 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9427 MIB.setMemRefs(MMOBegin, MMOEnd);
9431 BuildMI(*MBB, MI, DL,
9432 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9433 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9435 MI.eraseFromParent();
9440 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9441 MachineBasicBlock *BB) const {
9442 if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9443 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9444 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9445 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9446 // Call lowering should have added an r2 operand to indicate a dependence
9447 // on the TOC base pointer value. It can't however, because there is no
9448 // way to mark the dependence as implicit there, and so the stackmap code
9449 // will confuse it with a regular operand. Instead, add the dependence
9451 setUsesTOCBasePtr(*BB->getParent());
9452 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9455 return emitPatchPoint(MI, BB);
9458 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9459 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9460 return emitEHSjLjSetJmp(MI, BB);
9461 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9462 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9463 return emitEHSjLjLongJmp(MI, BB);
9466 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9468 // To "insert" these instructions we actually have to insert their
9469 // control-flow patterns.
9470 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9471 MachineFunction::iterator It = ++BB->getIterator();
9473 MachineFunction *F = BB->getParent();
9475 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9476 MI.getOpcode() == PPC::SELECT_CC_I8 ||
9477 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9478 SmallVector<MachineOperand, 2> Cond;
9479 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9480 MI.getOpcode() == PPC::SELECT_CC_I8)
9481 Cond.push_back(MI.getOperand(4));
9483 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9484 Cond.push_back(MI.getOperand(1));
9486 DebugLoc dl = MI.getDebugLoc();
9487 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9488 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9489 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9490 MI.getOpcode() == PPC::SELECT_CC_I8 ||
9491 MI.getOpcode() == PPC::SELECT_CC_F4 ||
9492 MI.getOpcode() == PPC::SELECT_CC_F8 ||
9493 MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9494 MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9495 MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9496 MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9497 MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9498 MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9499 MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9500 MI.getOpcode() == PPC::SELECT_I4 ||
9501 MI.getOpcode() == PPC::SELECT_I8 ||
9502 MI.getOpcode() == PPC::SELECT_F4 ||
9503 MI.getOpcode() == PPC::SELECT_F8 ||
9504 MI.getOpcode() == PPC::SELECT_QFRC ||
9505 MI.getOpcode() == PPC::SELECT_QSRC ||
9506 MI.getOpcode() == PPC::SELECT_QBRC ||
9507 MI.getOpcode() == PPC::SELECT_VRRC ||
9508 MI.getOpcode() == PPC::SELECT_VSFRC ||
9509 MI.getOpcode() == PPC::SELECT_VSSRC ||
9510 MI.getOpcode() == PPC::SELECT_VSRC) {
9511 // The incoming instruction knows the destination vreg to set, the
9512 // condition code register to branch on, the true/false values to
9513 // select between, and a branch opcode to use.
9518 // cmpTY ccX, r1, r2
9520 // fallthrough --> copy0MBB
9521 MachineBasicBlock *thisMBB = BB;
9522 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9523 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9524 DebugLoc dl = MI.getDebugLoc();
9525 F->insert(It, copy0MBB);
9526 F->insert(It, sinkMBB);
9528 // Transfer the remainder of BB and its successor edges to sinkMBB.
9529 sinkMBB->splice(sinkMBB->begin(), BB,
9530 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9531 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9533 // Next, add the true and fallthrough blocks as its successors.
9534 BB->addSuccessor(copy0MBB);
9535 BB->addSuccessor(sinkMBB);
9537 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9538 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9539 MI.getOpcode() == PPC::SELECT_QFRC ||
9540 MI.getOpcode() == PPC::SELECT_QSRC ||
9541 MI.getOpcode() == PPC::SELECT_QBRC ||
9542 MI.getOpcode() == PPC::SELECT_VRRC ||
9543 MI.getOpcode() == PPC::SELECT_VSFRC ||
9544 MI.getOpcode() == PPC::SELECT_VSSRC ||
9545 MI.getOpcode() == PPC::SELECT_VSRC) {
9546 BuildMI(BB, dl, TII->get(PPC::BC))
9547 .addReg(MI.getOperand(1).getReg())
9550 unsigned SelectPred = MI.getOperand(4).getImm();
9551 BuildMI(BB, dl, TII->get(PPC::BCC))
9553 .addReg(MI.getOperand(1).getReg())
9558 // %FalseValue = ...
9559 // # fallthrough to sinkMBB
9562 // Update machine-CFG edges
9563 BB->addSuccessor(sinkMBB);
9566 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9569 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9570 .addReg(MI.getOperand(3).getReg())
9572 .addReg(MI.getOperand(2).getReg())
9574 } else if (MI.getOpcode() == PPC::ReadTB) {
9575 // To read the 64-bit time-base register on a 32-bit target, we read the
9576 // two halves. Should the counter have wrapped while it was being read, we
9577 // need to try again.
9580 // mfspr Rx,TBU # load from TBU
9581 // mfspr Ry,TB # load from TB
9582 // mfspr Rz,TBU # load from TBU
9583 // cmpw crX,Rx,Rz # check if 'old'='new'
9584 // bne readLoop # branch if they're not equal
9587 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9588 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9589 DebugLoc dl = MI.getDebugLoc();
9590 F->insert(It, readMBB);
9591 F->insert(It, sinkMBB);
9593 // Transfer the remainder of BB and its successor edges to sinkMBB.
9594 sinkMBB->splice(sinkMBB->begin(), BB,
9595 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9596 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9598 BB->addSuccessor(readMBB);
9601 MachineRegisterInfo &RegInfo = F->getRegInfo();
9602 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9603 unsigned LoReg = MI.getOperand(0).getReg();
9604 unsigned HiReg = MI.getOperand(1).getReg();
9606 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9607 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9608 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9610 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9612 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9613 .addReg(HiReg).addReg(ReadAgainReg);
9614 BuildMI(BB, dl, TII->get(PPC::BCC))
9615 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9617 BB->addSuccessor(readMBB);
9618 BB->addSuccessor(sinkMBB);
9619 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9620 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9621 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9622 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9623 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9624 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9625 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9626 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9628 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9629 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9630 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9631 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9632 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9633 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9634 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9635 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9637 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9638 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9639 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9640 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9641 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9642 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9643 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9644 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9646 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9647 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9648 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9649 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9650 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9651 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9652 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9653 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9655 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9656 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9657 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9658 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9659 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9660 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9661 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9662 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9664 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9665 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9666 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9667 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9668 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9669 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9670 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9671 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9673 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9674 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9675 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9676 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9677 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9678 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9679 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9680 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9682 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9683 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9684 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9685 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9686 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9687 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9688 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9689 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9691 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9692 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9693 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9694 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9695 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9696 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9697 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9698 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9700 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9701 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9702 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9703 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9704 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9705 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9706 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9707 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9709 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9710 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9711 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9712 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9713 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9714 BB = EmitAtomicBinary(MI, BB, 4, 0);
9715 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9716 BB = EmitAtomicBinary(MI, BB, 8, 0);
9717 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9718 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9719 (Subtarget.hasPartwordAtomics() &&
9720 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9721 (Subtarget.hasPartwordAtomics() &&
9722 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9723 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9725 auto LoadMnemonic = PPC::LDARX;
9726 auto StoreMnemonic = PPC::STDCX;
9727 switch (MI.getOpcode()) {
9729 llvm_unreachable("Compare and swap of unknown size");
9730 case PPC::ATOMIC_CMP_SWAP_I8:
9731 LoadMnemonic = PPC::LBARX;
9732 StoreMnemonic = PPC::STBCX;
9733 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9735 case PPC::ATOMIC_CMP_SWAP_I16:
9736 LoadMnemonic = PPC::LHARX;
9737 StoreMnemonic = PPC::STHCX;
9738 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9740 case PPC::ATOMIC_CMP_SWAP_I32:
9741 LoadMnemonic = PPC::LWARX;
9742 StoreMnemonic = PPC::STWCX;
9744 case PPC::ATOMIC_CMP_SWAP_I64:
9745 LoadMnemonic = PPC::LDARX;
9746 StoreMnemonic = PPC::STDCX;
9749 unsigned dest = MI.getOperand(0).getReg();
9750 unsigned ptrA = MI.getOperand(1).getReg();
9751 unsigned ptrB = MI.getOperand(2).getReg();
9752 unsigned oldval = MI.getOperand(3).getReg();
9753 unsigned newval = MI.getOperand(4).getReg();
9754 DebugLoc dl = MI.getDebugLoc();
9756 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9757 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9758 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9759 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9760 F->insert(It, loop1MBB);
9761 F->insert(It, loop2MBB);
9762 F->insert(It, midMBB);
9763 F->insert(It, exitMBB);
9764 exitMBB->splice(exitMBB->begin(), BB,
9765 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9766 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9770 // fallthrough --> loopMBB
9771 BB->addSuccessor(loop1MBB);
9774 // l[bhwd]arx dest, ptr
9775 // cmp[wd] dest, oldval
9778 // st[bhwd]cx. newval, ptr
9782 // st[bhwd]cx. dest, ptr
9785 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9786 .addReg(ptrA).addReg(ptrB);
9787 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9788 .addReg(oldval).addReg(dest);
9789 BuildMI(BB, dl, TII->get(PPC::BCC))
9790 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9791 BB->addSuccessor(loop2MBB);
9792 BB->addSuccessor(midMBB);
9795 BuildMI(BB, dl, TII->get(StoreMnemonic))
9796 .addReg(newval).addReg(ptrA).addReg(ptrB);
9797 BuildMI(BB, dl, TII->get(PPC::BCC))
9798 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9799 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9800 BB->addSuccessor(loop1MBB);
9801 BB->addSuccessor(exitMBB);
9804 BuildMI(BB, dl, TII->get(StoreMnemonic))
9805 .addReg(dest).addReg(ptrA).addReg(ptrB);
9806 BB->addSuccessor(exitMBB);
9811 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9812 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9813 // We must use 64-bit registers for addresses when targeting 64-bit,
9814 // since we're actually doing arithmetic on them. Other registers
9816 bool is64bit = Subtarget.isPPC64();
9817 bool isLittleEndian = Subtarget.isLittleEndian();
9818 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9820 unsigned dest = MI.getOperand(0).getReg();
9821 unsigned ptrA = MI.getOperand(1).getReg();
9822 unsigned ptrB = MI.getOperand(2).getReg();
9823 unsigned oldval = MI.getOperand(3).getReg();
9824 unsigned newval = MI.getOperand(4).getReg();
9825 DebugLoc dl = MI.getDebugLoc();
9827 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9828 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9829 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9830 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9831 F->insert(It, loop1MBB);
9832 F->insert(It, loop2MBB);
9833 F->insert(It, midMBB);
9834 F->insert(It, exitMBB);
9835 exitMBB->splice(exitMBB->begin(), BB,
9836 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9837 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9839 MachineRegisterInfo &RegInfo = F->getRegInfo();
9840 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9841 : &PPC::GPRCRegClass;
9842 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9843 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9845 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9846 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9847 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9848 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9849 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9850 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9851 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9852 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9853 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9854 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9855 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9857 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9858 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9861 // fallthrough --> loopMBB
9862 BB->addSuccessor(loop1MBB);
9864 // The 4-byte load must be aligned, while a char or short may be
9865 // anywhere in the word. Hence all this nasty bookkeeping code.
9866 // add ptr1, ptrA, ptrB [copy if ptrA==0]
9867 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9868 // xori shift, shift1, 24 [16]
9869 // rlwinm ptr, ptr1, 0, 0, 29
9870 // slw newval2, newval, shift
9871 // slw oldval2, oldval,shift
9872 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9873 // slw mask, mask2, shift
9874 // and newval3, newval2, mask
9875 // and oldval3, oldval2, mask
9877 // lwarx tmpDest, ptr
9878 // and tmp, tmpDest, mask
9879 // cmpw tmp, oldval3
9882 // andc tmp2, tmpDest, mask
9883 // or tmp4, tmp2, newval3
9888 // stwcx. tmpDest, ptr
9890 // srw dest, tmpDest, shift
9891 if (ptrA != ZeroReg) {
9892 Ptr1Reg = RegInfo.createVirtualRegister(RC);
9893 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9894 .addReg(ptrA).addReg(ptrB);
9898 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9899 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9900 if (!isLittleEndian)
9901 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9902 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9904 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9905 .addReg(Ptr1Reg).addImm(0).addImm(61);
9907 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9908 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9909 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9910 .addReg(newval).addReg(ShiftReg);
9911 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9912 .addReg(oldval).addReg(ShiftReg);
9914 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9916 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9917 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9918 .addReg(Mask3Reg).addImm(65535);
9920 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9921 .addReg(Mask2Reg).addReg(ShiftReg);
9922 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9923 .addReg(NewVal2Reg).addReg(MaskReg);
9924 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9925 .addReg(OldVal2Reg).addReg(MaskReg);
9928 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9929 .addReg(ZeroReg).addReg(PtrReg);
9930 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9931 .addReg(TmpDestReg).addReg(MaskReg);
9932 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9933 .addReg(TmpReg).addReg(OldVal3Reg);
9934 BuildMI(BB, dl, TII->get(PPC::BCC))
9935 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9936 BB->addSuccessor(loop2MBB);
9937 BB->addSuccessor(midMBB);
9940 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9941 .addReg(TmpDestReg).addReg(MaskReg);
9942 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9943 .addReg(Tmp2Reg).addReg(NewVal3Reg);
9944 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9945 .addReg(ZeroReg).addReg(PtrReg);
9946 BuildMI(BB, dl, TII->get(PPC::BCC))
9947 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9948 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9949 BB->addSuccessor(loop1MBB);
9950 BB->addSuccessor(exitMBB);
9953 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9954 .addReg(ZeroReg).addReg(PtrReg);
9955 BB->addSuccessor(exitMBB);
9960 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9962 } else if (MI.getOpcode() == PPC::FADDrtz) {
9963 // This pseudo performs an FADD with rounding mode temporarily forced
9964 // to round-to-zero. We emit this via custom inserter since the FPSCR
9965 // is not modeled at the SelectionDAG level.
9966 unsigned Dest = MI.getOperand(0).getReg();
9967 unsigned Src1 = MI.getOperand(1).getReg();
9968 unsigned Src2 = MI.getOperand(2).getReg();
9969 DebugLoc dl = MI.getDebugLoc();
9971 MachineRegisterInfo &RegInfo = F->getRegInfo();
9972 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9974 // Save FPSCR value.
9975 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9977 // Set rounding mode to round-to-zero.
9978 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9979 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9981 // Perform addition.
9982 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9984 // Restore FPSCR value.
9985 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9986 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9987 MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9988 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9989 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9990 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9991 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9994 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9995 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9997 MachineRegisterInfo &RegInfo = F->getRegInfo();
9998 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9999 &PPC::GPRCRegClass :
10000 &PPC::G8RCRegClass);
10002 DebugLoc dl = MI.getDebugLoc();
10003 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
10004 .addReg(MI.getOperand(1).getReg())
10006 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
10007 MI.getOperand(0).getReg())
10008 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
10009 } else if (MI.getOpcode() == PPC::TCHECK_RET) {
10010 DebugLoc Dl = MI.getDebugLoc();
10011 MachineRegisterInfo &RegInfo = F->getRegInfo();
10012 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10013 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
10016 llvm_unreachable("Unexpected instr type to insert");
10019 MI.eraseFromParent(); // The pseudo instruction is gone now.
10023 //===----------------------------------------------------------------------===//
10024 // Target Optimization Hooks
10025 //===----------------------------------------------------------------------===//
10027 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
10028 // For the estimates, convergence is quadratic, so we essentially double the
10029 // number of digits correct after every iteration. For both FRE and FRSQRTE,
10030 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
10031 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
10032 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
10033 if (VT.getScalarType() == MVT::f64)
10035 return RefinementSteps;
10038 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
10039 int Enabled, int &RefinementSteps,
10040 bool &UseOneConstNR,
10041 bool Reciprocal) const {
10042 EVT VT = Operand.getValueType();
10043 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
10044 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
10045 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10046 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10047 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10048 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10049 if (RefinementSteps == ReciprocalEstimate::Unspecified)
10050 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10052 UseOneConstNR = true;
10053 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
10058 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
10060 int &RefinementSteps) const {
10061 EVT VT = Operand.getValueType();
10062 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
10063 (VT == MVT::f64 && Subtarget.hasFRE()) ||
10064 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10065 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10066 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10067 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10068 if (RefinementSteps == ReciprocalEstimate::Unspecified)
10069 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10070 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
10075 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
10076 // Note: This functionality is used only when unsafe-fp-math is enabled, and
10077 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
10078 // enabled for division), this functionality is redundant with the default
10079 // combiner logic (once the division -> reciprocal/multiply transformation
10080 // has taken place). As a result, this matters more for older cores than for
10083 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10084 // reciprocal if there are two or more FDIVs (for embedded cores with only
10085 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10086 switch (Subtarget.getDarwinDirective()) {
10091 case PPC::DIR_E500mc:
10092 case PPC::DIR_E5500:
10097 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10098 // collapsed, and so we need to look through chains of them.
10099 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10100 int64_t& Offset, SelectionDAG &DAG) {
10101 if (DAG.isBaseWithConstantOffset(Loc)) {
10102 Base = Loc.getOperand(0);
10103 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10105 // The base might itself be a base plus an offset, and if so, accumulate
10107 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10111 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10112 unsigned Bytes, int Dist,
10113 SelectionDAG &DAG) {
10114 if (VT.getSizeInBits() / 8 != Bytes)
10117 SDValue BaseLoc = Base->getBasePtr();
10118 if (Loc.getOpcode() == ISD::FrameIndex) {
10119 if (BaseLoc.getOpcode() != ISD::FrameIndex)
10121 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10122 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
10123 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10124 int FS = MFI.getObjectSize(FI);
10125 int BFS = MFI.getObjectSize(BFI);
10126 if (FS != BFS || FS != (int)Bytes) return false;
10127 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10130 SDValue Base1 = Loc, Base2 = BaseLoc;
10131 int64_t Offset1 = 0, Offset2 = 0;
10132 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10133 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10134 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10138 const GlobalValue *GV1 = nullptr;
10139 const GlobalValue *GV2 = nullptr;
10142 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10143 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10144 if (isGA1 && isGA2 && GV1 == GV2)
10145 return Offset1 == (Offset2 + Dist*Bytes);
10149 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10150 // not enforce equality of the chain operands.
10151 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10152 unsigned Bytes, int Dist,
10153 SelectionDAG &DAG) {
10154 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10155 EVT VT = LS->getMemoryVT();
10156 SDValue Loc = LS->getBasePtr();
10157 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10160 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10162 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10163 default: return false;
10164 case Intrinsic::ppc_qpx_qvlfd:
10165 case Intrinsic::ppc_qpx_qvlfda:
10168 case Intrinsic::ppc_qpx_qvlfs:
10169 case Intrinsic::ppc_qpx_qvlfsa:
10172 case Intrinsic::ppc_qpx_qvlfcd:
10173 case Intrinsic::ppc_qpx_qvlfcda:
10176 case Intrinsic::ppc_qpx_qvlfcs:
10177 case Intrinsic::ppc_qpx_qvlfcsa:
10180 case Intrinsic::ppc_qpx_qvlfiwa:
10181 case Intrinsic::ppc_qpx_qvlfiwz:
10182 case Intrinsic::ppc_altivec_lvx:
10183 case Intrinsic::ppc_altivec_lvxl:
10184 case Intrinsic::ppc_vsx_lxvw4x:
10185 case Intrinsic::ppc_vsx_lxvw4x_be:
10188 case Intrinsic::ppc_vsx_lxvd2x:
10189 case Intrinsic::ppc_vsx_lxvd2x_be:
10192 case Intrinsic::ppc_altivec_lvebx:
10195 case Intrinsic::ppc_altivec_lvehx:
10198 case Intrinsic::ppc_altivec_lvewx:
10203 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10206 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10208 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10209 default: return false;
10210 case Intrinsic::ppc_qpx_qvstfd:
10211 case Intrinsic::ppc_qpx_qvstfda:
10214 case Intrinsic::ppc_qpx_qvstfs:
10215 case Intrinsic::ppc_qpx_qvstfsa:
10218 case Intrinsic::ppc_qpx_qvstfcd:
10219 case Intrinsic::ppc_qpx_qvstfcda:
10222 case Intrinsic::ppc_qpx_qvstfcs:
10223 case Intrinsic::ppc_qpx_qvstfcsa:
10226 case Intrinsic::ppc_qpx_qvstfiw:
10227 case Intrinsic::ppc_qpx_qvstfiwa:
10228 case Intrinsic::ppc_altivec_stvx:
10229 case Intrinsic::ppc_altivec_stvxl:
10230 case Intrinsic::ppc_vsx_stxvw4x:
10233 case Intrinsic::ppc_vsx_stxvd2x:
10236 case Intrinsic::ppc_vsx_stxvw4x_be:
10239 case Intrinsic::ppc_vsx_stxvd2x_be:
10242 case Intrinsic::ppc_altivec_stvebx:
10245 case Intrinsic::ppc_altivec_stvehx:
10248 case Intrinsic::ppc_altivec_stvewx:
10253 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10259 // Return true is there is a nearyby consecutive load to the one provided
10260 // (regardless of alignment). We search up and down the chain, looking though
10261 // token factors and other loads (but nothing else). As a result, a true result
10262 // indicates that it is safe to create a new consecutive load adjacent to the
10264 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10265 SDValue Chain = LD->getChain();
10266 EVT VT = LD->getMemoryVT();
10268 SmallSet<SDNode *, 16> LoadRoots;
10269 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10270 SmallSet<SDNode *, 16> Visited;
10272 // First, search up the chain, branching to follow all token-factor operands.
10273 // If we find a consecutive load, then we're done, otherwise, record all
10274 // nodes just above the top-level loads and token factors.
10275 while (!Queue.empty()) {
10276 SDNode *ChainNext = Queue.pop_back_val();
10277 if (!Visited.insert(ChainNext).second)
10280 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10281 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10284 if (!Visited.count(ChainLD->getChain().getNode()))
10285 Queue.push_back(ChainLD->getChain().getNode());
10286 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10287 for (const SDUse &O : ChainNext->ops())
10288 if (!Visited.count(O.getNode()))
10289 Queue.push_back(O.getNode());
10291 LoadRoots.insert(ChainNext);
10294 // Second, search down the chain, starting from the top-level nodes recorded
10295 // in the first phase. These top-level nodes are the nodes just above all
10296 // loads and token factors. Starting with their uses, recursively look though
10297 // all loads (just the chain uses) and token factors to find a consecutive
10302 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10303 IE = LoadRoots.end(); I != IE; ++I) {
10304 Queue.push_back(*I);
10306 while (!Queue.empty()) {
10307 SDNode *LoadRoot = Queue.pop_back_val();
10308 if (!Visited.insert(LoadRoot).second)
10311 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10312 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10315 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10316 UE = LoadRoot->use_end(); UI != UE; ++UI)
10317 if (((isa<MemSDNode>(*UI) &&
10318 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10319 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10320 Queue.push_back(*UI);
10327 /// This function is called when we have proved that a SETCC node can be replaced
10328 /// by subtraction (and other supporting instructions) so that the result of
10329 /// comparison is kept in a GPR instead of CR. This function is purely for
10330 /// codegen purposes and has some flags to guide the codegen process.
10331 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10332 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10333 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10335 // Zero extend the operands to the largest legal integer. Originally, they
10336 // must be of a strictly smaller size.
10337 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10338 DAG.getConstant(Size, DL, MVT::i32));
10339 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10340 DAG.getConstant(Size, DL, MVT::i32));
10342 // Swap if needed. Depends on the condition code.
10344 std::swap(Op0, Op1);
10346 // Subtract extended integers.
10347 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10349 // Move the sign bit to the least significant position and zero out the rest.
10350 // Now the least significant bit carries the result of original comparison.
10351 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10352 DAG.getConstant(Size - 1, DL, MVT::i32));
10353 auto Final = Shifted;
10355 // Complement the result if needed. Based on the condition code.
10357 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10358 DAG.getConstant(1, DL, MVT::i64));
10360 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10363 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10364 DAGCombinerInfo &DCI) const {
10365 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10367 SelectionDAG &DAG = DCI.DAG;
10370 // Size of integers being compared has a critical role in the following
10371 // analysis, so we prefer to do this when all types are legal.
10372 if (!DCI.isAfterLegalizeVectorOps())
10375 // If all users of SETCC extend its value to a legal integer type
10376 // then we replace SETCC with a subtraction
10377 for (SDNode::use_iterator UI = N->use_begin(),
10378 UE = N->use_end(); UI != UE; ++UI) {
10379 if (UI->getOpcode() != ISD::ZERO_EXTEND)
10383 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10384 auto OpSize = N->getOperand(0).getValueSizeInBits();
10386 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10388 if (OpSize < Size) {
10392 return generateEquivalentSub(N, Size, false, false, DL, DAG);
10394 return generateEquivalentSub(N, Size, true, true, DL, DAG);
10396 return generateEquivalentSub(N, Size, false, true, DL, DAG);
10398 return generateEquivalentSub(N, Size, true, false, DL, DAG);
10405 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10406 DAGCombinerInfo &DCI) const {
10407 SelectionDAG &DAG = DCI.DAG;
10410 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10411 // If we're tracking CR bits, we need to be careful that we don't have:
10412 // trunc(binary-ops(zext(x), zext(y)))
10414 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10415 // such that we're unnecessarily moving things into GPRs when it would be
10416 // better to keep them in CR bits.
10418 // Note that trunc here can be an actual i1 trunc, or can be the effective
10419 // truncation that comes from a setcc or select_cc.
10420 if (N->getOpcode() == ISD::TRUNCATE &&
10421 N->getValueType(0) != MVT::i1)
10424 if (N->getOperand(0).getValueType() != MVT::i32 &&
10425 N->getOperand(0).getValueType() != MVT::i64)
10428 if (N->getOpcode() == ISD::SETCC ||
10429 N->getOpcode() == ISD::SELECT_CC) {
10430 // If we're looking at a comparison, then we need to make sure that the
10431 // high bits (all except for the first) don't matter the result.
10433 cast<CondCodeSDNode>(N->getOperand(
10434 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10435 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10437 if (ISD::isSignedIntSetCC(CC)) {
10438 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10439 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10441 } else if (ISD::isUnsignedIntSetCC(CC)) {
10442 if (!DAG.MaskedValueIsZero(N->getOperand(0),
10443 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10444 !DAG.MaskedValueIsZero(N->getOperand(1),
10445 APInt::getHighBitsSet(OpBits, OpBits-1)))
10446 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10449 // This is neither a signed nor an unsigned comparison, just make sure
10450 // that the high bits are equal.
10451 KnownBits Op1Known, Op2Known;
10452 DAG.computeKnownBits(N->getOperand(0), Op1Known);
10453 DAG.computeKnownBits(N->getOperand(1), Op2Known);
10455 // We don't really care about what is known about the first bit (if
10456 // anything), so clear it in all masks prior to comparing them.
10457 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
10458 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
10460 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
10465 // We now know that the higher-order bits are irrelevant, we just need to
10466 // make sure that all of the intermediate operations are bit operations, and
10467 // all inputs are extensions.
10468 if (N->getOperand(0).getOpcode() != ISD::AND &&
10469 N->getOperand(0).getOpcode() != ISD::OR &&
10470 N->getOperand(0).getOpcode() != ISD::XOR &&
10471 N->getOperand(0).getOpcode() != ISD::SELECT &&
10472 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10473 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10474 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10475 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10476 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10479 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10480 N->getOperand(1).getOpcode() != ISD::AND &&
10481 N->getOperand(1).getOpcode() != ISD::OR &&
10482 N->getOperand(1).getOpcode() != ISD::XOR &&
10483 N->getOperand(1).getOpcode() != ISD::SELECT &&
10484 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10485 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10486 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10487 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10488 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10491 SmallVector<SDValue, 4> Inputs;
10492 SmallVector<SDValue, 8> BinOps, PromOps;
10493 SmallPtrSet<SDNode *, 16> Visited;
10495 for (unsigned i = 0; i < 2; ++i) {
10496 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10497 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10498 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10499 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10500 isa<ConstantSDNode>(N->getOperand(i)))
10501 Inputs.push_back(N->getOperand(i));
10503 BinOps.push_back(N->getOperand(i));
10505 if (N->getOpcode() == ISD::TRUNCATE)
10509 // Visit all inputs, collect all binary operations (and, or, xor and
10510 // select) that are all fed by extensions.
10511 while (!BinOps.empty()) {
10512 SDValue BinOp = BinOps.back();
10515 if (!Visited.insert(BinOp.getNode()).second)
10518 PromOps.push_back(BinOp);
10520 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10521 // The condition of the select is not promoted.
10522 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10524 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10527 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10528 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10529 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10530 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10531 isa<ConstantSDNode>(BinOp.getOperand(i))) {
10532 Inputs.push_back(BinOp.getOperand(i));
10533 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10534 BinOp.getOperand(i).getOpcode() == ISD::OR ||
10535 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10536 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10537 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10538 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10539 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10540 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10541 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10542 BinOps.push_back(BinOp.getOperand(i));
10544 // We have an input that is not an extension or another binary
10545 // operation; we'll abort this transformation.
10551 // Make sure that this is a self-contained cluster of operations (which
10552 // is not quite the same thing as saying that everything has only one
10554 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10555 if (isa<ConstantSDNode>(Inputs[i]))
10558 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10559 UE = Inputs[i].getNode()->use_end();
10561 SDNode *User = *UI;
10562 if (User != N && !Visited.count(User))
10565 // Make sure that we're not going to promote the non-output-value
10566 // operand(s) or SELECT or SELECT_CC.
10567 // FIXME: Although we could sometimes handle this, and it does occur in
10568 // practice that one of the condition inputs to the select is also one of
10569 // the outputs, we currently can't deal with this.
10570 if (User->getOpcode() == ISD::SELECT) {
10571 if (User->getOperand(0) == Inputs[i])
10573 } else if (User->getOpcode() == ISD::SELECT_CC) {
10574 if (User->getOperand(0) == Inputs[i] ||
10575 User->getOperand(1) == Inputs[i])
10581 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10582 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10583 UE = PromOps[i].getNode()->use_end();
10585 SDNode *User = *UI;
10586 if (User != N && !Visited.count(User))
10589 // Make sure that we're not going to promote the non-output-value
10590 // operand(s) or SELECT or SELECT_CC.
10591 // FIXME: Although we could sometimes handle this, and it does occur in
10592 // practice that one of the condition inputs to the select is also one of
10593 // the outputs, we currently can't deal with this.
10594 if (User->getOpcode() == ISD::SELECT) {
10595 if (User->getOperand(0) == PromOps[i])
10597 } else if (User->getOpcode() == ISD::SELECT_CC) {
10598 if (User->getOperand(0) == PromOps[i] ||
10599 User->getOperand(1) == PromOps[i])
10605 // Replace all inputs with the extension operand.
10606 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10607 // Constants may have users outside the cluster of to-be-promoted nodes,
10608 // and so we need to replace those as we do the promotions.
10609 if (isa<ConstantSDNode>(Inputs[i]))
10612 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10615 std::list<HandleSDNode> PromOpHandles;
10616 for (auto &PromOp : PromOps)
10617 PromOpHandles.emplace_back(PromOp);
10619 // Replace all operations (these are all the same, but have a different
10620 // (i1) return type). DAG.getNode will validate that the types of
10621 // a binary operator match, so go through the list in reverse so that
10622 // we've likely promoted both operands first. Any intermediate truncations or
10623 // extensions disappear.
10624 while (!PromOpHandles.empty()) {
10625 SDValue PromOp = PromOpHandles.back().getValue();
10626 PromOpHandles.pop_back();
10628 if (PromOp.getOpcode() == ISD::TRUNCATE ||
10629 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10630 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10631 PromOp.getOpcode() == ISD::ANY_EXTEND) {
10632 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10633 PromOp.getOperand(0).getValueType() != MVT::i1) {
10634 // The operand is not yet ready (see comment below).
10635 PromOpHandles.emplace_front(PromOp);
10639 SDValue RepValue = PromOp.getOperand(0);
10640 if (isa<ConstantSDNode>(RepValue))
10641 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10643 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10648 switch (PromOp.getOpcode()) {
10649 default: C = 0; break;
10650 case ISD::SELECT: C = 1; break;
10651 case ISD::SELECT_CC: C = 2; break;
10654 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10655 PromOp.getOperand(C).getValueType() != MVT::i1) ||
10656 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10657 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10658 // The to-be-promoted operands of this node have not yet been
10659 // promoted (this should be rare because we're going through the
10660 // list backward, but if one of the operands has several users in
10661 // this cluster of to-be-promoted nodes, it is possible).
10662 PromOpHandles.emplace_front(PromOp);
10666 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10667 PromOp.getNode()->op_end());
10669 // If there are any constant inputs, make sure they're replaced now.
10670 for (unsigned i = 0; i < 2; ++i)
10671 if (isa<ConstantSDNode>(Ops[C+i]))
10672 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10674 DAG.ReplaceAllUsesOfValueWith(PromOp,
10675 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10678 // Now we're left with the initial truncation itself.
10679 if (N->getOpcode() == ISD::TRUNCATE)
10680 return N->getOperand(0);
10682 // Otherwise, this is a comparison. The operands to be compared have just
10683 // changed type (to i1), but everything else is the same.
10684 return SDValue(N, 0);
10687 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10688 DAGCombinerInfo &DCI) const {
10689 SelectionDAG &DAG = DCI.DAG;
10692 // If we're tracking CR bits, we need to be careful that we don't have:
10693 // zext(binary-ops(trunc(x), trunc(y)))
10695 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10696 // such that we're unnecessarily moving things into CR bits that can more
10697 // efficiently stay in GPRs. Note that if we're not certain that the high
10698 // bits are set as required by the final extension, we still may need to do
10699 // some masking to get the proper behavior.
10701 // This same functionality is important on PPC64 when dealing with
10702 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10703 // the return values of functions. Because it is so similar, it is handled
10706 if (N->getValueType(0) != MVT::i32 &&
10707 N->getValueType(0) != MVT::i64)
10710 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10711 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10714 if (N->getOperand(0).getOpcode() != ISD::AND &&
10715 N->getOperand(0).getOpcode() != ISD::OR &&
10716 N->getOperand(0).getOpcode() != ISD::XOR &&
10717 N->getOperand(0).getOpcode() != ISD::SELECT &&
10718 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10721 SmallVector<SDValue, 4> Inputs;
10722 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10723 SmallPtrSet<SDNode *, 16> Visited;
10725 // Visit all inputs, collect all binary operations (and, or, xor and
10726 // select) that are all fed by truncations.
10727 while (!BinOps.empty()) {
10728 SDValue BinOp = BinOps.back();
10731 if (!Visited.insert(BinOp.getNode()).second)
10734 PromOps.push_back(BinOp);
10736 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10737 // The condition of the select is not promoted.
10738 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10740 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10743 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10744 isa<ConstantSDNode>(BinOp.getOperand(i))) {
10745 Inputs.push_back(BinOp.getOperand(i));
10746 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10747 BinOp.getOperand(i).getOpcode() == ISD::OR ||
10748 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10749 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10750 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10751 BinOps.push_back(BinOp.getOperand(i));
10753 // We have an input that is not a truncation or another binary
10754 // operation; we'll abort this transformation.
10760 // The operands of a select that must be truncated when the select is
10761 // promoted because the operand is actually part of the to-be-promoted set.
10762 DenseMap<SDNode *, EVT> SelectTruncOp[2];
10764 // Make sure that this is a self-contained cluster of operations (which
10765 // is not quite the same thing as saying that everything has only one
10767 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10768 if (isa<ConstantSDNode>(Inputs[i]))
10771 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10772 UE = Inputs[i].getNode()->use_end();
10774 SDNode *User = *UI;
10775 if (User != N && !Visited.count(User))
10778 // If we're going to promote the non-output-value operand(s) or SELECT or
10779 // SELECT_CC, record them for truncation.
10780 if (User->getOpcode() == ISD::SELECT) {
10781 if (User->getOperand(0) == Inputs[i])
10782 SelectTruncOp[0].insert(std::make_pair(User,
10783 User->getOperand(0).getValueType()));
10784 } else if (User->getOpcode() == ISD::SELECT_CC) {
10785 if (User->getOperand(0) == Inputs[i])
10786 SelectTruncOp[0].insert(std::make_pair(User,
10787 User->getOperand(0).getValueType()));
10788 if (User->getOperand(1) == Inputs[i])
10789 SelectTruncOp[1].insert(std::make_pair(User,
10790 User->getOperand(1).getValueType()));
10795 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10796 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10797 UE = PromOps[i].getNode()->use_end();
10799 SDNode *User = *UI;
10800 if (User != N && !Visited.count(User))
10803 // If we're going to promote the non-output-value operand(s) or SELECT or
10804 // SELECT_CC, record them for truncation.
10805 if (User->getOpcode() == ISD::SELECT) {
10806 if (User->getOperand(0) == PromOps[i])
10807 SelectTruncOp[0].insert(std::make_pair(User,
10808 User->getOperand(0).getValueType()));
10809 } else if (User->getOpcode() == ISD::SELECT_CC) {
10810 if (User->getOperand(0) == PromOps[i])
10811 SelectTruncOp[0].insert(std::make_pair(User,
10812 User->getOperand(0).getValueType()));
10813 if (User->getOperand(1) == PromOps[i])
10814 SelectTruncOp[1].insert(std::make_pair(User,
10815 User->getOperand(1).getValueType()));
10820 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10821 bool ReallyNeedsExt = false;
10822 if (N->getOpcode() != ISD::ANY_EXTEND) {
10823 // If all of the inputs are not already sign/zero extended, then
10824 // we'll still need to do that at the end.
10825 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10826 if (isa<ConstantSDNode>(Inputs[i]))
10830 Inputs[i].getOperand(0).getValueSizeInBits();
10831 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10833 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10834 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10835 APInt::getHighBitsSet(OpBits,
10836 OpBits-PromBits))) ||
10837 (N->getOpcode() == ISD::SIGN_EXTEND &&
10838 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10839 (OpBits-(PromBits-1)))) {
10840 ReallyNeedsExt = true;
10846 // Replace all inputs, either with the truncation operand, or a
10847 // truncation or extension to the final output type.
10848 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10849 // Constant inputs need to be replaced with the to-be-promoted nodes that
10850 // use them because they might have users outside of the cluster of
10852 if (isa<ConstantSDNode>(Inputs[i]))
10855 SDValue InSrc = Inputs[i].getOperand(0);
10856 if (Inputs[i].getValueType() == N->getValueType(0))
10857 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10858 else if (N->getOpcode() == ISD::SIGN_EXTEND)
10859 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10860 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10861 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10862 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10863 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10865 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10866 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10869 std::list<HandleSDNode> PromOpHandles;
10870 for (auto &PromOp : PromOps)
10871 PromOpHandles.emplace_back(PromOp);
10873 // Replace all operations (these are all the same, but have a different
10874 // (promoted) return type). DAG.getNode will validate that the types of
10875 // a binary operator match, so go through the list in reverse so that
10876 // we've likely promoted both operands first.
10877 while (!PromOpHandles.empty()) {
10878 SDValue PromOp = PromOpHandles.back().getValue();
10879 PromOpHandles.pop_back();
10882 switch (PromOp.getOpcode()) {
10883 default: C = 0; break;
10884 case ISD::SELECT: C = 1; break;
10885 case ISD::SELECT_CC: C = 2; break;
10888 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10889 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10890 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10891 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10892 // The to-be-promoted operands of this node have not yet been
10893 // promoted (this should be rare because we're going through the
10894 // list backward, but if one of the operands has several users in
10895 // this cluster of to-be-promoted nodes, it is possible).
10896 PromOpHandles.emplace_front(PromOp);
10900 // For SELECT and SELECT_CC nodes, we do a similar check for any
10901 // to-be-promoted comparison inputs.
10902 if (PromOp.getOpcode() == ISD::SELECT ||
10903 PromOp.getOpcode() == ISD::SELECT_CC) {
10904 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10905 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10906 (SelectTruncOp[1].count(PromOp.getNode()) &&
10907 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10908 PromOpHandles.emplace_front(PromOp);
10913 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10914 PromOp.getNode()->op_end());
10916 // If this node has constant inputs, then they'll need to be promoted here.
10917 for (unsigned i = 0; i < 2; ++i) {
10918 if (!isa<ConstantSDNode>(Ops[C+i]))
10920 if (Ops[C+i].getValueType() == N->getValueType(0))
10923 if (N->getOpcode() == ISD::SIGN_EXTEND)
10924 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10925 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10926 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10928 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10931 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10932 // truncate them again to the original value type.
10933 if (PromOp.getOpcode() == ISD::SELECT ||
10934 PromOp.getOpcode() == ISD::SELECT_CC) {
10935 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10936 if (SI0 != SelectTruncOp[0].end())
10937 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10938 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10939 if (SI1 != SelectTruncOp[1].end())
10940 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10943 DAG.ReplaceAllUsesOfValueWith(PromOp,
10944 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10947 // Now we're left with the initial extension itself.
10948 if (!ReallyNeedsExt)
10949 return N->getOperand(0);
10951 // To zero extend, just mask off everything except for the first bit (in the
10953 if (N->getOpcode() == ISD::ZERO_EXTEND)
10954 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10955 DAG.getConstant(APInt::getLowBitsSet(
10956 N->getValueSizeInBits(0), PromBits),
10957 dl, N->getValueType(0)));
10959 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10960 "Invalid extension type");
10961 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10963 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10964 return DAG.getNode(
10965 ISD::SRA, dl, N->getValueType(0),
10966 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10970 /// \brief Reduces the number of fp-to-int conversion when building a vector.
10972 /// If this vector is built out of floating to integer conversions,
10973 /// transform it to a vector built out of floating point values followed by a
10974 /// single floating to integer conversion of the vector.
10975 /// Namely (build_vector (fptosi $A), (fptosi $B), ...)
10976 /// becomes (fptosi (build_vector ($A, $B, ...)))
10977 SDValue PPCTargetLowering::
10978 combineElementTruncationToVectorTruncation(SDNode *N,
10979 DAGCombinerInfo &DCI) const {
10980 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10981 "Should be called with a BUILD_VECTOR node");
10983 SelectionDAG &DAG = DCI.DAG;
10986 SDValue FirstInput = N->getOperand(0);
10987 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
10988 "The input operand must be an fp-to-int conversion.");
10990 // This combine happens after legalization so the fp_to_[su]i nodes are
10991 // already converted to PPCSISD nodes.
10992 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
10993 if (FirstConversion == PPCISD::FCTIDZ ||
10994 FirstConversion == PPCISD::FCTIDUZ ||
10995 FirstConversion == PPCISD::FCTIWZ ||
10996 FirstConversion == PPCISD::FCTIWUZ) {
10997 bool IsSplat = true;
10998 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
10999 FirstConversion == PPCISD::FCTIWUZ;
11000 EVT SrcVT = FirstInput.getOperand(0).getValueType();
11001 SmallVector<SDValue, 4> Ops;
11002 EVT TargetVT = N->getValueType(0);
11003 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11004 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
11006 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
11007 if (NextConversion != FirstConversion)
11009 if (N->getOperand(i) != FirstInput)
11013 // If this is a splat, we leave it as-is since there will be only a single
11014 // fp-to-int conversion followed by a splat of the integer. This is better
11015 // for 32-bit and smaller ints and neutral for 64-bit ints.
11019 // Now that we know we have the right type of node, get its operands
11020 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11021 SDValue In = N->getOperand(i).getOperand(0);
11022 // For 32-bit values, we need to add an FP_ROUND node.
11025 Ops.push_back(DAG.getUNDEF(SrcVT));
11027 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
11028 MVT::f32, In.getOperand(0),
11029 DAG.getIntPtrConstant(1, dl));
11030 Ops.push_back(Trunc);
11033 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
11037 if (FirstConversion == PPCISD::FCTIDZ ||
11038 FirstConversion == PPCISD::FCTIWZ)
11039 Opcode = ISD::FP_TO_SINT;
11041 Opcode = ISD::FP_TO_UINT;
11043 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
11044 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
11045 return DAG.getNode(Opcode, dl, TargetVT, BV);
11050 /// \brief Reduce the number of loads when building a vector.
11052 /// Building a vector out of multiple loads can be converted to a load
11053 /// of the vector type if the loads are consecutive. If the loads are
11054 /// consecutive but in descending order, a shuffle is added at the end
11055 /// to reorder the vector.
11056 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
11057 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11058 "Should be called with a BUILD_VECTOR node");
11061 bool InputsAreConsecutiveLoads = true;
11062 bool InputsAreReverseConsecutive = true;
11063 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
11064 SDValue FirstInput = N->getOperand(0);
11065 bool IsRoundOfExtLoad = false;
11067 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
11068 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
11069 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
11070 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
11072 // Not a build vector of (possibly fp_rounded) loads.
11073 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
11076 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
11077 // If any inputs are fp_round(extload), they all must be.
11078 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
11081 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11083 if (NextInput.getOpcode() != ISD::LOAD)
11086 SDValue PreviousInput =
11087 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11088 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11089 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11091 // If any inputs are fp_round(extload), they all must be.
11092 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11095 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11096 InputsAreConsecutiveLoads = false;
11097 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11098 InputsAreReverseConsecutive = false;
11100 // Exit early if the loads are neither consecutive nor reverse consecutive.
11101 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11105 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11106 "The loads cannot be both consecutive and reverse consecutive.");
11108 SDValue FirstLoadOp =
11109 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11110 SDValue LastLoadOp =
11111 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11112 N->getOperand(N->getNumOperands()-1);
11114 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11115 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11116 if (InputsAreConsecutiveLoads) {
11117 assert(LD1 && "Input needs to be a LoadSDNode.");
11118 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11119 LD1->getBasePtr(), LD1->getPointerInfo(),
11120 LD1->getAlignment());
11122 if (InputsAreReverseConsecutive) {
11123 assert(LDL && "Input needs to be a LoadSDNode.");
11124 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11125 LDL->getBasePtr(), LDL->getPointerInfo(),
11126 LDL->getAlignment());
11127 SmallVector<int, 16> Ops;
11128 for (int i = N->getNumOperands() - 1; i >= 0; i--)
11131 return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11132 DAG.getUNDEF(N->getValueType(0)), Ops);
11137 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11138 DAGCombinerInfo &DCI) const {
11139 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11140 "Should be called with a BUILD_VECTOR node");
11142 SelectionDAG &DAG = DCI.DAG;
11145 if (!Subtarget.hasVSX())
11148 // The target independent DAG combiner will leave a build_vector of
11149 // float-to-int conversions intact. We can generate MUCH better code for
11150 // a float-to-int conversion of a vector of floats.
11151 SDValue FirstInput = N->getOperand(0);
11152 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11153 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11158 // If we're building a vector out of consecutive loads, just load that
11160 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11164 if (N->getValueType(0) != MVT::v2f64)
11168 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11169 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11170 FirstInput.getOpcode() != ISD::UINT_TO_FP)
11172 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11173 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11175 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11178 SDValue Ext1 = FirstInput.getOperand(0);
11179 SDValue Ext2 = N->getOperand(1).getOperand(0);
11180 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11181 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11184 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11185 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11186 if (!Ext1Op || !Ext2Op)
11188 if (Ext1.getValueType() != MVT::i32 ||
11189 Ext2.getValueType() != MVT::i32)
11190 if (Ext1.getOperand(0) != Ext2.getOperand(0))
11193 int FirstElem = Ext1Op->getZExtValue();
11194 int SecondElem = Ext2Op->getZExtValue();
11196 if (FirstElem == 0 && SecondElem == 1)
11197 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11198 else if (FirstElem == 2 && SecondElem == 3)
11199 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11203 SDValue SrcVec = Ext1.getOperand(0);
11204 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11205 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11206 return DAG.getNode(NodeType, dl, MVT::v2f64,
11207 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11210 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11211 DAGCombinerInfo &DCI) const {
11212 assert((N->getOpcode() == ISD::SINT_TO_FP ||
11213 N->getOpcode() == ISD::UINT_TO_FP) &&
11214 "Need an int -> FP conversion node here");
11216 if (useSoftFloat() || !Subtarget.has64BitSupport())
11219 SelectionDAG &DAG = DCI.DAG;
11223 SDValue FirstOperand(Op.getOperand(0));
11224 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11225 (FirstOperand.getValueType() == MVT::i8 ||
11226 FirstOperand.getValueType() == MVT::i16);
11227 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11228 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11229 bool DstDouble = Op.getValueType() == MVT::f64;
11230 unsigned ConvOp = Signed ?
11231 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
11232 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11233 SDValue WidthConst =
11234 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11236 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11237 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11238 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11239 DAG.getVTList(MVT::f64, MVT::Other),
11240 Ops, MVT::i8, LDN->getMemOperand());
11242 // For signed conversion, we need to sign-extend the value in the VSR
11244 SDValue ExtOps[] = { Ld, WidthConst };
11245 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11246 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11248 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11251 // Don't handle ppc_fp128 here or i1 conversions.
11252 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11254 if (Op.getOperand(0).getValueType() == MVT::i1)
11257 // For i32 intermediate values, unfortunately, the conversion functions
11258 // leave the upper 32 bits of the value are undefined. Within the set of
11259 // scalar instructions, we have no method for zero- or sign-extending the
11260 // value. Thus, we cannot handle i32 intermediate values here.
11261 if (Op.getOperand(0).getValueType() == MVT::i32)
11264 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11265 "UINT_TO_FP is supported only with FPCVT");
11267 // If we have FCFIDS, then use it when converting to single-precision.
11268 // Otherwise, convert to double-precision and then round.
11269 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11270 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11272 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11274 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11278 // If we're converting from a float, to an int, and back to a float again,
11279 // then we don't need the store/load pair at all.
11280 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11281 Subtarget.hasFPCVT()) ||
11282 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11283 SDValue Src = Op.getOperand(0).getOperand(0);
11284 if (Src.getValueType() == MVT::f32) {
11285 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11286 DCI.AddToWorklist(Src.getNode());
11287 } else if (Src.getValueType() != MVT::f64) {
11288 // Make sure that we don't pick up a ppc_fp128 source value.
11293 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11296 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11297 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11299 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11300 FP = DAG.getNode(ISD::FP_ROUND, dl,
11301 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11302 DCI.AddToWorklist(FP.getNode());
11311 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11312 // builtins) into loads with swaps.
11313 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11314 DAGCombinerInfo &DCI) const {
11315 SelectionDAG &DAG = DCI.DAG;
11319 MachineMemOperand *MMO;
11321 switch (N->getOpcode()) {
11323 llvm_unreachable("Unexpected opcode for little endian VSX load");
11325 LoadSDNode *LD = cast<LoadSDNode>(N);
11326 Chain = LD->getChain();
11327 Base = LD->getBasePtr();
11328 MMO = LD->getMemOperand();
11329 // If the MMO suggests this isn't a load of a full vector, leave
11330 // things alone. For a built-in, we have to make the change for
11331 // correctness, so if there is a size problem that will be a bug.
11332 if (MMO->getSize() < 16)
11336 case ISD::INTRINSIC_W_CHAIN: {
11337 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11338 Chain = Intrin->getChain();
11339 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11340 // us what we want. Get operand 2 instead.
11341 Base = Intrin->getOperand(2);
11342 MMO = Intrin->getMemOperand();
11347 MVT VecTy = N->getValueType(0).getSimpleVT();
11349 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
11350 // aligned and the type is a vector with elements up to 4 bytes
11351 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11352 && VecTy.getScalarSizeInBits() <= 32 ) {
11356 SDValue LoadOps[] = { Chain, Base };
11357 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11358 DAG.getVTList(MVT::v2f64, MVT::Other),
11359 LoadOps, MVT::v2f64, MMO);
11361 DCI.AddToWorklist(Load.getNode());
11362 Chain = Load.getValue(1);
11363 SDValue Swap = DAG.getNode(
11364 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11365 DCI.AddToWorklist(Swap.getNode());
11367 // Add a bitcast if the resulting load type doesn't match v2f64.
11368 if (VecTy != MVT::v2f64) {
11369 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11370 DCI.AddToWorklist(N.getNode());
11371 // Package {bitcast value, swap's chain} to match Load's shape.
11372 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11373 N, Swap.getValue(1));
11379 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11380 // builtins) into stores with swaps.
11381 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11382 DAGCombinerInfo &DCI) const {
11383 SelectionDAG &DAG = DCI.DAG;
11388 MachineMemOperand *MMO;
11390 switch (N->getOpcode()) {
11392 llvm_unreachable("Unexpected opcode for little endian VSX store");
11394 StoreSDNode *ST = cast<StoreSDNode>(N);
11395 Chain = ST->getChain();
11396 Base = ST->getBasePtr();
11397 MMO = ST->getMemOperand();
11399 // If the MMO suggests this isn't a store of a full vector, leave
11400 // things alone. For a built-in, we have to make the change for
11401 // correctness, so if there is a size problem that will be a bug.
11402 if (MMO->getSize() < 16)
11406 case ISD::INTRINSIC_VOID: {
11407 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11408 Chain = Intrin->getChain();
11409 // Intrin->getBasePtr() oddly does not get what we want.
11410 Base = Intrin->getOperand(3);
11411 MMO = Intrin->getMemOperand();
11417 SDValue Src = N->getOperand(SrcOpnd);
11418 MVT VecTy = Src.getValueType().getSimpleVT();
11420 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
11421 // aligned and the type is a vector with elements up to 4 bytes
11422 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11423 && VecTy.getScalarSizeInBits() <= 32 ) {
11427 // All stores are done as v2f64 and possible bit cast.
11428 if (VecTy != MVT::v2f64) {
11429 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11430 DCI.AddToWorklist(Src.getNode());
11433 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11434 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11435 DCI.AddToWorklist(Swap.getNode());
11436 Chain = Swap.getValue(1);
11437 SDValue StoreOps[] = { Chain, Swap, Base };
11438 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11439 DAG.getVTList(MVT::Other),
11440 StoreOps, VecTy, MMO);
11441 DCI.AddToWorklist(Store.getNode());
11445 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11446 DAGCombinerInfo &DCI) const {
11447 SelectionDAG &DAG = DCI.DAG;
11449 switch (N->getOpcode()) {
11452 return combineSHL(N, DCI);
11454 return combineSRA(N, DCI);
11456 return combineSRL(N, DCI);
11458 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11459 return N->getOperand(0);
11462 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11463 return N->getOperand(0);
11466 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11467 if (C->isNullValue() || // 0 >>s V -> 0.
11468 C->isAllOnesValue()) // -1 >>s V -> -1.
11469 return N->getOperand(0);
11472 case ISD::SIGN_EXTEND:
11473 case ISD::ZERO_EXTEND:
11474 case ISD::ANY_EXTEND:
11475 return DAGCombineExtBoolTrunc(N, DCI);
11476 case ISD::TRUNCATE:
11478 case ISD::SELECT_CC:
11479 return DAGCombineTruncBoolExt(N, DCI);
11480 case ISD::SINT_TO_FP:
11481 case ISD::UINT_TO_FP:
11482 return combineFPToIntToFP(N, DCI);
11484 EVT Op1VT = N->getOperand(1).getValueType();
11485 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11486 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11488 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11489 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11490 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11491 ValidTypeForStoreFltAsInt &&
11492 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11493 SDValue Val = N->getOperand(1).getOperand(0);
11494 if (Val.getValueType() == MVT::f32) {
11495 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
11496 DCI.AddToWorklist(Val.getNode());
11498 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
11499 DCI.AddToWorklist(Val.getNode());
11501 if (Op1VT == MVT::i32) {
11503 N->getOperand(0), Val, N->getOperand(2),
11504 DAG.getValueType(N->getOperand(1).getValueType())
11507 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
11508 DAG.getVTList(MVT::Other), Ops,
11509 cast<StoreSDNode>(N)->getMemoryVT(),
11510 cast<StoreSDNode>(N)->getMemOperand());
11512 unsigned WidthInBytes =
11513 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
11514 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
11517 N->getOperand(0), Val, N->getOperand(2), WidthConst,
11518 DAG.getValueType(N->getOperand(1).getValueType())
11520 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
11521 DAG.getVTList(MVT::Other), Ops,
11522 cast<StoreSDNode>(N)->getMemoryVT(),
11523 cast<StoreSDNode>(N)->getMemOperand());
11526 DCI.AddToWorklist(Val.getNode());
11530 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
11531 if (cast<StoreSDNode>(N)->isUnindexed() &&
11532 N->getOperand(1).getOpcode() == ISD::BSWAP &&
11533 N->getOperand(1).getNode()->hasOneUse() &&
11534 (N->getOperand(1).getValueType() == MVT::i32 ||
11535 N->getOperand(1).getValueType() == MVT::i16 ||
11536 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11537 N->getOperand(1).getValueType() == MVT::i64))) {
11538 SDValue BSwapOp = N->getOperand(1).getOperand(0);
11539 // Do an any-extend to 32-bits if this is a half-word input.
11540 if (BSwapOp.getValueType() == MVT::i16)
11541 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
11543 // If the type of BSWAP operand is wider than stored memory width
11544 // it need to be shifted to the right side before STBRX.
11545 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
11546 if (Op1VT.bitsGT(mVT)) {
11547 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
11548 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
11549 DAG.getConstant(Shift, dl, MVT::i32));
11550 // Need to truncate if this is a bswap of i64 stored as i32/i16.
11551 if (Op1VT == MVT::i64)
11552 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
11556 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
11559 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
11560 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
11561 cast<StoreSDNode>(N)->getMemOperand());
11564 // For little endian, VSX stores require generating xxswapd/lxvd2x.
11565 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11566 EVT VT = N->getOperand(1).getValueType();
11567 if (VT.isSimple()) {
11568 MVT StoreVT = VT.getSimpleVT();
11569 if (Subtarget.needsSwapsForVSXMemOps() &&
11570 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
11571 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
11572 return expandVSXStoreForLE(N, DCI);
11577 LoadSDNode *LD = cast<LoadSDNode>(N);
11578 EVT VT = LD->getValueType(0);
11580 // For little endian, VSX loads require generating lxvd2x/xxswapd.
11581 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11582 if (VT.isSimple()) {
11583 MVT LoadVT = VT.getSimpleVT();
11584 if (Subtarget.needsSwapsForVSXMemOps() &&
11585 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
11586 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
11587 return expandVSXLoadForLE(N, DCI);
11590 // We sometimes end up with a 64-bit integer load, from which we extract
11591 // two single-precision floating-point numbers. This happens with
11592 // std::complex<float>, and other similar structures, because of the way we
11593 // canonicalize structure copies. However, if we lack direct moves,
11594 // then the final bitcasts from the extracted integer values to the
11595 // floating-point numbers turn into store/load pairs. Even with direct moves,
11596 // just loading the two floating-point numbers is likely better.
11597 auto ReplaceTwoFloatLoad = [&]() {
11598 if (VT != MVT::i64)
11601 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
11605 // We're looking for a sequence like this:
11606 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
11607 // t16: i64 = srl t13, Constant:i32<32>
11608 // t17: i32 = truncate t16
11609 // t18: f32 = bitcast t17
11610 // t19: i32 = truncate t13
11611 // t20: f32 = bitcast t19
11613 if (!LD->hasNUsesOfValue(2, 0))
11616 auto UI = LD->use_begin();
11617 while (UI.getUse().getResNo() != 0) ++UI;
11618 SDNode *Trunc = *UI++;
11619 while (UI.getUse().getResNo() != 0) ++UI;
11620 SDNode *RightShift = *UI;
11621 if (Trunc->getOpcode() != ISD::TRUNCATE)
11622 std::swap(Trunc, RightShift);
11624 if (Trunc->getOpcode() != ISD::TRUNCATE ||
11625 Trunc->getValueType(0) != MVT::i32 ||
11626 !Trunc->hasOneUse())
11628 if (RightShift->getOpcode() != ISD::SRL ||
11629 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
11630 RightShift->getConstantOperandVal(1) != 32 ||
11631 !RightShift->hasOneUse())
11634 SDNode *Trunc2 = *RightShift->use_begin();
11635 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
11636 Trunc2->getValueType(0) != MVT::i32 ||
11637 !Trunc2->hasOneUse())
11640 SDNode *Bitcast = *Trunc->use_begin();
11641 SDNode *Bitcast2 = *Trunc2->use_begin();
11643 if (Bitcast->getOpcode() != ISD::BITCAST ||
11644 Bitcast->getValueType(0) != MVT::f32)
11646 if (Bitcast2->getOpcode() != ISD::BITCAST ||
11647 Bitcast2->getValueType(0) != MVT::f32)
11650 if (Subtarget.isLittleEndian())
11651 std::swap(Bitcast, Bitcast2);
11653 // Bitcast has the second float (in memory-layout order) and Bitcast2
11654 // has the first one.
11656 SDValue BasePtr = LD->getBasePtr();
11657 if (LD->isIndexed()) {
11658 assert(LD->getAddressingMode() == ISD::PRE_INC &&
11659 "Non-pre-inc AM on PPC?");
11661 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11666 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11667 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11668 LD->getPointerInfo(), LD->getAlignment(),
11669 MMOFlags, LD->getAAInfo());
11671 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11672 BasePtr, DAG.getIntPtrConstant(4, dl));
11673 SDValue FloatLoad2 = DAG.getLoad(
11674 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11675 LD->getPointerInfo().getWithOffset(4),
11676 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11678 if (LD->isIndexed()) {
11679 // Note that DAGCombine should re-form any pre-increment load(s) from
11680 // what is produced here if that makes sense.
11681 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11684 DCI.CombineTo(Bitcast2, FloatLoad);
11685 DCI.CombineTo(Bitcast, FloatLoad2);
11687 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11688 SDValue(FloatLoad2.getNode(), 1));
11692 if (ReplaceTwoFloatLoad())
11693 return SDValue(N, 0);
11695 EVT MemVT = LD->getMemoryVT();
11696 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11697 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11698 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11699 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11700 if (LD->isUnindexed() && VT.isVector() &&
11701 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11702 // P8 and later hardware should just use LOAD.
11703 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11704 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11705 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11706 LD->getAlignment() >= ScalarABIAlignment)) &&
11707 LD->getAlignment() < ABIAlignment) {
11708 // This is a type-legal unaligned Altivec or QPX load.
11709 SDValue Chain = LD->getChain();
11710 SDValue Ptr = LD->getBasePtr();
11711 bool isLittleEndian = Subtarget.isLittleEndian();
11713 // This implements the loading of unaligned vectors as described in
11714 // the venerable Apple Velocity Engine overview. Specifically:
11715 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11716 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11718 // The general idea is to expand a sequence of one or more unaligned
11719 // loads into an alignment-based permutation-control instruction (lvsl
11720 // or lvsr), a series of regular vector loads (which always truncate
11721 // their input address to an aligned address), and a series of
11722 // permutations. The results of these permutations are the requested
11723 // loaded values. The trick is that the last "extra" load is not taken
11724 // from the address you might suspect (sizeof(vector) bytes after the
11725 // last requested load), but rather sizeof(vector) - 1 bytes after the
11726 // last requested vector. The point of this is to avoid a page fault if
11727 // the base address happened to be aligned. This works because if the
11728 // base address is aligned, then adding less than a full vector length
11729 // will cause the last vector in the sequence to be (re)loaded.
11730 // Otherwise, the next vector will be fetched as you might suspect was
11733 // We might be able to reuse the permutation generation from
11734 // a different base address offset from this one by an aligned amount.
11735 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11736 // optimization later.
11737 Intrinsic::ID Intr, IntrLD, IntrPerm;
11738 MVT PermCntlTy, PermTy, LDTy;
11739 if (Subtarget.hasAltivec()) {
11740 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
11741 Intrinsic::ppc_altivec_lvsl;
11742 IntrLD = Intrinsic::ppc_altivec_lvx;
11743 IntrPerm = Intrinsic::ppc_altivec_vperm;
11744 PermCntlTy = MVT::v16i8;
11745 PermTy = MVT::v4i32;
11748 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11749 Intrinsic::ppc_qpx_qvlpcls;
11750 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11751 Intrinsic::ppc_qpx_qvlfs;
11752 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11753 PermCntlTy = MVT::v4f64;
11754 PermTy = MVT::v4f64;
11755 LDTy = MemVT.getSimpleVT();
11758 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11760 // Create the new MMO for the new base load. It is like the original MMO,
11761 // but represents an area in memory almost twice the vector size centered
11762 // on the original address. If the address is unaligned, we might start
11763 // reading up to (sizeof(vector)-1) bytes below the address of the
11764 // original unaligned load.
11765 MachineFunction &MF = DAG.getMachineFunction();
11766 MachineMemOperand *BaseMMO =
11767 MF.getMachineMemOperand(LD->getMemOperand(),
11768 -(long)MemVT.getStoreSize()+1,
11769 2*MemVT.getStoreSize()-1);
11771 // Create the new base load.
11773 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11774 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11776 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11777 DAG.getVTList(PermTy, MVT::Other),
11778 BaseLoadOps, LDTy, BaseMMO);
11780 // Note that the value of IncOffset (which is provided to the next
11781 // load's pointer info offset value, and thus used to calculate the
11782 // alignment), and the value of IncValue (which is actually used to
11783 // increment the pointer value) are different! This is because we
11784 // require the next load to appear to be aligned, even though it
11785 // is actually offset from the base pointer by a lesser amount.
11786 int IncOffset = VT.getSizeInBits() / 8;
11787 int IncValue = IncOffset;
11789 // Walk (both up and down) the chain looking for another load at the real
11790 // (aligned) offset (the alignment of the other load does not matter in
11791 // this case). If found, then do not use the offset reduction trick, as
11792 // that will prevent the loads from being later combined (as they would
11793 // otherwise be duplicates).
11794 if (!findConsecutiveLoad(LD, DAG))
11797 SDValue Increment =
11798 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11799 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11801 MachineMemOperand *ExtraMMO =
11802 MF.getMachineMemOperand(LD->getMemOperand(),
11803 1, 2*MemVT.getStoreSize()-1);
11804 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11805 SDValue ExtraLoad =
11806 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11807 DAG.getVTList(PermTy, MVT::Other),
11808 ExtraLoadOps, LDTy, ExtraMMO);
11810 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11811 BaseLoad.getValue(1), ExtraLoad.getValue(1));
11813 // Because vperm has a big-endian bias, we must reverse the order
11814 // of the input vectors and complement the permute control vector
11815 // when generating little endian code. We have already handled the
11816 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11817 // and ExtraLoad here.
11819 if (isLittleEndian)
11820 Perm = BuildIntrinsicOp(IntrPerm,
11821 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11823 Perm = BuildIntrinsicOp(IntrPerm,
11824 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11827 Perm = Subtarget.hasAltivec() ?
11828 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11829 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11830 DAG.getTargetConstant(1, dl, MVT::i64));
11831 // second argument is 1 because this rounding
11832 // is always exact.
11834 // The output of the permutation is our loaded result, the TokenFactor is
11836 DCI.CombineTo(N, Perm, TF);
11837 return SDValue(N, 0);
11841 case ISD::INTRINSIC_WO_CHAIN: {
11842 bool isLittleEndian = Subtarget.isLittleEndian();
11843 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11844 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11845 : Intrinsic::ppc_altivec_lvsl);
11846 if ((IID == Intr ||
11847 IID == Intrinsic::ppc_qpx_qvlpcld ||
11848 IID == Intrinsic::ppc_qpx_qvlpcls) &&
11849 N->getOperand(1)->getOpcode() == ISD::ADD) {
11850 SDValue Add = N->getOperand(1);
11852 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11853 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11855 if (DAG.MaskedValueIsZero(Add->getOperand(1),
11856 APInt::getAllOnesValue(Bits /* alignment */)
11857 .zext(Add.getScalarValueSizeInBits()))) {
11858 SDNode *BasePtr = Add->getOperand(0).getNode();
11859 for (SDNode::use_iterator UI = BasePtr->use_begin(),
11860 UE = BasePtr->use_end();
11862 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11863 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11864 // We've found another LVSL/LVSR, and this address is an aligned
11865 // multiple of that one. The results will be the same, so use the
11866 // one we've just found instead.
11868 return SDValue(*UI, 0);
11873 if (isa<ConstantSDNode>(Add->getOperand(1))) {
11874 SDNode *BasePtr = Add->getOperand(0).getNode();
11875 for (SDNode::use_iterator UI = BasePtr->use_begin(),
11876 UE = BasePtr->use_end(); UI != UE; ++UI) {
11877 if (UI->getOpcode() == ISD::ADD &&
11878 isa<ConstantSDNode>(UI->getOperand(1)) &&
11879 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11880 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11881 (1ULL << Bits) == 0) {
11882 SDNode *OtherAdd = *UI;
11883 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11884 VE = OtherAdd->use_end(); VI != VE; ++VI) {
11885 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11886 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11887 return SDValue(*VI, 0);
11897 case ISD::INTRINSIC_W_CHAIN:
11898 // For little endian, VSX loads require generating lxvd2x/xxswapd.
11899 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11900 if (Subtarget.needsSwapsForVSXMemOps()) {
11901 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11904 case Intrinsic::ppc_vsx_lxvw4x:
11905 case Intrinsic::ppc_vsx_lxvd2x:
11906 return expandVSXLoadForLE(N, DCI);
11910 case ISD::INTRINSIC_VOID:
11911 // For little endian, VSX stores require generating xxswapd/stxvd2x.
11912 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11913 if (Subtarget.needsSwapsForVSXMemOps()) {
11914 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11917 case Intrinsic::ppc_vsx_stxvw4x:
11918 case Intrinsic::ppc_vsx_stxvd2x:
11919 return expandVSXStoreForLE(N, DCI);
11924 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11925 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11926 N->getOperand(0).hasOneUse() &&
11927 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11928 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11929 N->getValueType(0) == MVT::i64))) {
11930 SDValue Load = N->getOperand(0);
11931 LoadSDNode *LD = cast<LoadSDNode>(Load);
11932 // Create the byte-swapping load.
11934 LD->getChain(), // Chain
11935 LD->getBasePtr(), // Ptr
11936 DAG.getValueType(N->getValueType(0)) // VT
11939 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11940 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11941 MVT::i64 : MVT::i32, MVT::Other),
11942 Ops, LD->getMemoryVT(), LD->getMemOperand());
11944 // If this is an i16 load, insert the truncate.
11945 SDValue ResVal = BSLoad;
11946 if (N->getValueType(0) == MVT::i16)
11947 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11949 // First, combine the bswap away. This makes the value produced by the
11951 DCI.CombineTo(N, ResVal);
11953 // Next, combine the load away, we give it a bogus result value but a real
11954 // chain result. The result value is dead because the bswap is dead.
11955 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11957 // Return N so it doesn't get rechecked!
11958 return SDValue(N, 0);
11962 // If a VCMPo node already exists with exactly the same operands as this
11963 // node, use its result instead of this node (VCMPo computes both a CR6 and
11964 // a normal output).
11966 if (!N->getOperand(0).hasOneUse() &&
11967 !N->getOperand(1).hasOneUse() &&
11968 !N->getOperand(2).hasOneUse()) {
11970 // Scan all of the users of the LHS, looking for VCMPo's that match.
11971 SDNode *VCMPoNode = nullptr;
11973 SDNode *LHSN = N->getOperand(0).getNode();
11974 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11976 if (UI->getOpcode() == PPCISD::VCMPo &&
11977 UI->getOperand(1) == N->getOperand(1) &&
11978 UI->getOperand(2) == N->getOperand(2) &&
11979 UI->getOperand(0) == N->getOperand(0)) {
11984 // If there is no VCMPo node, or if the flag value has a single use, don't
11986 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11989 // Look at the (necessarily single) use of the flag value. If it has a
11990 // chain, this transformation is more complex. Note that multiple things
11991 // could use the value result, which we should ignore.
11992 SDNode *FlagUser = nullptr;
11993 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11994 FlagUser == nullptr; ++UI) {
11995 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11996 SDNode *User = *UI;
11997 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11998 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
12005 // If the user is a MFOCRF instruction, we know this is safe.
12006 // Otherwise we give up for right now.
12007 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
12008 return SDValue(VCMPoNode, 0);
12011 case ISD::BRCOND: {
12012 SDValue Cond = N->getOperand(1);
12013 SDValue Target = N->getOperand(2);
12015 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12016 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
12017 Intrinsic::ppc_is_decremented_ctr_nonzero) {
12019 // We now need to make the intrinsic dead (it cannot be instruction
12021 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
12022 assert(Cond.getNode()->hasOneUse() &&
12023 "Counter decrement has more than one use");
12025 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
12026 N->getOperand(0), Target);
12031 // If this is a branch on an altivec predicate comparison, lower this so
12032 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
12033 // lowering is done pre-legalize, because the legalizer lowers the predicate
12034 // compare down to code that is difficult to reassemble.
12035 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
12036 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
12038 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
12039 // value. If so, pass-through the AND to get to the intrinsic.
12040 if (LHS.getOpcode() == ISD::AND &&
12041 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12042 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
12043 Intrinsic::ppc_is_decremented_ctr_nonzero &&
12044 isa<ConstantSDNode>(LHS.getOperand(1)) &&
12045 !isNullConstant(LHS.getOperand(1)))
12046 LHS = LHS.getOperand(0);
12048 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12049 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
12050 Intrinsic::ppc_is_decremented_ctr_nonzero &&
12051 isa<ConstantSDNode>(RHS)) {
12052 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
12053 "Counter decrement comparison is not EQ or NE");
12055 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12056 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
12057 (CC == ISD::SETNE && !Val);
12059 // We now need to make the intrinsic dead (it cannot be instruction
12061 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
12062 assert(LHS.getNode()->hasOneUse() &&
12063 "Counter decrement has more than one use");
12065 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
12066 N->getOperand(0), N->getOperand(4));
12072 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12073 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
12074 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
12075 assert(isDot && "Can't compare against a vector result!");
12077 // If this is a comparison against something other than 0/1, then we know
12078 // that the condition is never/always true.
12079 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12080 if (Val != 0 && Val != 1) {
12081 if (CC == ISD::SETEQ) // Cond never true, remove branch.
12082 return N->getOperand(0);
12083 // Always !=, turn it into an unconditional branch.
12084 return DAG.getNode(ISD::BR, dl, MVT::Other,
12085 N->getOperand(0), N->getOperand(4));
12088 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
12090 // Create the PPCISD altivec 'dot' comparison node.
12092 LHS.getOperand(2), // LHS of compare
12093 LHS.getOperand(3), // RHS of compare
12094 DAG.getConstant(CompareOpc, dl, MVT::i32)
12096 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
12097 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12099 // Unpack the result based on how the target uses it.
12100 PPC::Predicate CompOpc;
12101 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12102 default: // Can't happen, don't crash on invalid number though.
12103 case 0: // Branch on the value of the EQ bit of CR6.
12104 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12106 case 1: // Branch on the inverted value of the EQ bit of CR6.
12107 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12109 case 2: // Branch on the value of the LT bit of CR6.
12110 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12112 case 3: // Branch on the inverted value of the LT bit of CR6.
12113 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12117 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12118 DAG.getConstant(CompOpc, dl, MVT::i32),
12119 DAG.getRegister(PPC::CR6, MVT::i32),
12120 N->getOperand(4), CompNode.getValue(1));
12124 case ISD::BUILD_VECTOR:
12125 return DAGCombineBuildVector(N, DCI);
12132 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12134 std::vector<SDNode *> *Created) const {
12135 // fold (sdiv X, pow2)
12136 EVT VT = N->getValueType(0);
12137 if (VT == MVT::i64 && !Subtarget.isPPC64())
12139 if ((VT != MVT::i32 && VT != MVT::i64) ||
12140 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12144 SDValue N0 = N->getOperand(0);
12146 bool IsNegPow2 = (-Divisor).isPowerOf2();
12147 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12148 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12150 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12152 Created->push_back(Op.getNode());
12155 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12157 Created->push_back(Op.getNode());
12163 //===----------------------------------------------------------------------===//
12164 // Inline Assembly Support
12165 //===----------------------------------------------------------------------===//
12167 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12169 const APInt &DemandedElts,
12170 const SelectionDAG &DAG,
12171 unsigned Depth) const {
12173 switch (Op.getOpcode()) {
12175 case PPCISD::LBRX: {
12176 // lhbrx is known to have the top bits cleared out.
12177 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12178 Known.Zero = 0xFFFF0000;
12181 case ISD::INTRINSIC_WO_CHAIN: {
12182 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12184 case Intrinsic::ppc_altivec_vcmpbfp_p:
12185 case Intrinsic::ppc_altivec_vcmpeqfp_p:
12186 case Intrinsic::ppc_altivec_vcmpequb_p:
12187 case Intrinsic::ppc_altivec_vcmpequh_p:
12188 case Intrinsic::ppc_altivec_vcmpequw_p:
12189 case Intrinsic::ppc_altivec_vcmpequd_p:
12190 case Intrinsic::ppc_altivec_vcmpgefp_p:
12191 case Intrinsic::ppc_altivec_vcmpgtfp_p:
12192 case Intrinsic::ppc_altivec_vcmpgtsb_p:
12193 case Intrinsic::ppc_altivec_vcmpgtsh_p:
12194 case Intrinsic::ppc_altivec_vcmpgtsw_p:
12195 case Intrinsic::ppc_altivec_vcmpgtsd_p:
12196 case Intrinsic::ppc_altivec_vcmpgtub_p:
12197 case Intrinsic::ppc_altivec_vcmpgtuh_p:
12198 case Intrinsic::ppc_altivec_vcmpgtuw_p:
12199 case Intrinsic::ppc_altivec_vcmpgtud_p:
12200 Known.Zero = ~1U; // All bits but the low one are known to be zero.
12207 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12208 switch (Subtarget.getDarwinDirective()) {
12211 case PPC::DIR_PWR4:
12212 case PPC::DIR_PWR5:
12213 case PPC::DIR_PWR5X:
12214 case PPC::DIR_PWR6:
12215 case PPC::DIR_PWR6X:
12216 case PPC::DIR_PWR7:
12217 case PPC::DIR_PWR8:
12218 case PPC::DIR_PWR9: {
12222 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12224 // For small loops (between 5 and 8 instructions), align to a 32-byte
12225 // boundary so that the entire loop fits in one instruction-cache line.
12226 uint64_t LoopSize = 0;
12227 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12228 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12229 LoopSize += TII->getInstSizeInBytes(*J);
12234 if (LoopSize > 16 && LoopSize <= 32)
12241 return TargetLowering::getPrefLoopAlignment(ML);
12244 /// getConstraintType - Given a constraint, return the type of
12245 /// constraint it is for this target.
12246 PPCTargetLowering::ConstraintType
12247 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12248 if (Constraint.size() == 1) {
12249 switch (Constraint[0]) {
12257 return C_RegisterClass;
12259 // FIXME: While Z does indicate a memory constraint, it specifically
12260 // indicates an r+r address (used in conjunction with the 'y' modifier
12261 // in the replacement string). Currently, we're forcing the base
12262 // register to be r0 in the asm printer (which is interpreted as zero)
12263 // and forming the complete address in the second register. This is
12267 } else if (Constraint == "wc") { // individual CR bits.
12268 return C_RegisterClass;
12269 } else if (Constraint == "wa" || Constraint == "wd" ||
12270 Constraint == "wf" || Constraint == "ws") {
12271 return C_RegisterClass; // VSX registers.
12273 return TargetLowering::getConstraintType(Constraint);
12276 /// Examine constraint type and operand type and determine a weight value.
12277 /// This object must already have been set up with the operand type
12278 /// and the current alternative constraint selected.
12279 TargetLowering::ConstraintWeight
12280 PPCTargetLowering::getSingleConstraintMatchWeight(
12281 AsmOperandInfo &info, const char *constraint) const {
12282 ConstraintWeight weight = CW_Invalid;
12283 Value *CallOperandVal = info.CallOperandVal;
12284 // If we don't have a value, we can't do a match,
12285 // but allow it at the lowest weight.
12286 if (!CallOperandVal)
12288 Type *type = CallOperandVal->getType();
12290 // Look at the constraint type.
12291 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12292 return CW_Register; // an individual CR bit.
12293 else if ((StringRef(constraint) == "wa" ||
12294 StringRef(constraint) == "wd" ||
12295 StringRef(constraint) == "wf") &&
12296 type->isVectorTy())
12297 return CW_Register;
12298 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12299 return CW_Register;
12301 switch (*constraint) {
12303 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12306 if (type->isIntegerTy())
12307 weight = CW_Register;
12310 if (type->isFloatTy())
12311 weight = CW_Register;
12314 if (type->isDoubleTy())
12315 weight = CW_Register;
12318 if (type->isVectorTy())
12319 weight = CW_Register;
12322 weight = CW_Register;
12325 weight = CW_Memory;
12331 std::pair<unsigned, const TargetRegisterClass *>
12332 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12333 StringRef Constraint,
12335 if (Constraint.size() == 1) {
12336 // GCC RS6000 Constraint Letters
12337 switch (Constraint[0]) {
12338 case 'b': // R1-R31
12339 if (VT == MVT::i64 && Subtarget.isPPC64())
12340 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12341 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12342 case 'r': // R0-R31
12343 if (VT == MVT::i64 && Subtarget.isPPC64())
12344 return std::make_pair(0U, &PPC::G8RCRegClass);
12345 return std::make_pair(0U, &PPC::GPRCRegClass);
12346 // 'd' and 'f' constraints are both defined to be "the floating point
12347 // registers", where one is for 32-bit and the other for 64-bit. We don't
12348 // really care overly much here so just give them all the same reg classes.
12351 if (VT == MVT::f32 || VT == MVT::i32)
12352 return std::make_pair(0U, &PPC::F4RCRegClass);
12353 if (VT == MVT::f64 || VT == MVT::i64)
12354 return std::make_pair(0U, &PPC::F8RCRegClass);
12355 if (VT == MVT::v4f64 && Subtarget.hasQPX())
12356 return std::make_pair(0U, &PPC::QFRCRegClass);
12357 if (VT == MVT::v4f32 && Subtarget.hasQPX())
12358 return std::make_pair(0U, &PPC::QSRCRegClass);
12361 if (VT == MVT::v4f64 && Subtarget.hasQPX())
12362 return std::make_pair(0U, &PPC::QFRCRegClass);
12363 if (VT == MVT::v4f32 && Subtarget.hasQPX())
12364 return std::make_pair(0U, &PPC::QSRCRegClass);
12365 if (Subtarget.hasAltivec())
12366 return std::make_pair(0U, &PPC::VRRCRegClass);
12368 return std::make_pair(0U, &PPC::CRRCRegClass);
12370 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12371 // An individual CR bit.
12372 return std::make_pair(0U, &PPC::CRBITRCRegClass);
12373 } else if ((Constraint == "wa" || Constraint == "wd" ||
12374 Constraint == "wf") && Subtarget.hasVSX()) {
12375 return std::make_pair(0U, &PPC::VSRCRegClass);
12376 } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12377 if (VT == MVT::f32 && Subtarget.hasP8Vector())
12378 return std::make_pair(0U, &PPC::VSSRCRegClass);
12380 return std::make_pair(0U, &PPC::VSFRCRegClass);
12383 std::pair<unsigned, const TargetRegisterClass *> R =
12384 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12386 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12387 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12388 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12390 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12391 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12392 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12393 PPC::GPRCRegClass.contains(R.first))
12394 return std::make_pair(TRI->getMatchingSuperReg(R.first,
12395 PPC::sub_32, &PPC::G8RCRegClass),
12396 &PPC::G8RCRegClass);
12398 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12399 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12400 R.first = PPC::CR0;
12401 R.second = &PPC::CRRCRegClass;
12407 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12408 /// vector. If it is invalid, don't add anything to Ops.
12409 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12410 std::string &Constraint,
12411 std::vector<SDValue>&Ops,
12412 SelectionDAG &DAG) const {
12415 // Only support length 1 constraints.
12416 if (Constraint.length() > 1) return;
12418 char Letter = Constraint[0];
12429 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12430 if (!CST) return; // Must be an immediate to match.
12432 int64_t Value = CST->getSExtValue();
12433 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12434 // numbers are printed as such.
12436 default: llvm_unreachable("Unknown constraint letter!");
12437 case 'I': // "I" is a signed 16-bit constant.
12438 if (isInt<16>(Value))
12439 Result = DAG.getTargetConstant(Value, dl, TCVT);
12441 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
12442 if (isShiftedUInt<16, 16>(Value))
12443 Result = DAG.getTargetConstant(Value, dl, TCVT);
12445 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
12446 if (isShiftedInt<16, 16>(Value))
12447 Result = DAG.getTargetConstant(Value, dl, TCVT);
12449 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
12450 if (isUInt<16>(Value))
12451 Result = DAG.getTargetConstant(Value, dl, TCVT);
12453 case 'M': // "M" is a constant that is greater than 31.
12455 Result = DAG.getTargetConstant(Value, dl, TCVT);
12457 case 'N': // "N" is a positive constant that is an exact power of two.
12458 if (Value > 0 && isPowerOf2_64(Value))
12459 Result = DAG.getTargetConstant(Value, dl, TCVT);
12461 case 'O': // "O" is the constant zero.
12463 Result = DAG.getTargetConstant(Value, dl, TCVT);
12465 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
12466 if (isInt<16>(-Value))
12467 Result = DAG.getTargetConstant(Value, dl, TCVT);
12474 if (Result.getNode()) {
12475 Ops.push_back(Result);
12479 // Handle standard constraint letters.
12480 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12483 // isLegalAddressingMode - Return true if the addressing mode represented
12484 // by AM is legal for this target, for a load/store of the specified type.
12485 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12486 const AddrMode &AM, Type *Ty,
12487 unsigned AS) const {
12488 // PPC does not allow r+i addressing modes for vectors!
12489 if (Ty->isVectorTy() && AM.BaseOffs != 0)
12492 // PPC allows a sign-extended 16-bit immediate field.
12493 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
12496 // No global is ever allowed as a base.
12500 // PPC only support r+r,
12501 switch (AM.Scale) {
12502 case 0: // "r+i" or just "i", depending on HasBaseReg.
12505 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
12507 // Otherwise we have r+r or r+i.
12510 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
12512 // Allow 2*r as r+r.
12515 // No other scales are supported.
12522 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
12523 SelectionDAG &DAG) const {
12524 MachineFunction &MF = DAG.getMachineFunction();
12525 MachineFrameInfo &MFI = MF.getFrameInfo();
12526 MFI.setReturnAddressIsTaken(true);
12528 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12532 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12534 // Make sure the function does not optimize away the store of the RA to
12536 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
12537 FuncInfo->setLRStoreRequired();
12538 bool isPPC64 = Subtarget.isPPC64();
12539 auto PtrVT = getPointerTy(MF.getDataLayout());
12542 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12544 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
12545 isPPC64 ? MVT::i64 : MVT::i32);
12546 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12547 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
12548 MachinePointerInfo());
12551 // Just load the return address off the stack.
12552 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
12553 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
12554 MachinePointerInfo());
12557 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
12558 SelectionDAG &DAG) const {
12560 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12562 MachineFunction &MF = DAG.getMachineFunction();
12563 MachineFrameInfo &MFI = MF.getFrameInfo();
12564 MFI.setFrameAddressIsTaken(true);
12566 EVT PtrVT = getPointerTy(MF.getDataLayout());
12567 bool isPPC64 = PtrVT == MVT::i64;
12569 // Naked functions never have a frame pointer, and so we use r1. For all
12570 // other functions, this decision must be delayed until during PEI.
12572 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
12573 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
12575 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
12577 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
12580 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
12581 FrameAddr, MachinePointerInfo());
12585 // FIXME? Maybe this could be a TableGen attribute on some registers and
12586 // this table could be generated automatically from RegInfo.
12587 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
12588 SelectionDAG &DAG) const {
12589 bool isPPC64 = Subtarget.isPPC64();
12590 bool isDarwinABI = Subtarget.isDarwinABI();
12592 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
12593 (!isPPC64 && VT != MVT::i32))
12594 report_fatal_error("Invalid register global variable type");
12596 bool is64Bit = isPPC64 && VT == MVT::i64;
12597 unsigned Reg = StringSwitch<unsigned>(RegName)
12598 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
12599 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
12600 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
12601 (is64Bit ? PPC::X13 : PPC::R13))
12606 report_fatal_error("Invalid register name global variable");
12610 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12611 // The PowerPC target isn't yet aware of offsets.
12615 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12617 unsigned Intrinsic) const {
12618 switch (Intrinsic) {
12619 case Intrinsic::ppc_qpx_qvlfd:
12620 case Intrinsic::ppc_qpx_qvlfs:
12621 case Intrinsic::ppc_qpx_qvlfcd:
12622 case Intrinsic::ppc_qpx_qvlfcs:
12623 case Intrinsic::ppc_qpx_qvlfiwa:
12624 case Intrinsic::ppc_qpx_qvlfiwz:
12625 case Intrinsic::ppc_altivec_lvx:
12626 case Intrinsic::ppc_altivec_lvxl:
12627 case Intrinsic::ppc_altivec_lvebx:
12628 case Intrinsic::ppc_altivec_lvehx:
12629 case Intrinsic::ppc_altivec_lvewx:
12630 case Intrinsic::ppc_vsx_lxvd2x:
12631 case Intrinsic::ppc_vsx_lxvw4x: {
12633 switch (Intrinsic) {
12634 case Intrinsic::ppc_altivec_lvebx:
12637 case Intrinsic::ppc_altivec_lvehx:
12640 case Intrinsic::ppc_altivec_lvewx:
12643 case Intrinsic::ppc_vsx_lxvd2x:
12646 case Intrinsic::ppc_qpx_qvlfd:
12649 case Intrinsic::ppc_qpx_qvlfs:
12652 case Intrinsic::ppc_qpx_qvlfcd:
12655 case Intrinsic::ppc_qpx_qvlfcs:
12663 Info.opc = ISD::INTRINSIC_W_CHAIN;
12665 Info.ptrVal = I.getArgOperand(0);
12666 Info.offset = -VT.getStoreSize()+1;
12667 Info.size = 2*VT.getStoreSize()-1;
12670 Info.readMem = true;
12671 Info.writeMem = false;
12674 case Intrinsic::ppc_qpx_qvlfda:
12675 case Intrinsic::ppc_qpx_qvlfsa:
12676 case Intrinsic::ppc_qpx_qvlfcda:
12677 case Intrinsic::ppc_qpx_qvlfcsa:
12678 case Intrinsic::ppc_qpx_qvlfiwaa:
12679 case Intrinsic::ppc_qpx_qvlfiwza: {
12681 switch (Intrinsic) {
12682 case Intrinsic::ppc_qpx_qvlfda:
12685 case Intrinsic::ppc_qpx_qvlfsa:
12688 case Intrinsic::ppc_qpx_qvlfcda:
12691 case Intrinsic::ppc_qpx_qvlfcsa:
12699 Info.opc = ISD::INTRINSIC_W_CHAIN;
12701 Info.ptrVal = I.getArgOperand(0);
12703 Info.size = VT.getStoreSize();
12706 Info.readMem = true;
12707 Info.writeMem = false;
12710 case Intrinsic::ppc_qpx_qvstfd:
12711 case Intrinsic::ppc_qpx_qvstfs:
12712 case Intrinsic::ppc_qpx_qvstfcd:
12713 case Intrinsic::ppc_qpx_qvstfcs:
12714 case Intrinsic::ppc_qpx_qvstfiw:
12715 case Intrinsic::ppc_altivec_stvx:
12716 case Intrinsic::ppc_altivec_stvxl:
12717 case Intrinsic::ppc_altivec_stvebx:
12718 case Intrinsic::ppc_altivec_stvehx:
12719 case Intrinsic::ppc_altivec_stvewx:
12720 case Intrinsic::ppc_vsx_stxvd2x:
12721 case Intrinsic::ppc_vsx_stxvw4x: {
12723 switch (Intrinsic) {
12724 case Intrinsic::ppc_altivec_stvebx:
12727 case Intrinsic::ppc_altivec_stvehx:
12730 case Intrinsic::ppc_altivec_stvewx:
12733 case Intrinsic::ppc_vsx_stxvd2x:
12736 case Intrinsic::ppc_qpx_qvstfd:
12739 case Intrinsic::ppc_qpx_qvstfs:
12742 case Intrinsic::ppc_qpx_qvstfcd:
12745 case Intrinsic::ppc_qpx_qvstfcs:
12753 Info.opc = ISD::INTRINSIC_VOID;
12755 Info.ptrVal = I.getArgOperand(1);
12756 Info.offset = -VT.getStoreSize()+1;
12757 Info.size = 2*VT.getStoreSize()-1;
12760 Info.readMem = false;
12761 Info.writeMem = true;
12764 case Intrinsic::ppc_qpx_qvstfda:
12765 case Intrinsic::ppc_qpx_qvstfsa:
12766 case Intrinsic::ppc_qpx_qvstfcda:
12767 case Intrinsic::ppc_qpx_qvstfcsa:
12768 case Intrinsic::ppc_qpx_qvstfiwa: {
12770 switch (Intrinsic) {
12771 case Intrinsic::ppc_qpx_qvstfda:
12774 case Intrinsic::ppc_qpx_qvstfsa:
12777 case Intrinsic::ppc_qpx_qvstfcda:
12780 case Intrinsic::ppc_qpx_qvstfcsa:
12788 Info.opc = ISD::INTRINSIC_VOID;
12790 Info.ptrVal = I.getArgOperand(1);
12792 Info.size = VT.getStoreSize();
12795 Info.readMem = false;
12796 Info.writeMem = true;
12806 /// getOptimalMemOpType - Returns the target specific optimal type for load
12807 /// and store operations as a result of memset, memcpy, and memmove
12808 /// lowering. If DstAlign is zero that means it's safe to destination
12809 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12810 /// means there isn't a need to check it against alignment requirement,
12811 /// probably because the source does not need to be loaded. If 'IsMemset' is
12812 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12813 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12814 /// source is constant so it does not need to be loaded.
12815 /// It returns EVT::Other if the type should be determined using generic
12816 /// target-independent logic.
12817 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12818 unsigned DstAlign, unsigned SrcAlign,
12819 bool IsMemset, bool ZeroMemset,
12821 MachineFunction &MF) const {
12822 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12823 const Function *F = MF.getFunction();
12824 // When expanding a memset, require at least two QPX instructions to cover
12825 // the cost of loading the value to be stored from the constant pool.
12826 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12827 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12828 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12832 // We should use Altivec/VSX loads and stores when available. For unaligned
12833 // addresses, unaligned VSX loads are only fast starting with the P8.
12834 if (Subtarget.hasAltivec() && Size >= 16 &&
12835 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12836 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12840 if (Subtarget.isPPC64()) {
12847 /// \brief Returns true if it is beneficial to convert a load of a constant
12848 /// to just the constant itself.
12849 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12851 assert(Ty->isIntegerTy());
12853 unsigned BitSize = Ty->getPrimitiveSizeInBits();
12854 return !(BitSize == 0 || BitSize > 64);
12857 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12858 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12860 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12861 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12862 return NumBits1 == 64 && NumBits2 == 32;
12865 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12866 if (!VT1.isInteger() || !VT2.isInteger())
12868 unsigned NumBits1 = VT1.getSizeInBits();
12869 unsigned NumBits2 = VT2.getSizeInBits();
12870 return NumBits1 == 64 && NumBits2 == 32;
12873 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12874 // Generally speaking, zexts are not free, but they are free when they can be
12875 // folded with other operations.
12876 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12877 EVT MemVT = LD->getMemoryVT();
12878 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12879 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12880 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12881 LD->getExtensionType() == ISD::ZEXTLOAD))
12885 // FIXME: Add other cases...
12886 // - 32-bit shifts with a zext to i64
12887 // - zext after ctlz, bswap, etc.
12888 // - zext after and by a constant mask
12890 return TargetLowering::isZExtFree(Val, VT2);
12893 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12894 assert(VT.isFloatingPoint());
12898 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12899 return isInt<16>(Imm) || isUInt<16>(Imm);
12902 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12903 return isInt<16>(Imm) || isUInt<16>(Imm);
12906 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12909 bool *Fast) const {
12910 if (DisablePPCUnaligned)
12913 // PowerPC supports unaligned memory access for simple non-vector types.
12914 // Although accessing unaligned addresses is not as efficient as accessing
12915 // aligned addresses, it is generally more efficient than manual expansion,
12916 // and generally only traps for software emulation when crossing page
12919 if (!VT.isSimple())
12922 if (VT.getSimpleVT().isVector()) {
12923 if (Subtarget.hasVSX()) {
12924 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12925 VT != MVT::v4f32 && VT != MVT::v4i32)
12932 if (VT == MVT::ppcf128)
12941 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12942 VT = VT.getScalarType();
12944 if (!VT.isSimple())
12947 switch (VT.getSimpleVT().SimpleTy) {
12959 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12960 // LR is a callee-save register, but we must treat it as clobbered by any call
12961 // site. Hence we include LR in the scratch registers, which are in turn added
12962 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12963 // to CTR, which is used by any indirect call.
12964 static const MCPhysReg ScratchRegs[] = {
12965 PPC::X12, PPC::LR8, PPC::CTR8, 0
12968 return ScratchRegs;
12971 unsigned PPCTargetLowering::getExceptionPointerRegister(
12972 const Constant *PersonalityFn) const {
12973 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12976 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12977 const Constant *PersonalityFn) const {
12978 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12982 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12983 EVT VT , unsigned DefinedValues) const {
12984 if (VT == MVT::v2i64)
12985 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12987 if (Subtarget.hasVSX() || Subtarget.hasQPX())
12990 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12993 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12994 if (DisableILPPref || Subtarget.enableMachineScheduler())
12995 return TargetLowering::getSchedulingPreference(N);
13000 // Create a fast isel object.
13002 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
13003 const TargetLibraryInfo *LibInfo) const {
13004 return PPC::createFastISel(FuncInfo, LibInfo);
13007 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13008 if (Subtarget.isDarwinABI()) return;
13009 if (!Subtarget.isPPC64()) return;
13011 // Update IsSplitCSR in PPCFunctionInfo
13012 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
13013 PFI->setIsSplitCSR(true);
13016 void PPCTargetLowering::insertCopiesSplitCSR(
13017 MachineBasicBlock *Entry,
13018 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13019 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13020 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13024 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13025 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13026 MachineBasicBlock::iterator MBBI = Entry->begin();
13027 for (const MCPhysReg *I = IStart; *I; ++I) {
13028 const TargetRegisterClass *RC = nullptr;
13029 if (PPC::G8RCRegClass.contains(*I))
13030 RC = &PPC::G8RCRegClass;
13031 else if (PPC::F8RCRegClass.contains(*I))
13032 RC = &PPC::F8RCRegClass;
13033 else if (PPC::CRRCRegClass.contains(*I))
13034 RC = &PPC::CRRCRegClass;
13035 else if (PPC::VRRCRegClass.contains(*I))
13036 RC = &PPC::VRRCRegClass;
13038 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13040 unsigned NewVR = MRI->createVirtualRegister(RC);
13041 // Create copy from CSR to a virtual register.
13042 // FIXME: this currently does not emit CFI pseudo-instructions, it works
13043 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13044 // nounwind. If we want to generalize this later, we may need to emit
13045 // CFI pseudo-instructions.
13046 assert(Entry->getParent()->getFunction()->hasFnAttribute(
13047 Attribute::NoUnwind) &&
13048 "Function should be nounwind in insertCopiesSplitCSR!");
13049 Entry->addLiveIn(*I);
13050 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13053 // Insert the copy-back instructions right before the terminator
13054 for (auto *Exit : Exits)
13055 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13056 TII->get(TargetOpcode::COPY), *I)
13061 // Override to enable LOAD_STACK_GUARD lowering on Linux.
13062 bool PPCTargetLowering::useLoadStackGuardNode() const {
13063 if (!Subtarget.isTargetLinux())
13064 return TargetLowering::useLoadStackGuardNode();
13068 // Override to disable global variable loading on Linux.
13069 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
13070 if (!Subtarget.isTargetLinux())
13071 return TargetLowering::insertSSPDeclarations(M);
13074 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13075 if (!VT.isSimple() || !Subtarget.hasVSX())
13078 switch(VT.getSimpleVT().SimpleTy) {
13080 // For FP types that are currently not supported by PPC backend, return
13081 // false. Examples: f16, f80.
13086 return Imm.isPosZero();
13090 // For vector shift operation op, fold
13091 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
13092 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
13093 SelectionDAG &DAG) {
13094 SDValue N0 = N->getOperand(0);
13095 SDValue N1 = N->getOperand(1);
13096 EVT VT = N0.getValueType();
13097 unsigned OpSizeInBits = VT.getScalarSizeInBits();
13098 unsigned Opcode = N->getOpcode();
13099 unsigned TargetOpcode;
13103 llvm_unreachable("Unexpected shift operation");
13105 TargetOpcode = PPCISD::SHL;
13108 TargetOpcode = PPCISD::SRL;
13111 TargetOpcode = PPCISD::SRA;
13115 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13116 N1->getOpcode() == ISD::AND)
13117 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13118 if (Mask->getZExtValue() == OpSizeInBits - 1)
13119 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13124 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13125 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13131 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13132 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13138 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13139 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))